<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\Expense;
use App\Models\Purchase;
use App\Models\Roster;
use App\Models\Sale;
use App\Models\Employee;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index()
    {
        $today     = today();
        $yesterday = today()->subDay();
        $weekAgo   = today()->subDays(6);
        $monthAgo  = today()->subDays(29);

        $stats = [
            'sales'         => Sale::whereDate('sale_date', $today)->sum('amount'),
            'purchases'     => Purchase::whereDate('purchase_date', $today)->sum('cost'),
            'expenses'      => Expense::whereDate('expense_date', $today)->sum('amount'),
            'employees'     => Employee::count(),
            'customers'     => Customer::count(),
            'rosters'       => Roster::whereDate('duty_date', $today)->count(),
            'due_customers' => Customer::where('current_due', '>', 0)->count(),

            // Yesterday
            'yesterday_sales'     => Sale::whereDate('sale_date', $yesterday)->sum('amount'),
            'yesterday_purchases' => Purchase::whereDate('purchase_date', $yesterday)->sum('cost'),
            'yesterday_expenses'  => Expense::whereDate('expense_date', $yesterday)->sum('amount'),

            // Last 30 days
            'month_sales'     => Sale::whereBetween('sale_date', [$monthAgo, $today])->sum('amount'),
            'month_purchases' => Purchase::whereBetween('purchase_date', [$monthAgo, $today])->sum('cost'),
            'month_expenses'  => Expense::whereBetween('expense_date', [$monthAgo, $today])->sum('amount'),
        ];

        // Last 7 days daily chart data
        $chartLabels   = [];
        $chartSales    = [];
        $chartPurchases = [];
        $chartExpenses = [];

        for ($i = 6; $i >= 0; $i--) {
            $date = today()->subDays($i);
            $chartLabels[]    = $date->format('d M');
            $chartSales[]     = (float) Sale::whereDate('sale_date', $date)->sum('amount');
            $chartPurchases[] = (float) Purchase::whereDate('purchase_date', $date)->sum('cost');
            $chartExpenses[]  = (float) Expense::whereDate('expense_date', $date)->sum('amount');
        }

        $latestSales = Sale::with(['customer'])->latest()->limit(5)->get();

        return view('dashboard', compact(
            'stats', 'latestSales', 'today',
            'chartLabels', 'chartSales', 'chartPurchases', 'chartExpenses'
        ));
    }
}

