<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user   = requireAuth();
$db     = getDB();
$action = post('action','list');

// Permission helper for fleet actions
function requireFleetPerm($db, $user, $action) {
    if ((int)$user['role_id'] === 1) return; // Admin always allowed
    try {
        $s = $db->prepare("SELECT allowed FROM role_permissions WHERE role_id=? AND module='fleet' AND action=? LIMIT 1");
        $s->execute([$user['role_id'], $action]);
        $row = $s->fetch();
        if (!$row || !(int)$row['allowed']) requireRole([]); // force 403
    } catch (Exception $e) {
        requireRole([1,2]); // fallback
    }
}


try {
    if ($action === 'list') {
        $stmt = $db->prepare("
            SELECT v.*,
                   u.full_name AS created_by_name,
                   (SELECT odo_reading FROM fleet_costs
                    WHERE vehicle_id=v.id AND odo_reading IS NOT NULL
                    ORDER BY cost_date DESC, id DESC LIMIT 1) AS last_odo_logged
            FROM fleet_vehicles v
            LEFT JOIN users u ON u.id = v.created_by
            ORDER BY v.status, v.make, v.model
        ");
        $stmt->execute();
        $vehicles = $stmt->fetchAll();

        foreach ($vehicles as &$v) {
            $svc = $db->prepare("
                SELECT *, (v2.current_odo - last_service_odo - service_interval_km + warn_at_km_before) AS km_until_warn
                FROM fleet_service_schedule fss
                JOIN fleet_vehicles v2 ON v2.id = fss.vehicle_id
                WHERE fss.vehicle_id = ?
            ");
            $svc->execute([$v['id']]);
            $v['service_schedules'] = $svc->fetchAll();
            $v['service_due']       = array_values(array_filter($v['service_schedules'], fn($s) => ($s['km_until_warn'] ?? 999) <= 0));
        }
        apiSuccess(['vehicles' => $vehicles]);
    }

    if ($action === 'get') {
        $id   = (int)post('id');
        $stmt = $db->prepare("SELECT * FROM fleet_vehicles WHERE id=?");
        $stmt->execute([$id]); $v = $stmt->fetch();
        if (!$v) apiError('Not found.', 404);

        $docs = $db->prepare("SELECT * FROM fleet_documents WHERE vehicle_id=? ORDER BY expiry_date");
        $docs->execute([$id]); $v['documents'] = $docs->fetchAll();

        $schedules = $db->prepare("SELECT * FROM fleet_service_schedule WHERE vehicle_id=?");
        $schedules->execute([$id]); $v['service_schedules'] = $schedules->fetchAll();

        $costs = $db->prepare("
            SELECT fc.*, u.full_name AS created_by_name
            FROM fleet_costs fc
            LEFT JOIN users u ON u.id = fc.created_by
            WHERE fc.vehicle_id=? ORDER BY fc.cost_date DESC LIMIT 100
        ");
        $costs->execute([$id]); $v['costs'] = $costs->fetchAll();

        apiSuccess(['vehicle' => $v]);
    }

    if ($action === 'monthly_summary') {
        // requires fleet.reports
        requireFleetPerm($db, $user, 'reports');
        $year  = (int)post('year',  date('Y'));
        $month = (int)post('month', date('n'));
        $from  = sprintf('%04d-%02d-01', $year, $month);
        $to    = date('Y-m-t', strtotime($from));

        $stmt = $db->prepare("
            SELECT v.registration, v.make, v.model,
                   fc.cost_type, SUM(fc.amount) AS total, COUNT(*) AS entries
            FROM fleet_costs fc
            JOIN fleet_vehicles v ON v.id = fc.vehicle_id
            WHERE fc.cost_date BETWEEN ? AND ?
            GROUP BY v.id, v.registration, v.make, v.model, fc.cost_type
            ORDER BY v.make, v.model, fc.cost_type
        ");
        $stmt->execute([$from, $to]);
        apiSuccess(['summary' => $stmt->fetchAll(), 'month' => $from]);
    }

    if ($action === 'delete') {
        requireFleetPerm($db, $user, 'delete');
        $db->prepare("DELETE FROM fleet_vehicles WHERE id=?")->execute([(int)post('id')]);
        apiSuccess([], 'Deleted.');
    }

    // save (add/edit)
    requireFleetPerm($db, $user, 'edit');
    $fields = [
        post('registration'), post('make'), post('model'),
        post('year') ?: null, post('color'), post('vehicle_type','bakkie'),
        post('vin'), post('engine_no'), (int)post('current_odo',0),
        post('fuel_type','diesel'),
        post('cost_per_km') !== '' ? (float)post('cost_per_km') : null,
        post('quote_rate_per_km') !== '' ? (float)post('quote_rate_per_km') : null,
        post('status','active'), post('notes'),
    ];
    $id = (int)post('id',0);
    if ($id) {
        $db->prepare("UPDATE fleet_vehicles SET registration=?,make=?,model=?,year=?,color=?,vehicle_type=?,vin=?,engine_no=?,current_odo=?,fuel_type=?,cost_per_km=?,quote_rate_per_km=?,status=?,notes=? WHERE id=?")
           ->execute([...$fields, $id]);
        apiSuccess(['id'=>$id], 'Updated.');
    } else {
        $db->prepare("INSERT INTO fleet_vehicles (registration,make,model,year,color,vehicle_type,vin,engine_no,current_odo,fuel_type,cost_per_km,quote_rate_per_km,status,notes,created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
           ->execute([...$fields, $user['id']]);
        apiSuccess(['id'=>(int)$db->lastInsertId()], 'Vehicle added.');
    }
} catch (Exception $e) {
    apiError('Error: ' . $e->getMessage(), 500);
}