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

// Handle Add
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_student'])) {
    $stmt = $pdo->prepare("INSERT INTO students (name, grade, parent_phone, bus_id, stop_id, latitude, longitude, nfc_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$_POST['name'], $_POST['grade'], $_POST['parent_phone'], $_POST['bus_id'], $_POST['stop_id'] ?: null, $_POST['latitude'], $_POST['longitude'], $_POST['nfc_id'] ?: null]);
    header('Location: students.php');
}

// Handle Edit
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_student'])) {
    $stmt = $pdo->prepare("UPDATE students SET name = ?, grade = ?, parent_phone = ?, bus_id = ?, stop_id = ?, latitude = ?, longitude = ?, nfc_id = ? WHERE id = ?");
    $stmt->execute([$_POST['name'], $_POST['grade'], $_POST['parent_phone'], $_POST['bus_id'], $_POST['stop_id'] ?: null, $_POST['latitude'], $_POST['longitude'], $_POST['nfc_id'] ?: null, $_POST['id']]);
    header('Location: students.php');
}

// Filtering Logic
$whereClause = "TRUE";
$params = [];

if (!empty($_GET['search'])) {
    $whereClause .= " AND s.name LIKE ?";
    $params[] = '%' . $_GET['search'] . '%';
}
if (!empty($_GET['filter_bus'])) {
    $whereClause .= " AND s.bus_id = ?";
    $params[] = $_GET['filter_bus'];
}
if (!empty($_GET['filter_grade'])) {
    $whereClause .= " AND s.grade = ?";
    $params[] = $_GET['filter_grade'];
}

$students = $pdo->prepare("SELECT s.*, b.bus_number, b.route_name, bs.stop_name 
                           FROM students s 
                           LEFT JOIN buses b ON s.bus_id = b.id 
                           LEFT JOIN bus_stops bs ON s.stop_id = bs.id
                           WHERE $whereClause 
                           ORDER BY s.created_at DESC");
$students->execute($params);
$students = $students->fetchAll();

$buses = $pdo->query("SELECT * FROM buses WHERE status = 'active'")->fetchAll();
$grades = $pdo->query("SELECT DISTINCT grade FROM students WHERE grade IS NOT NULL AND grade != '' ORDER BY grade ASC")->fetchAll(PDO::FETCH_COLUMN);
$bus_stops = $pdo->query("SELECT * FROM bus_stops ORDER BY bus_id, stop_order")->fetchAll();
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
    <h2>Registered Students</h2>
    <button class="btn btn-primary" style="width: auto; padding: 0.5rem 1.5rem" onclick="openAddModal()">
        <i class="fas fa-plus"></i> Add New Student
    </button>
</div>

<!-- Filters Section -->
<div class="card" style="margin-bottom: 2rem; padding: 1.5rem;">
    <form method="GET" style="display: flex; gap: 1rem; align-items: flex-end; flex-wrap: wrap;">
        <div class="form-group" style="flex: 2; min-width: 200px; margin: 0;">
            <label>Search Name</label>
            <input type="text" name="search" class="form-control" placeholder="Student name..." value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
        </div>
        <div class="form-group" style="flex: 1; min-width: 150px; margin: 0;">
            <label>Filter Bus</label>
            <select name="filter_bus" class="form-control">
                <option value="">All Buses</option>
                <?php foreach ($buses as $bus): ?>
                    <option value="<?= $bus['id'] ?>" <?= ($_GET['filter_bus'] ?? '') == $bus['id'] ? 'selected' : '' ?>>
                        <?= $bus['bus_number'] ?> (<?= $bus['route_name'] ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group" style="flex: 1; min-width: 150px; margin: 0;">
            <label>Filter Grade</label>
            <select name="filter_grade" class="form-control">
                <option value="">All Grades</option>
                <?php foreach ($grades as $grade): ?>
                    <option value="<?= htmlspecialchars($grade) ?>" <?= ($_GET['filter_grade'] ?? '') == $grade ? 'selected' : '' ?>>
                        <?= htmlspecialchars($grade) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div style="display: flex; gap: 0.5rem;">
            <button type="submit" class="btn btn-primary" style="width: auto; padding: 0.6rem 1.2rem;">
                <i class="fas fa-filter"></i> Apply
            </button>
            <a href="students.php" class="btn" style="width: auto; padding: 0.6rem 1.2rem; background: #eee; text-decoration: none; color: #333; display: inline-flex; align-items: center; justify-content: center; height: 100%;">
                <i class="fas fa-redo" style="margin-right: 5px;"></i> Clear
            </a>
        </div>
    </form>
</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;">Student Name</th>
                <th style="padding: 1rem;">Grade</th>
                <th style="padding: 1rem;">Parent Phone</th>
                <th style="padding: 1rem;">Bus Route</th>
                <th style="padding: 1rem;">Assigned Stop</th>
                <th style="padding: 1rem;">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($students as $student): ?>
            <tr style="border-bottom: 1px solid #eee;">
                <td style="padding: 1rem;"><strong><?= $student['name'] ?></strong></td>
                <td style="padding: 1rem;"><?= $student['grade'] ?></td>
                <td style="padding: 1rem;"><?= $student['parent_phone'] ?></td>
                <td style="padding: 1rem;"><?= $student['bus_number'] ? $student['bus_number'].' ('.$student['route_name'].')' : '<em>No Route</em>' ?></td>
                <td style="padding: 1rem;"><strong><?= htmlspecialchars($student['stop_name'] ?? 'Not Set') ?></strong></td>
                <td style="padding: 1rem;">
                    <a href="javascript:void(0)" style="color: var(--primary); margin-right: 1rem;" onclick='openEditModal(<?= json_encode($student) ?>)'>
                        <i class="fas fa-edit"></i>
                    </a>
                    <a href="?delete=<?= $student['id'] ?>" style="color: var(--danger)" onclick="return confirm('Delete this student?')">
                        <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 Student</h3><br>
        <form method="POST">
            <input type="hidden" name="add_student" value="1">
            <div class="form-group">
                <label>Student Full Name</label>
                <input type="text" name="name" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Grade/Class</label>
                <input type="text" name="grade" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Parent Phone Number</label>
                <input type="text" name="parent_phone" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Assign to Bus Route</label>
                <select name="bus_id" id="add_bus_id" class="form-control" onchange="updateStopList('add', this.value)">
                    <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 id="addStopSelection" class="form-group" style="display: none;">
                <label>Select Pickup Stop</label>
                <select name="stop_id" id="add_stop_id" class="form-control" onchange="setStopCoords('add', this.value)">
                    <option value="">-- Select a Stop --</option>
                </select>
            </div>
            <div class="form-group">
                <label>NFC Tag ID (Optional)</label>
                <input type="text" name="nfc_id" id="add_nfc_id" class="form-control" placeholder="e.g. 04:A1:B2:C3">
            </div>
            <div style="display: flex; gap: 1rem;">
                <div class="form-group" style="flex: 1;">
                    <label>Pickup Latitude</label>
                    <input type="text" name="latitude" id="add_latitude" class="form-control" placeholder="e.g. 27.7172">
                </div>
                <div class="form-group" style="flex: 1;">
                    <label>Pickup Longitude</label>
                    <input type="text" name="longitude" id="add_longitude" class="form-control" placeholder="e.g. 85.3240">
                </div>
            </div>
            <div style="display: flex; gap: 1rem;">
                <button type="submit" class="btn btn-primary">Save Student</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 Student</h3><br>
        <form method="POST">
            <input type="hidden" name="edit_student" value="1">
            <input type="hidden" name="id" id="edit_id">
            <div class="form-group">
                <label>Student Full Name</label>
                <input type="text" name="name" id="edit_name" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Grade/Class</label>
                <input type="text" name="grade" id="edit_grade" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Parent Phone Number</label>
                <input type="text" name="parent_phone" id="edit_phone" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Assign to Bus Route</label>
                <select name="bus_id" id="edit_bus_id" class="form-control" onchange="updateStopList('edit', this.value)">
                    <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 id="editStopSelection" class="form-group" style="display: none;">
                <label>Select Pickup Stop</label>
                <select name="stop_id" id="edit_stop_id" class="form-control" onchange="setStopCoords('edit', this.value)">
                    <option value="">-- Select a Stop --</option>
                </select>
            </div>
            <div class="form-group">
                <label>NFC Tag ID (Optional)</label>
                <input type="text" name="nfc_id" id="edit_nfc_id" class="form-control" placeholder="e.g. 04:A1:B2:C3">
            </div>
            <div style="display: flex; gap: 1rem;">
                <div class="form-group" style="flex: 1;">
                    <label>Pickup Latitude</label>
                    <input type="text" name="latitude" id="edit_lat" class="form-control">
                </div>
                <div class="form-group" style="flex: 1;">
                    <label>Pickup Longitude</label>
                    <input type="text" name="longitude" id="edit_lon" class="form-control">
                </div>
            </div>
            <div style="display: flex; gap: 1rem;">
                <button type="submit" class="btn btn-primary">Update Student</button>
                <button type="button" class="btn" onclick="document.getElementById('editModal').style.display='none'">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
const allStops = <?= json_encode($bus_stops) ?>;

function updateStopList(type, busId) {
    const stopSelect = document.getElementById(type + '_stop_id');
    const stopDiv = document.getElementById(type + 'StopSelection');
    
    // Clear existing options
    stopSelect.innerHTML = '<option value="">-- Select a Stop --</option>';
    
    if (!busId) {
        stopDiv.style.display = 'none';
        return;
    }
    
    const filteredStops = allStops.filter(s => s.bus_id == busId);
    
    if (filteredStops.length > 0) {
        filteredStops.forEach(stop => {
            const opt = document.createElement('option');
            opt.value = stop.id;
            opt.textContent = stop.stop_name;
            stopSelect.appendChild(opt);
        });
        stopDiv.style.display = 'block';
    } else {
        stopDiv.style.display = 'none';
    }
}

function setStopCoords(type, stopId) {
    if (!stopId) return;
    const stop = allStops.find(s => s.id == stopId);
    if (stop) {
        if (type === 'add') {
            document.getElementById('add_latitude').value = stop.latitude;
            document.getElementById('add_longitude').value = stop.longitude;
        } else {
            document.getElementById('edit_lat').value = stop.latitude;
            document.getElementById('edit_lon').value = stop.longitude;
        }
    }
}

function openAddModal() {
    document.getElementById('addModal').style.display = 'flex';
    document.getElementById('add_bus_id').value = '';
    document.getElementById('addStopSelection').style.display = 'none';
    document.getElementById('add_latitude').value = '';
    document.getElementById('add_longitude').value = '';
}

function openEditModal(student) {
    document.getElementById('edit_id').value = student.id;
    document.getElementById('edit_name').value = student.name;
    document.getElementById('edit_grade').value = student.grade;
    document.getElementById('edit_phone').value = student.parent_phone;
    document.getElementById('edit_bus_id').value = student.bus_id || '';
    document.getElementById('edit_lat').value = student.latitude || '';
    document.getElementById('edit_lon').value = student.longitude || '';
    document.getElementById('edit_nfc_id').value = student.nfc_id || '';
    
    if (student.bus_id) {
        updateStopList('edit', student.bus_id);
        // Try to pre-select the stop if coordinates match
        const matchingStop = allStops.find(s => s.bus_id == student.bus_id && s.latitude == student.latitude && s.longitude == student.longitude);
        if (matchingStop) {
            document.getElementById('edit_stop_id').value = matchingStop.id;
        }
    } else {
        document.getElementById('editStopSelection').style.display = 'none';
    }
    
    document.getElementById('editModal').style.display = 'flex';
}
</script>

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