<?php

namespace App\Http\Controllers;

use App\Models\BrandRequirement;
use App\Models\Inventory;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\OpportunitiesExport;

class OpportunityController extends Controller
{
    public function index(Request $request)
    {
        /* ================= EXCEL EXPORT ================= */
        if ($request->get('export') === 'excel') {
            return Excel::download(
                new OpportunitiesExport($request),
                'opportunities.xlsx'
            );
        }

        /* ================= DASHBOARD COUNTS ================= */
/* ================= BASE QUERY (ONE SOURCE OF TRUTH) ================= */
$baseQuery = BrandRequirement::whereHas('market.inventories');

/* ================= DASHBOARD COUNTS ================= */

$todayCount = (clone $baseQuery)
    ->whereBetween('created_at', [
        Carbon::now()->startOfDay(),
        Carbon::now()->endOfDay()
    ])
    ->count();

$yesterdayCount = (clone $baseQuery)
    ->whereBetween('created_at', [
        Carbon::now()->subDay()->startOfDay(),
        Carbon::now()->subDay()->endOfDay()
    ])
    ->count();

$weekCount = (clone $baseQuery)
    ->whereBetween('created_at', [
        Carbon::now()->subDays(6)->startOfDay(),
        Carbon::now()->endOfDay()
    ])
    ->count();

$monthCount = (clone $baseQuery)
    ->whereBetween('created_at', [
        Carbon::now()->startOfMonth()->startOfDay(),
        Carbon::now()->endOfDay()
    ])
    ->count();

$yearCount = (clone $baseQuery)
    ->whereBetween('created_at', [
        Carbon::now()->startOfYear()->startOfDay(),
        Carbon::now()->endOfDay()
    ])
    ->count();

$totalCount = (clone $baseQuery)->count();

/* ================= TABLE QUERY ================= */

$query = (clone $baseQuery)->with([
    'brand',
    'poc',
    'state',
    'city',
    'market'
]);

        /* ================= MAIN QUERY (PERMANENT) ================= */

       $query = BrandRequirement::with([
    'brand',
    'poc',
    'state',
    'city',
    'market'
])
->whereHas('market.inventories');


        /* ================= CITY FILTER ================= */
        if ($request->filled('cities')) {
            $query->whereIn('city_id', $request->cities);
        }

        /* ================= MARKET FILTER ================= */
        if ($request->filled('markets')) {
            $query->whereIn('market_id', $request->markets);
        }

        /* ================= DATE FILTER ================= */
        if ($request->date_filter === 'today') {
            $query->whereDate('created_at', Carbon::today());
        }

        if ($request->date_filter === 'yesterday') {
            $query->whereDate('created_at', Carbon::yesterday());
        }

        if ($request->filled('date_from') && $request->filled('date_to')) {
            $query->whereBetween('created_at', [
                Carbon::parse($request->date_from)->startOfDay(),
                Carbon::parse($request->date_to)->endOfDay()
            ]);
        }

        $opportunities = $query
            ->latest()
            ->paginate(15)
            ->appends($request->query());

        return view('dashboard', compact(
            'opportunities',
            'todayCount',
            'yesterdayCount',
            'weekCount',
            'monthCount',
            'yearCount',
            'totalCount'
        ));
    }

    /* ================= MODAL VIEW ================= */
    public function show($id)
    {
        $requirement = BrandRequirement::with([
            'brand',
            'poc',
            'state',
            'city',
            'market'
        ])->findOrFail($id);

        // Inventory sirf view ke liye
        $inventory = Inventory::with(['state', 'city', 'market'])
            ->where('market_id', $requirement->market_id)
            ->latest()
            ->first();

        return response()->json([
            'requirement' => $requirement,
            'inventory'   => $inventory
        ]);
    }
}