<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
// 1. IMPORT THE JOB WE CREATED
use App\Jobs\CheckBazaarSubscription;

// These are your existing imports
use App\Models\Law;
use App\Models\Notification;
use App\Models\RecentArt;
use App\Models\UserSubscriber;
use App\Traits\BaseApiResponse;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class HomeController extends Controller
{
    use BaseApiResponse;

    public function index()
    {
        $user = auth()->user();

        // 2. DISPATCH THE JOB AT THE VERY BEGINNING
        // ===================================================================
        // Find the user's latest subscription that has a purchase token
        $latestSubscription = $user->userSubscribers()->whereNotNull('purchase_token')->latest()->first();

        // If such a subscription exists, create a new job and hand it to the queue
        // if ($latestSubscription) {
        //     CheckBazaarSubscription::dispatch($latestSubscription);
        // }
        // ===================================================================
        // Your API now continues immediately without waiting for the check to finish.


        // --- ALL THE REST OF YOUR CODE REMAINS EXACTLY THE SAME ---

        $recent = RecentArt::query()->where('user_id', $user->id)->get()->map(function ($q) {
            return [
                'id' => $q->law?->id,
                'name' => $q->law?->title,
                'is_locked' => $q->law?->is_locked
            ];
        });

        $laws = Law::orderBy('created_at')->get()->map(function ($q) {
            return [
                'id' => $q->id,
                'name' => $q->title,
                'is_locked' => $q->is_locked
            ];
        });

        $categories = ['hagigi', 'kifari'];
        $lawsByCategory = [];

        foreach ($categories as $category) {
            $lawsByCategory[$category] = Law::whereHas('category', function ($q) use ($category) {
                $q->where('type', $category);
            })->get()->map(function ($q) {
                return [
                    "id" => $q->id,
                    "title" => $q->title,
                    "is_locked" => $q->is_locked,
                    "category_id" => $q->category_id,
                    "price" => $q->price,
                    "image" => $q->image,
                    "type" => 'law'
                ];
            });
        }

        $free_law = Law::where('is_locked', false)->orderBy('created_at')->get()->map(function ($q) {
            return [
                'id' => $q->id,
                'name' => $q->title,
                'is_locked' => $q->is_locked
            ];
        });

        $current_plan = null;

        $freeSubscription = $user->userSubscribers()
            ->whereHas('subscribe', function ($query) {
                $query->where('is_free', true);
            })
            ->where('expired_at', '>=', now())
            ->first();

        $expiredAt = null;
        $current_plan = null;

        if ($freeSubscription) {
            $expiredAt = $freeSubscription->expired_at;
            $current_plan = [
                'id' => $freeSubscription->id,
                'name' => $freeSubscription->subscribe->name,
                'price' => $freeSubscription->subscribe->price,
                'expired_day' => $freeSubscription->expired_at->diffInDays(now()),
                'is_free' => true
            ];
        }

        $latestSubscription = $user->userSubscribers()->latest()->first();

        $expiredDays = UserSubscriber::query()->where('user_id', $user->id)->where('expired_at', '>=', now())->get()->sum(function ($subscriber) {return $subscriber->expired_at->diffInDays(now());});

        $purchase_token = $latestSubscription?->purchase_token;
        $current_plan = [
            'id' => $latestSubscription->id,
            'name' => $latestSubscription->subscribe->name ?? 'Subscription',
            'price' => $latestSubscription->subscribe->price ?? 100,
            'expired_day' => $expiredDays,
            'is_free' => false
        ];

        $unread_notifications_count = Notification::unreadForUser($user->id)->count();

        return $this->success([
            'recent' => $recent,
            'laws' => $lawsByCategory,
            'last_law' => $laws,
            'free' => $free_law,
            'current_plan' => $current_plan,
            'unread_notifications_count' => $unread_notifications_count,
        ]);
    }
}
