<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\MatchPrediction;
use Carbon\Carbon;
use Illuminate\Http\Request;

class MatchPredictionController extends Controller
{
    /**
     * Return predictions for a given date (defaults to today).
     *
     * Access rules:
     *  - History (any past date): all predictions fully visible (is_locked = false).
     *  - Today:
     *      - Free package (layout_name = 'free') → always visible.
     *      - VIP packages → visible only if the authenticated user has an
     *        active row in user_subscriptions for that vip_package_id.
     *        Otherwise locked. Unauthenticated users always get locked VIP predictions.
     *
     * This approach is fully dynamic: any package an admin creates/deletes is
     * automatically handled without schema or code changes.
     *
     * GET /api/predictions?date=YYYY-MM-DD
     */
    public function index(Request $request)
    {
        $date    = $request->query('date', Carbon::today()->toDateString());
        $today   = Carbon::today()->toDateString();
        $isToday = $date === $today;

        // Optionally authenticate — Sanctum resolves the Bearer token on this public route
        $user = $request->user('sanctum');

        // Pre-load the user's active subscriptions in one query to avoid N+1
        $activePackageIds = collect();
        if ($user) {
            $activePackageIds = $user->activeSubscriptions()->pluck('vip_package_id');
        }

        $predictions = MatchPrediction::with('vipPackage')
            ->whereDate('prediction_date', $date)
            ->get();

        // Split: free predictions (layout_name = 'free') vs VIP
        $free = $predictions
            ->filter(fn($p) => $p->vipPackage && $p->vipPackage->layout_name === 'free')
            ->values()
            ->map(fn($p) => $this->formatPrediction($p, isLocked: false));

        $vip = $predictions
            ->filter(fn($p) => $p->vipPackage && $p->vipPackage->layout_name !== 'free')
            ->values()
            ->map(function ($p) use ($isToday, $activePackageIds) {
                // History: never locked
                if (!$isToday) {
                    return $this->formatPrediction($p, isLocked: false);
                }

                // Today: locked unless user has an active subscription for this package
                $locked = !$activePackageIds->contains($p->vip_package_id);
                return $this->formatPrediction($p, isLocked: $locked);
            });

        return response()->json([
            'date'             => $date,
            'free_predictions' => $free,
            'vip_predictions'  => $vip,
        ]);
    }

    /**
     * Return a performance history summary for the past N days.
     * All past days are free — just shows the win/loss signal.
     * Today is always appended as "locked" (pending predictions).
     *
     * GET /api/predictions/history?days=5
     */
    public function history(Request $request)
    {
        $days  = (int) $request->query('days', 5);
        $today = Carbon::today();

        $summary = [];

        for ($i = $days; $i >= 1; $i--) {
            $date    = $today->copy()->subDays($i);
            $dateStr = $date->toDateString();

            // Consider ALL predictions for that day to give an accurate overall signal
            $dayPredictions = MatchPrediction::whereDate('prediction_date', $dateStr)->get();

            $hasWon = $dayPredictions->contains('status', 'won');
            $hasLost = $dayPredictions->contains('status', 'lost');
            $isWin  = $dayPredictions->count() > 0 && $hasWon && !$hasLost;

            $summary[] = [
                'date'      => $dateStr,
                'label'     => $date->format('j M'),
                'is_win'    => $dayPredictions->count() > 0 ? ($isWin ? true : false) : null,
                'is_locked' => false, // History is always free
            ];
        }

        // Today is pending / locked
        $summary[] = [
            'date'      => $today->toDateString(),
            'label'     => $today->format('j M'),
            'is_win'    => null,
            'is_locked' => true,
        ];

        return response()->json(['history' => $summary]);
    }

    /**
     * Serialize a prediction and override vip_package.is_locked with the resolved value.
     */
    private function formatPrediction(MatchPrediction $prediction, bool $isLocked): array
    {
        $data = $prediction->toArray();

        if (isset($data['vip_package'])) {
            $data['vip_package']['is_locked'] = $isLocked;
        }

        return $data;
    }
}
