<?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']);
    $vehicle_info = mysqli_real_escape_string($db2, $_POST['vehicle_info']);
    $selected_characteristics = isset($_POST['vehicle_characteristics']) ? $_POST['vehicle_characteristics'] : [];
    $idcarat = implode(';', $selected_characteristics) . ';';

    // Handle image upload
    $target_dir = "../carimages/";
    $image_name = mysqli_real_escape_string($db2, $_POST['existing_image']);
    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("Invalid image format. Only jpg, png, and webp are allowed.");
        }

        if ($image_info[0] != 600 || $image_info[1] != 400) {
            die("Invalid image dimensions. Image must be 600x400 pixels.");
        }

        $image_name = uniqid() . "." . 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("Error uploading image.");
        }
    }

    $idcat = $idcat_prefix . $vehicle_category . ";";

    $update_query = "UPDATE jostj_vikrentcar_cars 
                     SET name = '$vehicle_name', idcat = '$idcat', idcarat = '$idcarat', info = '$vehicle_info', img = '$image_name'
                     WHERE id = $vehicle_id";

    if (mysqli_query($db2, $update_query)) {
        // Log the action
        $action = "Edit Vehicle";
        $details = "Updated vehicle: $vehicle_name (ID: $vehicle_id, Category: $idcat, Characteristics: $idcarat)";
        $log_query = "INSERT INTO action_logs (action, details, user) VALUES ('$action', '$details', '$user')";
        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.location.href = '../fleet.php';
        </script>";
    }
}
?>
