<?php

// app/Http/Controllers/SubscriptionController.php

namespace App\Http\Controllers;

use App\Services\SubscriptionService;
use App\Models\Subscription;
use Illuminate\Http\Request;
use App\Services\SafeHavenService;
use App\Models\Member;
use App\Models\CouponTransaction;
use App\Models\Coupon;
use Carbon\Carbon;
use App\Notifications\SubscriptionActivated;

class SubscriptionController extends Controller
{
    public function create(Request $request, SubscriptionService $service)
    {
        $request->validate([
            'type' => 'required|in:daily,weekly,monthly'
        ]);

        $subscription = $service->createSubscription($request->type);

        return response()->json([
            'message' => 'Subscription created, proceed to payment.',
            'data' => [
                'reference' => $subscription->reference,
                'amount' => $subscription->amount,
                'duration' => $subscription->duration,
                'start_date' => $subscription->start_date,
                'end_date' => $subscription->end_date,
                'status' => 'pending'
            ]
        ]);
    }

    public function verifyTransaction($transactionId) {
        $subscription = Subscription::where("reference", $transactionId)->first();

        if ($subscription == null) {
            return response()->json(["message" => "Invalid reference"], 400);
        }

        if ($subscription->active  == Subscription::PAID) {
            return response()->json([
                "message" => "Successful",
                "data" => $subscription
            ], 200);
        }

        $response = (new SafeHavenService())->verifyTransaction($transactionId);
        // return $response;
        if ($response == null) {
            return response()->json(["message" => "Invalid provider response"], 400);
        }

        if ($response["statusCode"] != 200) {
            return response()->json(["message" => $response["message"]], 400);
        }

        if ($response["data"]["status"] != 'Paid') {
            return response()->json(["message" => "Not Paid"], 400);
        }
        $subscription->update([
            "active" => Subscription::PAID
        ]);
        $member = Member::where("id", $subscription->member_id)->first();

        $member->update([
            "next_subscription_date" =>  $subscription->end_date
        ]);

        try {
            $member->notify(new SubscriptionActivated($subscription->end_date));
        } catch (\Exception $e) {
            logger()->error("Notification failed: " . $e->getMessage());
        }

        return response()->json([
            "message" => "Successful",
            "data" => $subscription
        ], 200);
    }


    public function subscribeWithCoupon(Request $request) {
        $request->validate([
            "coupon" => "required|string|exists:cupon,coupon_code",
        ]);
        $cupon = Coupon::where("coupon_code", $request->coupon)->first();

        $couponTransaction = CouponTransaction::where("coupon_id", $cupon->id)->where("member_id", auth("member")->user()->id)->first();

        if ($couponTransaction != null) {
            return response()->json(["message" => "Coupon already used"], 400);
        }

        $now = Carbon::now();
        $startDate = Carbon::parse($cupon->start_date)->subMinute();
        $endDate = Carbon::parse($cupon->end_date);
        if (!$now->between($startDate, $endDate)) {
            return response()->json([
                "message" => "Coupon expired. Valid between {$startDate->toDateString()} {$now->toDateString()} {$endDate->toDateString()}"
            ], 400);
        }

        $newCouponTransaction = CouponTransaction::create([
            "coupon_id" => $cupon->id,
            "member_id" => auth("member")->user()->id,
        ]);

        $member = Member::where("id", auth("member")->user()->id)->first();

        $member->update([
            "next_subscription_date" => $cupon->end_date // Adjust logic as needed
        ]);


        try {
            $member->notify(new SubscriptionActivated($cupon->end_date));
        } catch (\Exception $e) {
            logger()->error("Notification failed: " . $e->getMessage());
        }

        return response()->json([
            "message" => "Successful",
            "dsd" => $request->all(),
            "data" => auth("member")->user()
        ], 200);
    }

}

