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

// Fleet permission helper
function requireFleetPerm($db, $user, $action) {
    if ((int)$user['role_id'] === 1) return;
    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([]);
    } catch (Exception $e) {
        requireRole([1,2]);
    }
}
$action    = post('action','list');
$vehicleId = (int)post('vehicle_id',0);

try {
    if ($action === 'list') {
        if (!$vehicleId) apiError('Vehicle ID required.', 422);
        $stmt = $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 200
        ");
        $stmt->execute([$vehicleId]);
        apiSuccess(['costs' => $stmt->fetchAll()]);
    }

    if ($action === 'delete') {
        requireRole([1,2]);
        $db->prepare("DELETE FROM fleet_costs WHERE id=? AND vehicle_id=?")
           ->execute([(int)post('id'), $vehicleId]);
        apiSuccess([], 'Deleted.');
    }

    // save fuel slip (tech shortcut — no vehicle_id restriction by role)
    if ($action === 'fuel_slip') {
        $vId    = (int)post('vehicle_id');
        $odo    = (int)post('odo_reading',0);
        $litres = (float)post('litres',0);
        $amount = (float)post('amount',0);
        if (!$vId || !$amount) apiError('Vehicle and amount required.', 422);

        // Validate odo not less than latest
        if ($odo > 0) {
            $latestStmt = $db->prepare("SELECT MAX(odo_reading) AS latest FROM fleet_travel_log WHERE vehicle_id=?");
            $latestStmt->execute([$vId]);
            $latestRow = $latestStmt->fetch();
            $latestOdo = (int)($latestRow['latest'] ?? 0);
            if ($latestOdo > 0 && $odo < $latestOdo) {
                apiError("ODO reading cannot be less than the latest recorded reading ({$latestOdo} km).", 422);
            }
        }

        $imagePath = null;
        $filename  = null;
        if (!empty($_FILES['slip_image']) && $_FILES['slip_image']['error'] === UPLOAD_ERR_OK) {
            $file  = $_FILES['slip_image'];
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime  = finfo_file($finfo, $file['tmp_name']); finfo_close($finfo);
            if (!in_array($mime, ['image/jpeg','image/png','image/webp','image/gif'])) apiError('Images only.', 422);
            $dir = __DIR__ . '/../../uploads/fleet/fuel/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) ?: 'jpg';
            $filename = 'fuel_' . $vId . '_' . uniqid() . '.' . $ext;
            if (!move_uploaded_file($file['tmp_name'], $dir . $filename)) apiError('Upload failed.', 500);
            $imagePath = 'uploads/fleet/fuel/' . $filename;
        }

        $db->prepare("
            INSERT INTO fleet_costs (vehicle_id, cost_type, amount, description, odo_reading, litres, cost_date, slip_image_path, slip_filename, created_by)
            VALUES (?, 'fuel', ?, ?, ?, ?, ?, ?, ?, ?)
        ")->execute([$vId, $amount, post('description','Fuel'), $odo ?: null, $litres ?: null, post('cost_date', date('Y-m-d')), $imagePath, $filename, $user['id']]);

        $fuelCostId = (int)$db->lastInsertId();

        // Update current_odo and log to travel log if odo provided
        if ($odo > 0) {
            $db->prepare("UPDATE fleet_vehicles SET current_odo=GREATEST(current_odo,?) WHERE id=?")
               ->execute([$odo, $vId]);
            // Insert into unified travel log with source=fuel_slip
            $db->prepare("INSERT INTO fleet_travel_log (vehicle_id, odo_reading, reading_date, source, source_id, recorded_by, notes)
                          VALUES (?, ?, ?, 'fuel_slip', ?, ?, 'Fuel slip ODO')")
               ->execute([$vId, $odo, post('cost_date', date('Y-m-d')), $fuelCostId, $user['id']]);
        }
        apiSuccess(['id' => $fuelCostId], 'Fuel slip saved.');
    }

    // save general cost
    requireRole([1,2]);
    if (!$vehicleId) apiError('Vehicle ID required.', 422);
    $amount = (float)post('amount', 0);
    if (!$amount) apiError('Amount required.', 422);

    $imagePath = null;
    $filename  = null;
    if (!empty($_FILES['slip_image']) && $_FILES['slip_image']['error'] === UPLOAD_ERR_OK) {
        $file  = $_FILES['slip_image'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime  = finfo_file($finfo, $file['tmp_name']); finfo_close($finfo);
        if (!in_array($mime, ['image/jpeg','image/png','image/webp','image/gif'])) apiError('Images only.', 422);
        $dir = __DIR__ . '/../../uploads/fleet/costs/';
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) ?: 'jpg';
        $filename = 'cost_' . $vehicleId . '_' . uniqid() . '.' . $ext;
        if (!move_uploaded_file($file['tmp_name'], $dir . $filename)) apiError('Upload failed.', 500);
        $imagePath = 'uploads/fleet/costs/' . $filename;
    }

    $id = (int)post('id',0);
    if ($id) {
        $db->prepare("UPDATE fleet_costs SET cost_type=?,amount=?,description=?,odo_reading=?,litres=?,cost_date=? WHERE id=? AND vehicle_id=?")
           ->execute([post('cost_type','other'), $amount, post('description'), post('odo_reading') ?: null, post('litres') ?: null, post('cost_date',date('Y-m-d')), $id, $vehicleId]);
        apiSuccess(['id'=>$id], 'Updated.');
    } else {
        $db->prepare("INSERT INTO fleet_costs (vehicle_id,cost_type,amount,description,odo_reading,litres,cost_date,slip_image_path,slip_filename,created_by) VALUES (?,?,?,?,?,?,?,?,?,?)")
           ->execute([$vehicleId, post('cost_type','other'), $amount, post('description'), post('odo_reading') ?: null, post('litres') ?: null, post('cost_date',date('Y-m-d')), $imagePath, $filename, $user['id']]);
        $newId = (int)$db->lastInsertId();
        if (post('odo_reading')) {
            $db->prepare("UPDATE fleet_vehicles SET current_odo=GREATEST(current_odo,?) WHERE id=?")
               ->execute([(int)post('odo_reading'), $vehicleId]);
        }
        apiSuccess(['id'=>$newId], 'Cost added.');
    }
} catch (Exception $e) {
    apiError('Error: ' . $e->getMessage(), 500);
}