<?php
// POST /api/slips/stats.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user   = requireAuth();
$db     = getDB();
$isAdmin = in_array($user['role_id'], [1, 5]);

function Auth_hasFleetAccess($db, $user) {
    if ((int)$user['role_id'] === 1) return true;
    try {
        $s = $db->prepare("SELECT allowed FROM role_permissions WHERE role_id=? AND module='fleet' AND action='view' LIMIT 1");
        $s->execute([$user['role_id']]);
        $r = $s->fetch();
        return $r && (int)$r['allowed'];
    } catch (Exception $e) { return false; }
}

$uid = $isAdmin ? null : $user['id'];
$userCond      = $uid ? "AND user_id = {$uid}" : '';
$userCondFuel  = $uid ? "AND created_by = {$uid}" : '';

// This month
$mStart = date('Y-m-01');
$mEnd   = date('Y-m-d');

// Last month
$lStart = date('Y-m-01', strtotime('first day of last month'));
$lEnd   = date('Y-m-t',  strtotime('last day of last month'));

// ── This month slips total
$thisMoSlips = $db->prepare("SELECT COALESCE(SUM(amount),0) FROM slips WHERE slip_date BETWEEN ? AND ? {$userCond}");
$thisMoSlips->execute([$mStart, $mEnd]);
$thisMonthTotal = (float)$thisMoSlips->fetchColumn();

// ── Last month slips total
$lastMoSlips = $db->prepare("SELECT COALESCE(SUM(amount),0) FROM slips WHERE slip_date BETWEEN ? AND ? {$userCond}");
$lastMoSlips->execute([$lStart, $lEnd]);
$lastMonthTotal = (float)$lastMoSlips->fetchColumn();

// ── Fleet costs (fuel + vehicle) — wrapped in case fleet module not active
$fuelThisMonth    = 0.0;
$vehicleThisMonth = 0.0;
$canFleet = Auth_hasFleetAccess($db, $user);
if ($canFleet) {
    try {
        $fuelMo = $db->prepare("SELECT COALESCE(SUM(amount),0) FROM fleet_costs WHERE cost_type='fuel' AND cost_date BETWEEN ? AND ? {$userCondFuel}");
        $fuelMo->execute([$mStart, $mEnd]);
        $fuelThisMonth = (float)$fuelMo->fetchColumn();

        $vehMo = $db->prepare("SELECT COALESCE(SUM(amount),0) FROM fleet_costs WHERE cost_date BETWEEN ? AND ? {$userCondFuel}");
        $vehMo->execute([$mStart, $mEnd]);
        $vehicleThisMonth = (float)$vehMo->fetchColumn();

        // Add fleet fuel to monthly totals
        $fuelLastMo = $db->prepare("SELECT COALESCE(SUM(amount),0) FROM fleet_costs WHERE cost_type='fuel' AND cost_date BETWEEN ? AND ? {$userCondFuel}");
        $fuelLastMo->execute([$lStart, $lEnd]);
        $thisMonthTotal += $fuelThisMonth;
        $lastMonthTotal += (float)$fuelLastMo->fetchColumn();
    } catch (Exception $e) { /* fleet_costs table missing */ }
}

// ── Pending/unlinked slips count
$pendStmt = $db->prepare("SELECT COUNT(*) FROM slips WHERE status = 'unlinked' {$userCond}");
$pendStmt->execute();
$unlinkedCount = (int)$pendStmt->fetchColumn();

// ── Category breakdown this month (slips only)
$catStmt = $db->prepare("
    SELECT category, COALESCE(SUM(amount),0) AS total
    FROM slips WHERE slip_date BETWEEN ? AND ? {$userCond}
    GROUP BY category ORDER BY total DESC LIMIT 5
");
$catStmt->execute([$mStart, $mEnd]);
$topCategories = $catStmt->fetchAll();

// ── MoM change
$mom = $lastMonthTotal > 0 ? round((($thisMonthTotal - $lastMonthTotal) / $lastMonthTotal) * 100, 1) : null;

apiSuccess([
    'this_month'       => $thisMonthTotal,
    'last_month'       => $lastMonthTotal,
    'fuel_this_month'  => $fuelThisMonth,
    'vehicle_costs'    => $vehicleThisMonth,
    'unlinked_count'   => $unlinkedCount,
    'mom_change'       => $mom,
    'top_categories'   => $topCategories,
    'month_label'      => date('F Y'),
    'last_month_label' => date('F Y', strtotime('last month')),
]);