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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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']); // Process info field
    $idcat = $idcat_prefix . $vehicle_category . ";";

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

    // Generate alias from vehicle name
    $alias = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $vehicle_name));

    // Handle image upload
    $target_dir = "../carimages/";
    $image_name = "";
    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. Only jpg, png, and webp are allowed.'); window.history.back();</script>");
        }

        if ($image_info[0] != 600 || $image_info[1] != 400) {
            die("<script>alert('Invalid image dimensions. Image must be 600x400 pixels.'); 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. Please try again.'); window.history.back();</script>");
        }
    }

    // Insert into the database
   $insert_query = "INSERT INTO jostj_vikrentcar_cars (name, idcat, idcarat, alias, img, info) 
                 VALUES ('$vehicle_name', '$idcat', '$idcarat', '$alias', '$image_name', '$vehicle_info')";

  if (mysqli_query($db2, $insert_query)) {
    // Log the action
    $action = "Add Vehicle";
    $details = "Added vehicle: $vehicle_name (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 added successfully.');
        window.location.href = '../fleet.php';
    </script>";
} else {
    echo "<script>
        alert('Error adding vehicle: " . mysqli_error($db2) . "');
        window.history.back();
    </script>";
}
}
?>
