in this edit codes (<?php
// drivers_list.php

// Include authentication, database connection, and functions
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php';

// Start session to handle flash messages
session_start();

// Initialize variables for messages
$errors = [];
$success = "";

// Retrieve flash messages from session
if (isset($_SESSION['success'])) {
    $success = $_SESSION['success'];
    unset($_SESSION['success']);
}

if (isset($_SESSION['errors']) && !empty($_SESSION['errors'])) {
    $errors = $_SESSION['errors'];
    unset($_SESSION['errors']);
}

// Initialize filter and sort variables
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$filter_star = isset($_GET['filter_star']) ? intval($_GET['filter_star']) : 0; // 1 to filter starred drivers
$sort = isset($_GET['sort']) ? trim($_GET['sort']) : 'star_desc';

// Handle Form Submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle Add New Driver
    if (isset($_POST['add_driver'])) {
        $name = trim($_POST['name']);
        $number = trim($_POST['number']);
        $is_star = isset($_POST['is_star']) ? intval($_POST['is_star']) : 0;

        // Basic validation
        if (empty($name) || empty($number)) {
            $errors[] = "Driver name and number are required.";
        } else {
            // Insert into database using prepared statements to prevent SQL injection
            $stmt = $conn->prepare("INSERT INTO drivers (name, number, is_star) VALUES (?, ?, ?)");
            if ($stmt) {
                $stmt->bind_param("ssi", $name, $number, $is_star);
                if ($stmt->execute()) {
                    $_SESSION['success'] = "New driver added successfully.";
                } else {
                    $errors[] = "Error adding driver: " . htmlspecialchars($stmt->error, ENT_QUOTES, 'UTF-8');
                }
                $stmt->close();
            } else {
                $errors[] = "Database error: Unable to prepare statement.";
            }
        }
        // Redirect to avoid form resubmission
        $_SESSION['errors'] = $errors;
        header("Location: drivers_list.php" . buildQueryString(['filter_star' => $filter_star, 'sort' => $sort, 'search' => $search]));
        exit();
    }

    // Handle Toggle Star Status
    if (isset($_POST['toggle_star'])) {
        $driver_id = intval($_POST['id']);
        $new_star_status = intval($_POST['is_star']); // Expected 0 or 1

        if ($driver_id > 0 && in_array($new_star_status, [0, 1])) {
            $stmt = $conn->prepare("UPDATE drivers SET is_star = ? WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param("ii", $new_star_status, $driver_id);
                if ($stmt->execute()) {
                    $status = $new_star_status ? 'starred as important' : 'unstarred';
                    $_SESSION['success'] = "Driver successfully $status.";
                } else {
                    $errors[] = "Error updating star status: " . htmlspecialchars($stmt->error, ENT_QUOTES, 'UTF-8');
                }
                $stmt->close();
            } else {
                $errors[] = "Database error: Unable to prepare statement.";
            }
        } else {
            $errors[] = "Invalid driver ID or star status.";
        }
        // Redirect to avoid form resubmission
        $_SESSION['errors'] = $errors;
        header("Location: drivers_list.php" . buildQueryString(['filter_star' => $filter_star, 'sort' => $sort, 'search' => $search]));
        exit();
    }
}

/**
 * Helper function to build query strings while preserving existing parameters.
 *
 * @param array $params Key-value pairs to include in the query string.
 * @return string The built query string starting with '?' or '&'.
 */
function buildQueryString($params = [])
{
    // Preserve existing GET parameters
    foreach ($params as $key => $value) {
        $_GET[$key] = $value;
    }
    $query = http_build_query($_GET);
    return '?' . $query;
}

// Function to format phone numbers for WhatsApp links
function formatPhoneNumberForWhatsApp($number)
{
    // Strip out non-numeric characters and add country code if needed
    $formatted = preg_replace('/\D/', '', $number);
    // Ensure the number starts with the country code, e.g., '965' for Kuwait
    if (strpos($formatted, '965') !== 0) {
        $formatted = '965' . $formatted;
    }
    return $formatted;
}

// Determine sorting order
switch ($sort) {
    case 'name_asc':
        $order_by = 'name ASC';
        break;
    case 'name_desc':
        $order_by = 'name DESC';
        break;
    case 'number_asc':
        $order_by = 'number ASC';
        break;
    case 'number_desc':
        $order_by = 'number DESC';
        break;
    case 'star_asc':
        $order_by = 'is_star ASC, name ASC'; // Non-starred first
        break;
    case 'star_desc':
    default:
        $order_by = 'is_star DESC, name ASC'; // Starred first
}

// Prepare the SQL statement
if (!empty($search)) {
    // Use prepared statements to prevent SQL injection
    $stmt = $conn->prepare("SELECT * FROM drivers WHERE (name LIKE ? OR number LIKE ?) " . ($filter_star ? "AND is_star = 1 " : "") . "ORDER BY $order_by");
    if ($stmt) {
        $like_search = '%' . $search . '%';
        $stmt->bind_param("ss", $like_search, $like_search);
    } else {
        die('Database error: ' . htmlspecialchars(mysqli_error($conn), ENT_QUOTES, 'UTF-8'));
    }
} else {
    $stmt = $conn->prepare("SELECT * FROM drivers " . ($filter_star ? "WHERE is_star = 1 " : "") . "ORDER BY $order_by");
    if (!$stmt) {
        die('Database error: ' . htmlspecialchars(mysqli_error($conn), ENT_QUOTES, 'UTF-8'));
    }
}

// Execute the statement and fetch results
$stmt->execute();
$result = $stmt->get_result();
if (!$result) {
    die('Query failed: ' . htmlspecialchars(mysqli_error($conn), ENT_QUOTES, 'UTF-8'));
}

// Now include the header AFTER all PHP processing is done
require_once '../../includes/header.php';
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drivers List</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Bootstrap Icons CDN -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <!-- Custom Styles -->
    <style>
        /* Custom Modal Styles */
        .modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 50;
            /* Sit on top */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgba(0, 0, 0, 0.5);
            /* Black w/ opacity */
        }

        .modal-content {
            background-color: white;
            margin: 5%;
            /* 5% from the top and centered */
            padding: 20px;
            border: 1px solid #888;
            width: 90%;
            max-width: 500px;
            /* Could be more or less, depending on screen size */
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 1.5rem;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover,
        .close:focus {
            color: #000;
        }

        /* Tooltip Styles */
        .tooltip {
            position: relative;
            display: inline-block;
        }

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 160px;
            background-color: #333;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 5px 0;

            /* Position the tooltip */
            position: absolute;
            z-index: 10;
            bottom: 125%;
            left: 50%;
            margin-left: -80px;

            /* Fade in tooltip */
            opacity: 0;
            transition: opacity 0.3s;
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }

        /* Enhanced Star Icon Styles */
        .star-btn {
            transition: color 0.3s, transform 0.2s;
        }

        .star-btn:hover {
            transform: scale(1.2);
            color: #20B2AA;
            /* Teal accent on hover */
        }

        /* Enhanced Scrollbar Styles */
        /* For WebKit browsers */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #a0aec0;
        }

        /* Responsive Grid */
        @media (max-width: 640px) {
            #driversGrid {
                grid-template-columns: repeat(1, minmax(0, 1fr));
            }
        }

        /* Add Driver Button Hover Effect */
        #addDriverBtn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        /* Notification Close Button Styling */
        .notification-close-button {
            cursor: pointer;
        }

        .notification-close-button:hover {
            color: #000;
        }
    </style>
</head>

<body class="bg-gray-100 min-h-screen font-sans">
    <div class="container mx-auto px-4 py-8">
        <!-- Header Section -->
        <div class="flex flex-col md:flex-row items-center justify-between mb-6">
            <h2 class="text-3xl font-bold text-teal-600">Drivers List</h2>
            <div class="flex items-center space-x-4 mt-4 md:mt-0">
                <button id="toggleStarred"
                    class="bg-teal-400 text-white px-4 py-2 rounded-md shadow hover:bg-teal-500 transition flex items-center focus:outline-none focus:ring-2 focus:ring-teal-500">
                    <?php if ($filter_star): ?>
                        <i class="bi bi-star-fill mr-2"></i> Show All
                    <?php else: ?>
                        <i class="bi bi-star mr-2"></i> Show Starred
                    <?php endif; ?>
                </button>
                <button id="addDriverBtn"
                    class="bg-teal-600 text-white px-4 py-2 rounded-md shadow hover:bg-teal-700 transition flex items-center focus:outline-none focus:ring-2 focus:ring-teal-500">
                    <i class="bi bi-plus-circle-fill mr-2"></i> Add Driver
                </button>
            </div>
        </div>

        <!-- Filter and Search Section -->
        <div class="flex flex-col md:flex-row items-center justify-between mb-6">
            <form method="GET" action="drivers_list.php" id="searchForm"
                class="flex flex-col md:flex-row items-center w-full md:w-auto space-y-4 md:space-y-0">
                <div class="flex items-center border border-gray-300 rounded-md overflow-hidden">
                    <input type="text" name="search" id="searchInput" placeholder="Search by name or number..."
                        value="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>"
                        class="w-full px-4 py-2 focus:outline-none focus:ring-2 focus:ring-teal-500">
                </div>
                <div class="flex items-center space-x-4">
                    <select name="sort" id="sortSelect" onchange="this.form.submit()"
                        class="px-4 py-2 border border-gray-300 bg-white rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500">
                        <option value="star_desc" <?= ($sort === 'star_desc') ? 'selected' : '' ?>>Starred First</option>
                        <option value="star_asc" <?= ($sort === 'star_asc') ? 'selected' : '' ?>>Starred Last</option>
                        <option value="name_asc" <?= ($sort === 'name_asc') ? 'selected' : '' ?>>Sort by Name (A-Z)</option>
                        <option value="name_desc" <?= ($sort === 'name_desc') ? 'selected' : '' ?>>Sort by Name (Z-A)</option>
                        <option value="number_asc" <?= ($sort === 'number_asc') ? 'selected' : '' ?>>Sort by Number (Ascending)</option>
                        <option value="number_desc" <?= ($sort === 'number_desc') ? 'selected' : '' ?>>Sort by Number (Descending)</option>
                        <option value="recent_desc" <?= ($sort === 'recent_desc') ? 'selected' : '' ?>>Recently Added</option>
                        <option value="recent_asc" <?= ($sort === 'recent_asc') ? 'selected' : '' ?>>Oldest Added</option>
                    </select>
                    <button type="submit"
                        class="bg-teal-500 text-white px-4 py-2 rounded-md hover:bg-teal-600 transition focus:outline-none focus:ring-2 focus:ring-teal-500">Search</button>
                </div>
            </form>
        </div>

        <!-- Success and Error Messages -->
        <?php if (!empty($success)): ?>
            <div
                class="mb-4 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative flex items-center"
                role="alert">
                <i class="bi bi-check-circle-fill mr-2"></i>
                <span class="flex-grow"><?= htmlspecialchars($success, ENT_QUOTES, 'UTF-8') ?></span>
                <span class="notification-close-button ml-4">
                    <i class="bi bi-x-circle-fill text-2xl"></i>
                </span>
            </div>
        <?php endif; ?>

        <?php if (!empty($errors)): ?>
            <div
                class="mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative flex items-center"
                role="alert">
                <i class="bi bi-exclamation-octagon-fill mr-2"></i>
                <span class="flex-grow">
                    <ul class="list-disc pl-5">
                        <?php foreach ($errors as $error): ?>
                            <li><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></li>
                        <?php endforeach; ?>
                    </ul>
                </span>
                <span class="notification-close-button ml-4">
                    <i class="bi bi-x-circle-fill text-2xl"></i>
                </span>
            </div>
        <?php endif; ?>

        <!-- Drivers Grid -->
        <div id="driversGrid" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            <?php if ($result->num_rows > 0): ?>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <?php
                        // Determine background color based on is_star
                        $bg_color = $row['is_star'] ? 'bg-teal-100' : 'bg-white';
                    ?>
                    <div
                        class="rounded-lg shadow-md p-6 flex flex-col justify-between transform transition-transform hover:scale-105 <?= $bg_color ?>">
                        <div>
                            <h3 class="text-xl font-semibold text-teal-600 mb-2 flex items-center">
                                <?= htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') ?>
                                <!-- Star Icon with Tooltip -->
                                <div class="tooltip ml-2">
                                    <form action="drivers_list.php<?= buildQueryString(['filter_star' => $filter_star, 'sort' => $sort, 'search' => $search]) ?>"
                                        method="POST" class="inline">
                                        <input type="hidden" name="id" value="<?= htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8') ?>">
                                        <input type="hidden" name="is_star" value="<?= $row['is_star'] ? 0 : 1; ?>">
                                        <button type="submit" name="toggle_star" class="focus:outline-none star-btn" aria-label="<?= $row['is_star'] ? 'Unmark as Important' : 'Mark as Important' ?>">
                                            <?php if ($row['is_star']): ?>
                                                <i class="bi bi-star-fill text-yellow-500 text-lg"></i>
                                            <?php else: ?>
                                                <i
                                                    class="bi bi-star text-gray-400 text-lg hover:text-yellow-500 transition-colors"></i>
                                            <?php endif; ?>
                                        </button>
                                        <span class="tooltiptext text-xs text-white"><?= $row['is_star'] ? 'Unmark as Important' : 'Mark as Important' ?></span>
                                    </form>
                                </div>
                            </h3>
                            <p class="text-gray-700 mb-4 flex items-center">
                                <i class="bi bi-telephone-fill mr-2 text-teal-500"></i><?= htmlspecialchars($row['number'], ENT_QUOTES, 'UTF-8') ?>
                            </p>
                        </div>
                        <div class="mt-4 flex justify-between items-center">
                            <a href="https://wa.me/<?= formatPhoneNumberForWhatsApp($row['number']); ?>" target="_blank"
                                class="bg-green-500 text-white px-3 py-2 rounded-md flex items-center hover:bg-green-600 transition focus:outline-none focus:ring-2 focus:ring-green-500">
                                <i class="bi bi-whatsapp mr-2"></i> 
                            </a>
                            <div class="flex space-x-2 items-center">
                                <a href="edit_driver.php?id=<?= htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'); ?>"
                                    class="bg-teal-500 text-white px-3 py-2 rounded-md flex items-center hover:bg-teal-600 transition focus:outline-none focus:ring-2 focus:ring-teal-500">
                                    <i class="bi bi-pencil-square mr-2"></i> 
                                </a>
                                <form action="delete_driver.php" method="POST" onsubmit="return confirm('Are you sure you want to delete this driver?');"
                                    class="inline">
                                    <input type="hidden" name="id" value="<?= htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'); ?>">
                                    <button type="submit" name="delete_driver"
                                        class="bg-red-500 text-white px-3 py-2 rounded-md flex items-center hover:bg-red-600 transition focus:outline-none focus:ring-2 focus:ring-red-500">
                                        <i class="bi bi-trash-fill mr-2"></i> 
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <p class="col-span-full text-center text-gray-600">No drivers found.</p>
            <?php endif; ?>
        </div>

        <!-- Add Driver Modal -->
        <div id="addDriverModal" class="modal">
            <div class="modal-content">
                <span class="close" id="closeModal">&times;</span>
                <h2 class="text-2xl font-bold mb-4 text-teal-600">Add New Driver</h2>
                <form action="drivers_list.php<?= buildQueryString(['filter_star' => $filter_star, 'sort' => $sort, 'search' => $search]) ?>" method="POST">
                    <div class="mb-4">
                        <label for="name" class="block text-gray-700">Driver Name <span class="text-red-500">*</span></label>
                        <input type="text" id="name" name="name" required
                            class="w-full mt-1 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500">
                    </div>
                    <div class="mb-4">
                        <label for="number" class="block text-gray-700">Driver Number <span
                                class="text-red-500">*</span></label>
                        <input type="text" id="number" name="number" required placeholder="+1234567890"
                            class="w-full mt-1 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-teal-500">
                    </div>
                    <div class="mb-6">
                        <label for="is_star" class="block text-gray-700">Important</label>
                        <div class="mt-2">
                            <input type="checkbox" id="is_star" name="is_star" value="1" class="mr-2">
                            <label for="is_star" class="text-gray-700">Mark as Important</label>
                        </div>
                    </div>
                    <div class="flex justify-end">
                        <button type="button" id="cancelBtn"
                            class="bg-gray-500 text-white px-4 py-2 rounded-md mr-2 hover:bg-gray-600 transition focus:outline-none focus:ring-2 focus:ring-gray-500">Cancel</button>
                        <button type="submit" name="add_driver"
                            class="bg-teal-600 text-white px-4 py-2 rounded-md hover:bg-teal-700 transition focus:outline-none focus:ring-2 focus:ring-teal-500">Add Driver</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Include the footer -->
    <?php
    require_once '../../includes/footer.php';
    ?>

    <!-- JavaScript for Modal Functionality and Real-Time Search -->
    <script>
        // Modal Elements
        const modal = document.getElementById("addDriverModal");
        const addDriverBtn = document.getElementById("addDriverBtn");
        const closeModal = document.getElementById("closeModal");
        const cancelBtn = document.getElementById("cancelBtn");
        const notificationCloseButtons = document.querySelectorAll('.notification-close-button');

        // Open the modal when the user clicks the Add Driver button
        addDriverBtn.onclick = function () {
            modal.style.display = "block";
        }

        // Close the modal when the user clicks on <span> (x)
        closeModal.onclick = function () {
            modal.style.display = "none";
        }

        // Close the modal when the user clicks on Cancel button
        cancelBtn.onclick = function () {
            modal.style.display = "none";
        }

        // Close the modal when the user clicks anywhere outside of the modal
        window.onclick = function (event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }

        // Real-Time Search Functionality
        const searchInput = document.getElementById('searchInput');

        searchInput.addEventListener('input', function () {
            // Debounce to prevent too many submissions
            clearTimeout(this.delay);
            this.delay = setTimeout(() => {
                document.getElementById('searchForm').submit();
            }, 500);
        });

        // Toggle Starred Drivers Filter
        const toggleStarredBtn = document.getElementById('toggleStarred');

        toggleStarredBtn.addEventListener('click', function () {
            const currentURL = new URL(window.location.href);
            const filterStar = currentURL.searchParams.get('filter_star') === '1' ? 0 : 1;
            currentURL.searchParams.set('filter_star', filterStar);
            // Reset search if filtering
            if (filterStar) {
                currentURL.searchParams.delete('search');
            }
            window.location.href = currentURL.toString();
        });

        // Close notification messages when close button is clicked
        notificationCloseButtons.forEach(button => {
            button.addEventListener('click', () => {
                button.parentElement.style.display = 'none';
            });
        });
    </script>
</body>

</html>) make it readable and so amazing and make edit as popup not page and make it cool ldesig and add more codes and make actions button without text and type full codes