<?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]);
    }
}

requireFleetPerm($db, $user, 'reports');
$action    = post('action','save');
$vehicleId = (int)post('vehicle_id',0);

try {

    if ($action === 'list') {
        if (!$vehicleId) apiError('Vehicle ID required.', 422);
        $stmt = $db->prepare("
            SELECT fss.*, v.current_odo,
                   (v.current_odo - fss.last_service_odo) AS km_since_service,
                   (fss.service_interval_km - (v.current_odo - fss.last_service_odo)) AS km_remaining
            FROM fleet_service_schedule fss
            JOIN fleet_vehicles v ON v.id = fss.vehicle_id
            WHERE fss.vehicle_id=?
            ORDER BY fss.service_type
        ");
        $stmt->execute([$vehicleId]);
        apiSuccess(['schedules' => $stmt->fetchAll()]);
    }

    if ($action === 'history') {
        if (!$vehicleId) apiError('Vehicle ID required.', 422);
        $stmt = $db->prepare("
            SELECT fsh.*,
                   u.full_name AS recorded_by_name,
                   fc.amount AS cost_amount,
                   fc.slip_image_path
            FROM fleet_service_history fsh
            JOIN users u ON u.id = fsh.recorded_by
            LEFT JOIN fleet_costs fc ON fc.id = fsh.cost_id
            WHERE fsh.vehicle_id = ?
            ORDER BY fsh.service_date DESC, fsh.created_at DESC
        ");
        $stmt->execute([$vehicleId]);
        apiSuccess(['history' => $stmt->fetchAll()]);
    }

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

    if ($action === 'complete') {
        if (!$vehicleId) apiError('Vehicle ID required.', 422);
        $scheduleId  = (int)post('id');
        $odo         = (int)post('odo_reading');
        $serviceDate = post('service_date', date('Y-m-d'));
        $notes       = post('notes', '');
        $amount      = (float)post('amount', 0);
        $serviceType = post('service_type', 'Service');

        // Handle slip upload
        $slipPath = null; $slipFilename = null;
        if (!empty($_FILES['slip']) && $_FILES['slip']['error'] === UPLOAD_ERR_OK) {
            $file    = $_FILES['slip'];
            $finfo   = finfo_open(FILEINFO_MIME_TYPE);
            $mime    = finfo_file($finfo, $file['tmp_name']); finfo_close($finfo);
            $allowed = ['image/jpeg','image/png','image/webp','image/gif','application/pdf'];
            if (!in_array($mime, $allowed)) apiError('Only images and PDFs allowed for slip.', 422);
            $dir = __DIR__ . '/../../uploads/fleet/service/' . $vehicleId . '/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $ext          = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) ?: 'jpg';
            $slipFilename = 'svc_' . uniqid() . '.' . $ext;
            if (!move_uploaded_file($file['tmp_name'], $dir . $slipFilename)) apiError('Slip upload failed.', 500);
            $slipPath = 'uploads/fleet/service/' . $vehicleId . '/' . $slipFilename;
        }

        $db->beginTransaction();

        // Insert fleet_costs entry for service
        $costId = null;
        $db->prepare("
            INSERT INTO fleet_costs (vehicle_id, cost_type, amount, description, odo_reading, cost_date, slip_image_path, slip_filename, created_by)
            VALUES (?, 'service', ?, ?, ?, ?, ?, ?, ?)
        ")->execute([$vehicleId, $amount, $serviceType . ($notes ? ' — ' . $notes : ''), $odo, $serviceDate, $slipPath, $slipFilename, $user['id']]);
        $costId = (int)$db->lastInsertId();

        // Insert service history record
        $db->prepare("
            INSERT INTO fleet_service_history (vehicle_id, schedule_id, service_type, service_date, odo_reading, cost_id, notes, recorded_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ")->execute([$vehicleId, $scheduleId ?: null, $serviceType, $serviceDate, $odo, $costId, $notes, $user['id']]);

        // Update schedule last service
        if ($scheduleId) {
            $db->prepare("UPDATE fleet_service_schedule SET last_service_odo=?, last_service_date=? WHERE id=? AND vehicle_id=?")
               ->execute([$odo, $serviceDate, $scheduleId, $vehicleId]);
        }

        // Update vehicle odo
        $db->prepare("UPDATE fleet_vehicles SET current_odo=GREATEST(current_odo,?) WHERE id=?")->execute([$odo, $vehicleId]);

        $db->commit();
        apiSuccess(['cost_id' => $costId], 'Service recorded.');
    }

    if ($action === 'save') {
        if (!$vehicleId) apiError('Vehicle ID required.', 422);
        $id = (int)post('id', 0);
        if ($id) {
            $db->prepare("UPDATE fleet_service_schedule SET service_type=?,service_interval_km=?,last_service_odo=?,last_service_date=?,warn_at_km_before=?,notes=? WHERE id=? AND vehicle_id=?")
               ->execute([post('service_type'), (int)post('service_interval_km',10000), (int)post('last_service_odo',0), post('last_service_date') ?: null, (int)post('warn_at_km_before',500), post('notes'), $id, $vehicleId]);
            apiSuccess(['id'=>$id], 'Updated.');
        } else {
            $db->prepare("INSERT INTO fleet_service_schedule (vehicle_id,service_type,service_interval_km,last_service_odo,last_service_date,warn_at_km_before,notes) VALUES (?,?,?,?,?,?,?)")
               ->execute([$vehicleId, post('service_type'), (int)post('service_interval_km',10000), (int)post('last_service_odo',0), post('last_service_date') ?: null, (int)post('warn_at_km_before',500), post('notes')]);
            apiSuccess(['id' => (int)$db->lastInsertId()], 'Schedule added.');
        }
    }

    apiError('Unknown action.', 400);

} catch (Exception $e) {
    if ($db->inTransaction()) $db->rollBack();
    apiError('Error: ' . $e->getMessage(), 500);
}