<?php
ini_set('display_errors', 1); // Disable displaying errors
ini_set('log_errors', 1); // Log errors instead
include "../include/auth.php"; // Ensure user authentication
include "../include/lskfjwfe.php"; // Include database connection

session_start();
$userid = $_POST['userid'] ?? null;  // Get the user ID from form input
$username = $_POST['username'] ?? null; // Get the username from form input

if (!$userid) {
    die("❌ Session expired or user not authenticated.");
}

// Capture form input
$veh_id = $_POST['veh_id'] ?? null;
$current_km = intval($_POST['current_km'] ?? 0);
$next_service = null;
if (!empty($_POST['nextservice'])) {
    // Convert DD/MM/YYYY to YYYY-MM-DD
    $date_parts = explode("/", $_POST['nextservice']); // Split input date
    if (count($date_parts) == 3) {
        $formatted_date = $date_parts[2] . "-" . $date_parts[1] . "-" . $date_parts[0]; // Rearrange to YYYY-MM-DD
        $next_service = strtotime($formatted_date); // Convert to timestamp
    }
}
$next_km = isset($_POST['next_km']) ? intval($_POST['next_km']) : 0;

// Ensure it's within a valid integer range (INT(11) max is ~2 billion)
if ($next_km < 0 || $next_km > 2000000) { // Assuming no car goes beyond 2,000,000 km
    $next_km = 0; // Default to 0 if invalid
}
$service_group = intval($_POST['service_group'] ?? 0);
$service_tasks = isset($_POST['service_tasks']) ? $_POST['service_tasks'] : [];

// Ensure it's an array before converting to CSV
if (is_array($service_tasks)) {
    $service_tasks = implode(',', array_map('intval', $service_tasks)); 
} else {
    $service_tasks = ''; // Default to empty if something is wrong
}
$damages = $_POST['damages'] ?? null;
$info = $_POST['info'] ?? null;

// Validate inputs
if (!$veh_id || $current_km <= 0 || $service_group <= 0) {
    die("❌ Invalid input. Please fill in all required fields.");
}

// Capture current timestamp for log entry
$log_date = time();

// Insert service log
$stmt = $db2->prepare("
    INSERT INTO service_logs (veh_id, log_date, current_km, service_group_id, service_tasks, damages, info, userid)
    VALUES (?, UNIX_TIMESTAMP(), ?, ?, ?, ?, ?, ?)
");
$stmt->bind_param('iiisssi', $veh_id, $current_km, $service_group, $service_tasks, $damages, $info, $userid);


if ($stmt->execute()) {
    // Successfully inserted service log, now update fleet table
    $update_stmt = $db2->prepare("
        UPDATE fleet 
        SET fleet_last_service = ?, fleet_last_serv_km = ?, fleet_next_service = ?, fleet_next_serv_km = ? 
        WHERE fleet_id = ?
    ");

    $update_stmt->bind_param('iiiii', $log_date, $current_km, $next_service, $next_km, $veh_id);
    
    if ($update_stmt->execute()) {
        // ✅ Success: Log action
        $action_details = "Service Group: $service_group, Tasks: " . (!empty($service_tasks) ? $service_tasks : 'None');
        $action_description = "Added Service action on vehicle ID $veh_id.";

        $log_stmt = $db2->prepare("
            INSERT INTO action_logs (user, action, details, timestamp)
            VALUES (?, ?, ?, NOW())
        ");

        $log_stmt->bind_param('sss', $username, $action_description, $action_details);
        if (!$log_stmt->execute()) {
            file_put_contents("debug_log.txt", "❌ Failed to insert into action_logs: " . $log_stmt->error, FILE_APPEND);
            die("❌ An error occurred while logging the action.");
        }

        echo "<script>alert('✅ Service log added successfully!'); window.location.href='../vehicle.php?id=$veh_id';</script>";
        exit;
    } else {
        file_put_contents("debug_log.txt", "❌ Failed to update fleet: " . $update_stmt->error, FILE_APPEND);
        die("❌ Failed to update fleet table.");
    }
} else {
    die("❌ Failed to add service log. Error: " . $stmt->error);
}
?>
