<?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 buses WHERE id = ?");
    $stmt->execute([$_GET['delete']]);
    header('Location: buses.php');
}

// Handle Add
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_bus'])) {
    $stmt = $pdo->prepare("INSERT INTO buses (bus_number, route_name, model, capacity) VALUES (?, ?, ?, ?)");
    $stmt->execute([$_POST['bus_number'], $_POST['route_name'], $_POST['model'], $_POST['capacity']]);
    header('Location: buses.php');
}

// Handle Edit
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_bus'])) {
    $stmt = $pdo->prepare("UPDATE buses SET bus_number = ?, route_name = ?, model = ?, capacity = ?, status = ? WHERE id = ?");
    $stmt->execute([$_POST['bus_number'], $_POST['route_name'], $_POST['model'], $_POST['capacity'], $_POST['status'], $_POST['id']]);
    header('Location: buses.php');
}

$buses = $pdo->query("SELECT b.*, COUNT(s.id) as student_count FROM buses b LEFT JOIN students s ON b.id = s.bus_id GROUP BY b.id ORDER BY b.created_at DESC")->fetchAll();
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
    <h2>Manage Buses</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 Bus
    </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;">ID</th>
                <th style="padding: 1rem;">Bus Number</th>
                <th style="padding: 1rem;">Route Name</th>
                <th style="padding: 1rem;">Model</th>
                <th style="padding: 1rem;">Capacity</th>
                <th style="padding: 1rem;">Students</th>
                <th style="padding: 1rem;">Status</th>
                <th style="padding: 1rem;">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($buses as $bus): ?>
            <tr style="border-bottom: 1px solid #eee;">
                <td style="padding: 1rem;"><?= $bus['id'] ?></td>
                <td style="padding: 1rem;"><strong><?= $bus['bus_number'] ?></strong></td>
                <td style="padding: 1rem;"><?= $bus['route_name'] ?: '<em>Not Set</em>' ?></td>
                <td style="padding: 1rem;"><?= $bus['model'] ?></td>
                <td style="padding: 1rem;"><?= $bus['capacity'] ?></td>
                <td style="padding: 1rem;">
                    <span style="font-weight: bold; color: var(--primary)"><?= $bus['student_count'] ?></span>
                </td>
                <td style="padding: 1rem;">
                    <span style="padding: 0.3rem 0.8rem; border-radius: 1rem; font-size: 0.8rem; background: <?= $bus['status'] == 'active' ? '#e1f7f0; color: #1dbf73' : '#ffeaea; color: #f94144' ?>">
                        <?= ucfirst($bus['status']) ?>
                    </span>
                </td>
                <td style="padding: 1rem;">
                    <a href="javascript:void(0)" style="color: var(--primary); margin-right: 1rem;" onclick='openEditModal(<?= json_encode($bus) ?>)'>
                        <i class="fas fa-edit"></i>
                    </a>
                    <a href="?delete=<?= $bus['id'] ?>" style="color: var(--danger)" onclick="return confirm('Delete this bus?')">
                        <i class="fas fa-trash"></i>
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Simple 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;">
    <div class="card" style="width: 400px; margin-bottom: 0;">
        <h3>Add New Bus</h3><br>
        <form method="POST">
            <input type="hidden" name="add_bus" value="1">
            <div class="form-group">
                <label>Bus Number</label>
                <input type="text" name="bus_number" class="form-control" required placeholder="e.g. BA 1 PA 1234">
            </div>
            <div class="form-group">
                <label>Route Name</label>
                <input type="text" name="route_name" class="form-control" placeholder="e.g. Kalanki - Ratnapark">
            </div>
            <div class="form-group">
                <label>Model</label>
                <input type="text" name="model" class="form-control" placeholder="e.g. Tata Starbus">
            </div>
            <div class="form-group">
                <label>Capacity</label>
                <input type="number" name="capacity" class="form-control" placeholder="e.g. 35">
            </div>
            <div style="display: flex; gap: 1rem;">
                <button type="submit" class="btn btn-primary">Save Bus</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: 400px; max-height: 90vh; overflow-y: auto; margin-bottom: 0;">
        <h3>Edit Bus</h3><br>
        <form method="POST">
            <input type="hidden" name="edit_bus" value="1">
            <input type="hidden" name="id" id="edit_id">
            <div class="form-group">
                <label>Bus Number</label>
                <input type="text" name="bus_number" id="edit_bus_number" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Route Name</label>
                <input type="text" name="route_name" id="edit_route_name" class="form-control">
            </div>
            <div class="form-group">
                <label>Model</label>
                <input type="text" name="model" id="edit_model" class="form-control">
            </div>
            <div class="form-group">
                <label>Capacity</label>
                <input type="number" name="capacity" id="edit_capacity" class="form-control">
            </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 Bus</button>
                <button type="button" class="btn" onclick="document.getElementById('editModal').style.display='none'">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
function openEditModal(bus) {
    document.getElementById('edit_id').value = bus.id;
    document.getElementById('edit_bus_number').value = bus.bus_number;
    document.getElementById('edit_route_name').value = bus.route_name || '';
    document.getElementById('edit_model').value = bus.model || '';
    document.getElementById('edit_capacity').value = bus.capacity || '';
    document.getElementById('edit_status').value = bus.status;
    document.getElementById('editModal').style.display = 'flex';
}
</script>

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