<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../includes/db.php';
include '../includes/header_admin.php';

// Handle Delete
if (isset($_GET['delete'])) {
    $stmt = $pdo->prepare("DELETE FROM drivers WHERE id = ?");
    $stmt->execute([$_GET['delete']]);
    header('Location: drivers.php');
}

// Handle Add
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_driver'])) {
    $passHash = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $stmt = $pdo->prepare("INSERT INTO drivers (name, phone, password, bus_id) VALUES (?, ?, ?, ?)");
    $stmt->execute([$_POST['name'], $_POST['phone'], $passHash, $_POST['bus_id']]);
    header('Location: drivers.php');
}

// Handle Edit
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_driver'])) {
    if (!empty($_POST['password'])) {
        $passHash = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE drivers SET name = ?, phone = ?, password = ?, bus_id = ?, status = ? WHERE id = ?");
        $stmt->execute([$_POST['name'], $_POST['phone'], $passHash, $_POST['bus_id'], $_POST['status'], $_POST['id']]);
    } else {
        $stmt = $pdo->prepare("UPDATE drivers SET name = ?, phone = ?, bus_id = ?, status = ? WHERE id = ?");
        $stmt->execute([$_POST['name'], $_POST['phone'], $_POST['bus_id'], $_POST['status'], $_POST['id']]);
    }
    header('Location: drivers.php');
}

$drivers = $pdo->query("SELECT d.*, b.bus_number, b.route_name FROM drivers d LEFT JOIN buses b ON d.bus_id = b.id ORDER BY d.created_at DESC")->fetchAll();
$buses = $pdo->query("SELECT * FROM buses WHERE status = 'active'")->fetchAll();
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
    <h2>Manage Drivers</h2>
    <button class="btn btn-primary" style="width: auto; padding: 0.5rem 1.5rem" onclick="document.getElementById('addModal').style.display='flex'">
        <i class="fas fa-plus"></i> Add New Driver
    </button>
</div>

<div class="card">
    <table style="width: 100%; border-collapse: collapse;">
        <thead>
            <tr style="text-align: left; border-bottom: 2px solid #eee;">
                <th style="padding: 1rem;">Name</th>
                <th style="padding: 1rem;">Phone</th>
                <th style="padding: 1rem;">Assigned Bus</th>
                <th style="padding: 1rem;">API Key</th>
                <th style="padding: 1rem;">Status</th>
                <th style="padding: 1rem;">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($drivers as $driver): ?>
            <tr style="border-bottom: 1px solid #eee;">
                <td style="padding: 1rem;"><strong><?= $driver['name'] ?></strong></td>
                <td style="padding: 1rem;"><?= $driver['phone'] ?></td>
                <td style="padding: 1rem;"><?= $driver['bus_number'] ? $driver['bus_number'].' ('.$driver['route_name'].')' : '<em>Unassigned</em>' ?></td>
                <td style="padding: 1rem;"><code style="font-size: 0.8rem;"><?= substr($driver['api_key'] ?? '', 0, 10) ?>...</code></td>
                <td style="padding: 1rem;">
                    <span style="padding: 0.3rem 0.8rem; border-radius: 1rem; font-size: 0.8rem; background: <?= $driver['status'] == 'active' ? '#e1f7f0; color: #1dbf73' : '#ffeaea; color: #f94144' ?>">
                        <?= ucfirst($driver['status']) ?>
                    </span>
                </td>
                <td style="padding: 1rem;">
                    <a href="javascript:void(0)" style="color: var(--primary); margin-right: 1rem;" onclick='openEditModal(<?= json_encode($driver) ?>)'>
                        <i class="fas fa-edit"></i>
                    </a>
                    <a href="?delete=<?= $driver['id'] ?>" style="color: var(--danger)" onclick="return confirm('Delete this driver?')">
                        <i class="fas fa-trash"></i>
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Add Modal -->
<div id="addModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); justify-content: center; align-items: center; z-index: 1000; padding: 20px;">
    <div class="card" style="width: 450px; max-height: 90vh; overflow-y: auto; margin-bottom: 0;">
        <h3>Add New Driver</h3><br>
        <form method="POST">
            <input type="hidden" name="add_driver" value="1">
            <div class="form-group">
                <label>Full Name</label>
                <input type="text" name="name" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Phone Number</label>
                <input type="text" name="phone" class="form-control" required>
            </div>
            <div class="form-group">
                <label>App Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Assign Bus</label>
                <select name="bus_id" class="form-control">
                    <option value="">Select a Bus</option>
                    <?php foreach ($buses as $bus): ?>
                        <option value="<?= $bus['id'] ?>"><?= $bus['bus_number'] ?> (<?= $bus['route_name'] ?>)</option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="display: flex; gap: 1rem;">
                <button type="submit" class="btn btn-primary">Create Driver Account</button>
                <button type="button" class="btn" onclick="document.getElementById('addModal').style.display='none'">Cancel</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Modal -->
<div id="editModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); justify-content: center; align-items: center; z-index: 1000; padding: 20px;">
    <div class="card" style="width: 450px; max-height: 90vh; overflow-y: auto; margin-bottom: 0;">
        <h3>Edit Driver</h3><br>
        <form method="POST">
            <input type="hidden" name="edit_driver" value="1">
            <input type="hidden" name="id" id="edit_id">
            <div class="form-group">
                <label>Full Name</label>
                <input type="text" name="name" id="edit_name" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Phone Number</label>
                <input type="text" name="phone" id="edit_phone" class="form-control" required>
            </div>
            <div class="form-group">
                <label>App Password (leave blank to keep current)</label>
                <input type="password" name="password" class="form-control">
            </div>
            <div class="form-group">
                <label>Assign Bus</label>
                <select name="bus_id" id="edit_bus_id" class="form-control">
                    <option value="">Select a Bus</option>
                    <?php foreach ($buses as $bus): ?>
                        <option value="<?= $bus['id'] ?>"><?= $bus['bus_number'] ?> (<?= $bus['route_name'] ?>)</option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Status</label>
                <select name="status" id="edit_status" class="form-control">
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                </select>
            </div>
            <div style="display: flex; gap: 1rem;">
                <button type="submit" class="btn btn-primary">Update Driver Account</button>
                <button type="button" class="btn" onclick="document.getElementById('editModal').style.display='none'">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
function openEditModal(driver) {
    document.getElementById('edit_id').value = driver.id;
    document.getElementById('edit_name').value = driver.name;
    document.getElementById('edit_phone').value = driver.phone;
    document.getElementById('edit_bus_id').value = driver.bus_id || '';
    document.getElementById('edit_status').value = driver.status;
    document.getElementById('editModal').style.display = 'flex';
}
</script>

<?php include '../includes/footer_admin.php'; ?>
