<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\Law;
use App\Models\Notification;
use App\Models\RecentArt;
use App\Models\UserSubscriber;
use App\Services\AppMarketPurchaseVerifier;
use App\Traits\BaseApiResponse;

class HomeController extends Controller
{
    use BaseApiResponse;

    public function __construct(private AppMarketPurchaseVerifier $marketVerifier)
    {
    }

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

        $this->refreshMarketSubscription($user);

        $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
            ];
        });

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

        $current_plan = null;

        if ($freeSubscription) {
            $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()
            ->where('expired_at', '>=', now())
            ->latest('expired_at')
            ->first();

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

        if ($latestSubscription) {
            $current_plan = [
                'id' => $latestSubscription->id,
                'name' => $latestSubscription->subscribe->name ?? 'Subscription',
                'price' => $latestSubscription->subscribe->price ?? 100,
                'expired_day' => $expiredDays,
                'is_free' => (bool) $latestSubscription->is_free
            ];
        }

        $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,
        ]);
    }

    private function refreshMarketSubscription($user): void
    {
        $bazaarSubscription = $user->userSubscribers()
            ->whereNotNull('purchase_token')
            ->whereNotNull('subscription_id')
            ->where(function ($query) {
                $query->where('market_provider', 'bazaar')
                    ->orWhereNull('market_provider');
            })
            ->latest()
            ->first();

        if ($bazaarSubscription && $this->marketVerifier->refreshBazaarSubscriber($bazaarSubscription)) {
            return;
        }

        $myketSubscription = $user->userSubscribers()
            ->where('market_provider', 'myket')
            ->whereNotNull('purchase_token')
            ->whereNotNull('product_id')
            ->latest()
            ->first();

        if ($myketSubscription) {
            $this->marketVerifier->refreshMyketSubscriber($myketSubscription);
        }
    }
}
