<?php

class DashboardController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        $user=Auth::user();$role=$user['role']??'';
        if($role==='driver')$this->redirect('/driver/loads');
        if($role==='carrier')$this->redirect('/carrier');
        if($role==='accountant')$this->redirect('/accounting');
        if($role==='maintenance')$this->redirect('/maintenance');
        if($role==='team')$this->redirect('/tasks');

        $db=Database::connection();
        $stats=[
            'active_loads'=>(int)$db->query("SELECT COUNT(*) FROM loads WHERE status IN ('new','assigned','arrived_pickup','picked_up','in_transit','arrived_delivery')")->fetchColumn(),
            'active_carriers'=>(int)$db->query("SELECT COUNT(*) FROM carriers WHERE status='active'")->fetchColumn(),
            'available_drivers'=>(int)$db->query("SELECT COUNT(*) FROM drivers WHERE status='available'")->fetchColumn(),
            'available_trucks'=>(int)$db->query("SELECT COUNT(*) FROM trucks WHERE status='available'")->fetchColumn(),
            'available_trailers'=>(int)$db->query("SELECT COUNT(*) FROM trailers WHERE status='available'")->fetchColumn(),
            'monthly_revenue'=>(float)$db->query("SELECT COALESCE(SUM(rate),0) FROM loads WHERE MONTH(created_at)=MONTH(CURRENT_DATE()) AND YEAR(created_at)=YEAR(CURRENT_DATE()) AND status<>'cancelled'")->fetchColumn(),
            'monthly_dispatch_fees'=>(float)$db->query("SELECT COALESCE(SUM(dispatch_fee_amount),0) FROM loads WHERE MONTH(created_at)=MONTH(CURRENT_DATE()) AND YEAR(created_at)=YEAR(CURRENT_DATE()) AND status<>'cancelled'")->fetchColumn(),
            'pending_invoices'=>(float)$db->query("SELECT COALESCE(SUM(balance_due),0) FROM invoices WHERE status NOT IN ('paid','void','cancelled','written_off')")->fetchColumn(),
            'maintenance_due'=>(int)$db->query("SELECT COUNT(*) FROM maintenance_records WHERE next_service_date IS NOT NULL AND next_service_date<=DATE_ADD(CURDATE(),INTERVAL 30 DAY)")->fetchColumn(),
            'border_attention'=>(int)$db->query("SELECT COUNT(*) FROM border_crossings WHERE status IN ('documents_required','broker_reviewing','waiting_in_queue','customs_inspection','on_hold')")->fetchColumn(),
            'pending_expenses'=>(int)$db->query("SELECT COUNT(*) FROM expenses WHERE status IN ('submitted','under_review')")->fetchColumn(),
            'temperature_alerts'=>(new TemperatureLog())->latestAlertCount(),
            'carrier_compliance'=>(int)$db->query("SELECT COUNT(*) FROM carriers WHERE status='active' AND ((insurance_expiry IS NOT NULL AND insurance_expiry<=DATE_ADD(CURDATE(),INTERVAL 30 DAY)) OR (cargo_insurance_expiry IS NOT NULL AND cargo_insurance_expiry<=DATE_ADD(CURDATE(),INTERVAL 30 DAY)) OR onboarding_status<>'approved')")->fetchColumn(),
        ];

        $recentLoads=$db->query('SELECT loads.*,brokers.company_name broker_name,carriers.company_name carrier_name,drivers.name driver_name,trailers.trailer_number FROM loads LEFT JOIN brokers ON brokers.id=loads.broker_id LEFT JOIN carriers ON carriers.id=loads.carrier_id LEFT JOIN drivers ON drivers.id=loads.driver_id LEFT JOIN trailers ON trailers.id=loads.trailer_id ORDER BY loads.id DESC LIMIT 6')->fetchAll();
        $statusRows=$db->query("SELECT status,COUNT(*) total FROM loads WHERE status<>'cancelled' GROUP BY status")->fetchAll();
        $loadStatusBreakdown=['in_transit'=>0,'picked_up'=>0,'delivered'=>0,'assigned'=>0,'pending'=>0];
        foreach($statusRows as $statusRow){
            $status=(string)$statusRow['status'];$count=(int)$statusRow['total'];
            if(in_array($status,['in_transit','arrived_delivery'],true))$loadStatusBreakdown['in_transit']+=$count;
            elseif(in_array($status,['picked_up','arrived_pickup'],true))$loadStatusBreakdown['picked_up']+=$count;
            elseif(in_array($status,['delivered','invoiced','paid'],true))$loadStatusBreakdown['delivered']+=$count;
            elseif($status==='assigned')$loadStatusBreakdown['assigned']+=$count;
            else $loadStatusBreakdown['pending']+=$count;
        }
        $todaySchedule=(new Load())->todaySchedule();$overdueInvoices=(new Invoice())->overdue();$expiringDocuments=(new Document())->expiring(30);$maintenanceDue=(new Maintenance())->dueSoon(30);
        $activities=$db->query('SELECT activity_logs.*,users.name user_name FROM activity_logs LEFT JOIN users ON users.id=activity_logs.user_id ORDER BY activity_logs.id DESC LIMIT 8')->fetchAll();
        $this->view('dashboard/index',compact('stats','recentLoads','loadStatusBreakdown','todaySchedule','overdueInvoices','expiringDocuments','maintenanceDue','activities'));
    }
}
