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

if (!isset($_GET['id']) || empty($_GET['id'])) {
    die("Invalid request.");
}

$category_id = intval($_GET['id']);

// Check if the category is associated with any cars
$check_query = "SELECT COUNT(*) AS count FROM jostj_vikrentcar_cars WHERE idcat LIKE '%$category_id;%'";
$result = mysqli_query($db2, $check_query);

if (!$result) {
    die("Error checking category: " . mysqli_error($db2));
}

$row = mysqli_fetch_assoc($result);

if ($row['count'] > 0) {
    // If there are cars using this category, show an error message and redirect back
    echo "<script>
        alert('This category is currently associated with cars and cannot be deleted.');
        window.location.href = '../categories.php';
    </script>";
    exit;
}

// If no cars are using this category, ask for confirmation
if (isset($_GET['confirm']) && $_GET['confirm'] == 'yes') {
    // Get the category details before deletion
    $category_query = "SELECT * FROM jostj_vikrentcar_categories WHERE id = $category_id";
    $category_result = mysqli_query($db2, $category_query);
    $category_details = mysqli_fetch_assoc($category_result);

    $delete_query = "DELETE FROM jostj_vikrentcar_categories WHERE id = $category_id";
    if (mysqli_query($db2, $delete_query)) {
        // Log the deletion
        $action = "Delete Category";
        $details = "Deleted category {$category_details['id']}, {$category_details['name']}";
        $log_query = "INSERT INTO action_logs (action, details, user) VALUES ('$action', '$details', '$user')";
        mysqli_query($db2, $log_query);

        echo "<script>
            alert('Category deleted successfully.');
            window.location.href = '../categories.php';
        </script>";
    } else {
        echo "<script>
            alert('Error deleting category: " . mysqli_error($db2) . "');
            window.location.href = '../categories.php';
        </script>";
    }
    exit;
}

// If no confirmation, show the confirmation dialog
echo "<script>
    if (confirm('No cars are using this category. Are you sure you want to delete it?')) {
        window.location.href = 'delete_category.php?id=$category_id&confirm=yes';
    } else {
        window.location.href = '../categories.php';
    }
</script>";
