<?php
declare(strict_types=1);

require_once '../config/database.php';
require_once '../app/helpers/rbac.php';
require_once '../app/helpers/api_security.php';

header('Content-Type: application/json');

requireApiLogin();
enforceCsrfForUnsafeRequest();

$action = $_GET['action'] ?? 'summary';

try {
    switch ($action) {
        case 'summary':   handleSummary($pdo); break;
        case 'detail':    handleDetail($pdo); break;
        case 'vehicles':  handleVehicles($pdo); break;
        default: respond(['status' => 'error', 'message' => 'Unknown action']);
    }
} catch (Exception $e) {
    respond(['status' => 'error', 'message' => $e->getMessage()]);
}

function getFilters(): array
{
    $year = (int)($_GET['year'] ?? date('Y'));
    $vehicleId = (int)($_GET['vehicle_id'] ?? 0);
    $startDate = $_GET['start_date'] ?? "$year-01-01";
    $endDate   = $_GET['end_date'] ?? "$year-12-31";
    return [$year, $vehicleId, $startDate, $endDate];
}

function handleSummary(PDO $pdo): void
{
    [$year, $vehicleId, $startDate, $endDate] = getFilters();

    $vehicleWhere = '';
    $params = [':start' => $startDate, ':end' => $endDate];
    if ($vehicleId > 0) {
        $vehicleWhere = ' AND v.id = :vid';
        $params[':vid'] = $vehicleId;
    }

    $whereClause = "v.deleted_at IS NULL AND v.vehicle_status IN ('active','Active','ACTIVE')$vehicleWhere";
    $vehicles = $pdo->prepare("SELECT v.id, v.plate_number, v.vehicle_model, v.year_of_manufacturing AS model_year,
        v.vehicle_type, v.vehicle_status,
        COALESCE((SELECT SUM(f.total_amount) FROM vehicle_fuel_entries f
            WHERE f.vehicle_id = v.id AND f.deleted_at IS NULL AND f.approval_status = 'Approved'
            AND f.record_date BETWEEN :start AND :end), 0) AS fuel_cost,
        COALESCE((SELECT COALESCE(SUM(m.approved_amount), SUM(m.cost_of_repair), 0) FROM maintenance_jobs m
            WHERE m.vehicle_id = v.id AND m.deleted_at IS NULL
            AND m.complaint_date BETWEEN :start2 AND :end2), 0) AS maint_cost,
        COALESCE((SELECT SUM(p.premium_amount) FROM vehicle_insurance_policies p
            WHERE p.vehicle_id = v.id AND p.deleted_at IS NULL
            AND (p.coverage_start BETWEEN :start3 AND :end3 OR p.coverage_end BETWEEN :start3 AND :end3)), 0) AS ins_cost,
        COALESCE((SELECT SUM(e.amount) FROM vehicle_expenses e
            WHERE e.vehicle_id = v.id AND e.deleted_at IS NULL
            AND e.expense_date BETWEEN :start4 AND :end4), 0) AS expense_cost
        FROM vehicles v WHERE $whereClause ORDER BY v.plate_number");
    $vehicles->execute(array_merge($params, [
        ':start2' => $params[':start'], ':end2' => $params[':end'],
        ':start3' => $params[':start'], ':end3' => $params[':end'],
        ':start4' => $params[':start'], ':end4' => $params[':end'],
    ]));
    $rows = $vehicles->fetchAll(PDO::FETCH_ASSOC);

    $data = [];
    $totalFuel = $totalMaint = $totalIns = $totalExpense = 0;
    foreach ($rows as $r) {
        $tco = (float)$r['fuel_cost'] + (float)$r['maint_cost'] + (float)$r['ins_cost'] + (float)$r['expense_cost'];
        $totalFuel += (float)$r['fuel_cost'];
        $totalMaint += (float)$r['maint_cost'];
        $totalIns += (float)$r['ins_cost'];
        $totalExpense += (float)$r['expense_cost'];
        $data[] = [
            'vehicle_id'    => (int)$r['id'],
            'plate_number'  => $r['plate_number'],
            'make_model'    => $r['vehicle_model'] ?? '',
            'vehicle_type'  => $r['vehicle_type'],
            'model_year'    => $r['model_year'],
            'fuel_cost'     => round((float)$r['fuel_cost'], 2),
            'maint_cost'    => round((float)$r['maint_cost'], 2),
            'ins_cost'      => round((float)$r['ins_cost'], 2),
            'expense_cost'  => round((float)$r['expense_cost'], 2),
            'tco'           => round($tco, 2),
        ];
    }

    $grandTotal = $totalFuel + $totalMaint + $totalIns + $totalExpense;

    respond([
        'status' => 'success',
        'data'   => $data,
        'kpis'   => [
            'vehicle_count'  => count($data),
            'total_fuel'     => round($totalFuel, 2),
            'total_maint'    => round($totalMaint, 2),
            'total_ins'      => round($totalIns, 2),
            'total_expense'  => round($totalExpense, 2),
            'grand_total'    => round($grandTotal, 2),
        ],
        'filters' => [
            'year'            => (int)$_GET['year'] ?? (int)date('Y'),
            'vehicle_id'      => (int)$_GET['vehicle_id'] ?? 0,
            'start_date'      => $_GET['start_date'] ?? date('Y-01-01'),
            'end_date'        => $_GET['end_date'] ?? date('Y-12-31'),
        ],
    ]);
}

function handleDetail(PDO $pdo): void
{
    [$year, $vehicleId, $startDate, $endDate] = getFilters();
    if ($vehicleId <= 0) {
        respond(['status' => 'error', 'message' => 'vehicle_id required'], 400);
    }

    $v = $pdo->prepare("SELECT id, plate_number, vehicle_model, year_of_manufacturing AS model_year, vehicle_type FROM vehicles WHERE id = ? AND deleted_at IS NULL");
    $v->execute([$vehicleId]);
    $vehicle = $v->fetch(PDO::FETCH_ASSOC);
    if (!$vehicle) {
        respond(['status' => 'error', 'message' => 'Vehicle not found'], 404);
    }

    $fuel = $pdo->prepare("SELECT record_date, vehicle_no, fuel_type_id, fuel_purchase_liters, naira_per_liter, total_amount, filling_station, approval_status FROM vehicle_fuel_entries WHERE vehicle_id = ? AND deleted_at IS NULL AND approval_status = 'Approved' AND record_date BETWEEN ? AND ? ORDER BY record_date DESC");
    $fuel->execute([$vehicleId, $startDate, $endDate]);

    $maint = $pdo->prepare("SELECT complaint_date, complaint_title, work_order_number, COALESCE(approved_amount, cost_of_repair, 0) AS cost, workshop, workflow_stage FROM maintenance_jobs WHERE vehicle_id = ? AND deleted_at IS NULL AND complaint_date BETWEEN ? AND ? ORDER BY complaint_date DESC");
    $maint->execute([$vehicleId, $startDate, $endDate]);

    $ins = $pdo->prepare("SELECT policy_number, insurer_name, policy_type, coverage_start, coverage_end, premium_amount, is_active FROM vehicle_insurance_policies WHERE vehicle_id = ? AND deleted_at IS NULL AND (coverage_start BETWEEN ? AND ? OR coverage_end BETWEEN ? AND ?) ORDER BY coverage_start DESC");
    $ins->execute([$vehicleId, $startDate, $endDate, $startDate, $endDate]);

    $exp = $pdo->prepare("SELECT expense_date, amount, description, reference_number FROM vehicle_expenses WHERE vehicle_id = ? AND deleted_at IS NULL AND expense_date BETWEEN ? AND ? ORDER BY expense_date DESC");
    $exp->execute([$vehicleId, $startDate, $endDate]);

    respond([
        'status' => 'success',
        'vehicle' => $vehicle,
        'fuel_entries'     => $fuel->fetchAll(PDO::FETCH_ASSOC),
        'maint_entries'    => $maint->fetchAll(PDO::FETCH_ASSOC),
        'ins_entries'      => $ins->fetchAll(PDO::FETCH_ASSOC),
        'expense_entries'  => $exp->fetchAll(PDO::FETCH_ASSOC),
    ]);
}

function handleVehicles(PDO $pdo): void
{
    $rows = $pdo->query("SELECT id, plate_number FROM vehicles WHERE deleted_at IS NULL AND vehicle_status IN ('active','Active','ACTIVE') ORDER BY plate_number")->fetchAll(PDO::FETCH_ASSOC);
    respond(['status' => 'success', 'data' => $rows]);
}

function respond(array $payload, int $code = 200): void { apiRespond($payload, $code); }
