<?php
include('../include/auth.php');
include('../include/lskfjwfe.php'); // Database connectivity file

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $vehicle_id = intval($_POST['vehicle_id']);
    $vehicle_name = mysqli_real_escape_string($db2, $_POST['vehicle_name']);
    $vehicle_category = intval($_POST['vehicle_category']);
    $idcat_prefix = mysqli_real_escape_string($db2, $_POST['idcat_prefix']);
    $idcat = $idcat_prefix . $vehicle_category . ";";

    // Process characteristics
    $selected_characteristics = isset($_POST['vehicle_characteristics']) ? $_POST['vehicle_characteristics'] : [];
    $idcarat = implode(';', $selected_characteristics) . ';';

    // Retrieve existing image
    $existing_image_query = "SELECT img FROM jostj_vikrentcar_cars WHERE id = $vehicle_id";
    $existing_image_result = mysqli_query($db2, $existing_image_query);
    $existing_image_row = mysqli_fetch_assoc($existing_image_result);
    $image_name = $existing_image_row['img']; // Default to existing image

    // Handle image upload
    $target_dir = "../carimages/";
    if (isset($_FILES['vehicle_image']) && $_FILES['vehicle_image']['error'] == 0) {
        $image_info = getimagesize($_FILES['vehicle_image']['tmp_name']);
        $allowed_types = ['image/jpeg', 'image/png', 'image/webp'];
        if (!in_array($image_info['mime'], $allowed_types)) {
            die("<script>alert('Invalid image format.'); window.history.back();</script>");
        }
        if ($image_info[0] != 600 || $image_info[1] != 400) {
            die("<script>alert('Invalid dimensions. Must be 600x400.'); window.history.back();</script>");
        }
        $image_name = uniqid('vehicle_') . "." . pathinfo($_FILES['vehicle_image']['name'], PATHINFO_EXTENSION);
        $target_file = $target_dir . $image_name;
        if (!move_uploaded_file($_FILES['vehicle_image']['tmp_name'], $target_file)) {
            die("<script>alert('Error uploading image.'); window.history.back();</script>");
        }
    }

    // Update vehicle record
    $update_query = "UPDATE jostj_vikrentcar_cars 
                     SET name = '$vehicle_name', idcat = '$idcat', idcarat = '$idcarat', img = '$image_name' 
                     WHERE id = $vehicle_id";

    if (mysqli_query($db2, $update_query)) {
    // Log the action
    $action = "Edit Vehicle";
    $details = "Edited vehicle: $vehicle_name (ID: $vehicle_id, Category: $idcat, Characteristics: $idcarat)";
    $log_query = "INSERT INTO action_logs (action, details, user, timestamp) VALUES ('$action', '$details', '$user', NOW())";
    mysqli_query($db2, $log_query);

    echo "<script>
        alert('Vehicle updated successfully.');
        window.location.href = '../fleet.php';
    </script>";
} else {
    echo "<script>
        alert('Error updating vehicle: " . mysqli_error($db2) . "');
        window.history.back();
    </script>";
}
}
?>
