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

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

// Handle Move Stop (Reorder)
if (isset($_GET['move_stop']) && isset($_GET['dir'])) {
    $stop_id = $_GET['move_stop'];
    $bus_id = $_GET['bus_id'];
    $dir = $_GET['dir'];
    
    // Get current order
    $stmt = $pdo->prepare("SELECT stop_order FROM bus_stops WHERE id = ?");
    $stmt->execute([$stop_id]);
    $current_order = $stmt->fetchColumn();
    
    if ($dir == 'up' && $current_order > 1) {
        $new_order = $current_order - 1;
        // Swap with the person above
        $pdo->prepare("UPDATE bus_stops SET stop_order = ? WHERE bus_id = ? AND stop_order = ?")->execute([$current_order, $bus_id, $new_order]);
        $pdo->prepare("UPDATE bus_stops SET stop_order = ? WHERE id = ?")->execute([$new_order, $stop_id]);
    } else if ($dir == 'down') {
        $new_order = $current_order + 1;
        // Swap with the person below
        $pdo->prepare("UPDATE bus_stops SET stop_order = ? WHERE bus_id = ? AND stop_order = ?")->execute([$current_order, $bus_id, $new_order]);
        $pdo->prepare("UPDATE bus_stops SET stop_order = ? WHERE id = ?")->execute([$new_order, $stop_id]);
    }
    
    header("Location: bus_routes.php?bus_id=$bus_id");
    exit;
}

// Handle Add Stop
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_stop'])) {
    $bus_id = $_POST['bus_id'];
    $stop_name = $_POST['stop_name'];
    $latitude = $_POST['latitude'];
    $longitude = $_POST['longitude'];
    
    // Get next order
    $stmt = $pdo->prepare("SELECT MAX(stop_order) as max_order FROM bus_stops WHERE bus_id = ?");
    $stmt->execute([$bus_id]);
    $row = $stmt->fetch();
    $next_order = ($row['max_order'] ?? 0) + 1;

    $stmt = $pdo->prepare("INSERT INTO bus_stops (bus_id, stop_name, latitude, longitude, stop_order) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$bus_id, $stop_name, $latitude, $longitude, $next_order]);
    
    header("Location: bus_routes.php?bus_id=$bus_id");
    exit;
}

// Handle Edit Stop
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_stop'])) {
    $stop_id = $_POST['stop_id'];
    $bus_id = $_POST['bus_id'];
    $stop_name = $_POST['stop_name'];
    $latitude = $_POST['latitude'];
    $longitude = $_POST['longitude'];

    $stmt = $pdo->prepare("UPDATE bus_stops SET stop_name = ?, latitude = ?, longitude = ? WHERE id = ?");
    $stmt->execute([$stop_name, $latitude, $longitude, $stop_id]);
    
    header("Location: bus_routes.php?bus_id=$bus_id");
    exit;
}

$buses = $pdo->query("SELECT * FROM buses WHERE status = 'active'")->fetchAll();
$selected_bus_id = $_GET['bus_id'] ?? null;
$stops = [];

if ($selected_bus_id) {
    $stmt = $pdo->prepare("SELECT bs.*, 
                           (SELECT COUNT(*) FROM students WHERE stop_id = bs.id) as student_count,
                           (SELECT GROUP_CONCAT(CONCAT(name, ':', IFNULL(grade, 'N/A')) ORDER BY name ASC SEPARATOR '|') FROM students WHERE stop_id = bs.id) as student_details
                           FROM bus_stops bs 
                           WHERE bs.bus_id = ? 
                           ORDER BY bs.stop_order ASC");
    $stmt->execute([$selected_bus_id]);
    $stops = $stmt->fetchAll();
}
?>

<div style="display: flex; gap: 2rem; align-items: flex-start;">
    <!-- LEFT: Bus Selection & Stop List -->
    <div style="flex: 1; min-width: 350px;">
        <div class="card">
            <h3>Select Bus Route</h3><br>
            <select class="form-control" onchange="window.location.href='?bus_id=' + this.value">
                <option value="">-- Select a Bus --</option>
                <?php foreach ($buses as $bus): ?>
                    <option value="<?= $bus['id'] ?>" <?= $selected_bus_id == $bus['id'] ? 'selected' : '' ?>>
                        <?= $bus['bus_number'] ?> (<?= $bus['route_name'] ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <?php if ($selected_bus_id): ?>
        <div class="card" style="margin-top: 1.5rem;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                <h4>Route Stops</h4>
                <button class="btn btn-primary" style="width: auto; padding: 0.3rem 1rem; font-size: 0.85rem;" onclick="document.getElementById('addStopModal').style.display='flex'">
                    <i class="fas fa-plus"></i> Add Stop
                </button>
            </div>
            
            <?php if (empty($stops)): ?>
                <p style="color: var(--dark-gray); text-align: center; padding: 1rem;">No stops defined for this route.</p>
            <?php else: ?>
                <div class="stop-list">
                    <?php foreach ($stops as $index => $stop): ?>
                        <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.8rem; border-bottom: 1px solid #eee;">
                            <div style="display: flex; align-items: center; gap: 0.5rem;">
                                <div style="display: flex; flex-direction: column; gap: 2px;">
                                    <a href="?move_stop=<?= $stop['id'] ?>&dir=up&bus_id=<?= $selected_bus_id ?>" style="color: #ccc; font-size: 0.7rem;" title="Move Up"><i class="fas fa-chevron-up"></i></a>
                                    <a href="?move_stop=<?= $stop['id'] ?>&dir=down&bus_id=<?= $selected_bus_id ?>" style="color: #ccc; font-size: 0.7rem;" title="Move Down"><i class="fas fa-chevron-down"></i></a>
                                </div>
                                <span style="background: var(--primary); color: white; width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center; border-radius: 50%; font-size: 0.75rem; margin-right: 0.5rem;">
                                    <?= $index + 1 ?>
                                </span>
                                <strong><?= htmlspecialchars($stop['stop_name']) ?></strong>
                            </div>
                            <div style="display: flex; align-items: center; gap: 1rem;">
                                <span title="View Students" 
                                      style="font-size: 0.85rem; color: var(--primary); background: #eef2ff; padding: 0.2rem 0.6rem; border-radius: 4px; cursor: pointer; border: 1px solid #dee2e6;"
                                      onclick="showStudents('<?= htmlspecialchars($stop['stop_name']) ?>', '<?= htmlspecialchars($stop['student_details'] ?? '') ?>')">
                                    <i class="fas fa-user-graduate" style="margin-right: 0.3rem;"></i><?= $stop['student_count'] ?>
                                </span>
                                <a href="javascript:void(0)" style="color: var(--primary)" onclick='openEditModal(<?= json_encode($stop) ?>)'>
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="?delete_stop=<?= $stop['id'] ?>&bus_id=<?= $selected_bus_id ?>" style="color: var(--danger)" onclick="return confirm('Delete this stop?')">
                                    <i class="fas fa-trash-alt"></i>
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- RIGHT: Map Interface -->
    <div style="flex: 2;">
        <div class="card" style="padding: 0; overflow: hidden; height: 600px;">
            <?php if (!$selected_bus_id): ?>
                <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: var(--dark-gray); padding: 2rem; text-align: center;">
                    <i class="fas fa-map-marked-alt" style="font-size: 3rem; margin-bottom: 1rem; color: #ddd;"></i>
                    <p>Select a bus route on the left to view and manage its stops on the map.</p>
                </div>
            <?php else: ?>
                <div id="routeMap" style="height: 100%; width: 100%;"></div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Students List Modal -->
<div id="studentsModal" 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: 80vh; overflow-y: auto; margin-bottom: 0;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
            <h3 id="modalStopName" style="margin: 0;">Students at Stop</h3>
            <span onclick="document.getElementById('studentsModal').style.display='none'" style="cursor: pointer; font-size: 1.5rem; color: var(--dark-gray);">&times;</span>
        </div>
        <hr style="border: 0; border-top: 1px solid #eee; margin: 1rem 0;">
        <div id="studentListContainer">
            <!-- List will be populated by JS -->
        </div>
        <br>
        <button class="btn btn-primary" onclick="document.getElementById('studentsModal').style.display='none'">Close Window</button>
    </div>
</div>

<!-- Add Stop Modal -->
<div id="addStopModal" 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 Bus Stop</h3><br>
        <form method="POST">
            <input type="hidden" name="add_stop" value="1">
            <input type="hidden" name="bus_id" value="<?= $selected_bus_id ?>">
            <div class="form-group">
                <label>Stop Name</label>
                <input type="text" name="stop_name" class="form-control" required placeholder="e.g. Main Chowk">
            </div>
            
            <div id="pickStopMap" style="height: 250px; margin-bottom: 1rem; border-radius: 8px; border: 1px solid #ddd;"></div>
            
            <div style="display: flex; gap: 1rem;">
                <div class="form-group" style="flex: 1;">
                    <label>Latitude</label>
                    <input type="text" name="latitude" id="stop_lat" class="form-control" required readonly>
                </div>
                <div class="form-group" style="flex: 1;">
                    <label>Longitude</label>
                    <input type="text" name="longitude" id="stop_lon" class="form-control" required readonly>
                </div>
            </div>
            
            <div style="display: flex; gap: 1rem;">
                <button type="submit" class="btn btn-primary">Save Stop</button>
                <button type="button" class="btn" onclick="document.getElementById('addStopModal').style.display='none'">Cancel</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Stop Modal -->
<div id="editStopModal" 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 Bus Stop</h3><br>
        <form method="POST">
            <input type="hidden" name="edit_stop" value="1">
            <input type="hidden" name="bus_id" value="<?= $selected_bus_id ?>">
            <input type="hidden" name="stop_id" id="edit_stop_id">
            <div class="form-group">
                <label>Stop Name</label>
                <input type="text" name="stop_name" id="edit_stop_name" class="form-control" required>
            </div>
            
            <div id="editPickStopMap" style="height: 250px; margin-bottom: 1rem; border-radius: 8px; border: 1px solid #ddd;"></div>
            
            <div style="display: flex; gap: 1rem;">
                <div class="form-group" style="flex: 1;">
                    <label>Latitude</label>
                    <input type="text" name="latitude" id="edit_stop_lat" class="form-control" required readonly>
                </div>
                <div class="form-group" style="flex: 1;">
                    <label>Longitude</label>
                    <input type="text" name="longitude" id="edit_stop_lon" class="form-control" required readonly>
                </div>
            </div>
            
            <div style="display: flex; gap: 1rem;">
                <button type="submit" class="btn btn-primary">Update Stop</button>
                <button type="button" class="btn" onclick="document.getElementById('editStopModal').style.display='none'">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
<?php if ($selected_bus_id): ?>
// Main Route Map
const routeMap = L.map('routeMap').setView([27.7172, 85.3240], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap contributors'
}).addTo(routeMap);

const stops = <?= json_encode($stops) ?>;
const polylinePoints = [];

if (stops.length > 0) {
    stops.forEach((stop, index) => {
        const point = [parseFloat(stop.latitude), parseFloat(stop.longitude)];
        polylinePoints.push(point);
        L.marker(point).addTo(routeMap)
            .bindPopup(`<b>Stop #${index + 1}:</b> ${stop.stop_name}`);
    });
    
    // Connect stops with a line
    if (polylinePoints.length > 1) {
        L.polyline(polylinePoints, {color: 'var(--primary)', weight: 4, opacity: 0.6}).addTo(routeMap);
    }
    
    // Zoom to fit stops
    const group = new L.featureGroup(stops.map(s => L.marker([s.latitude, s.longitude])));
    routeMap.fitBounds(group.getBounds().pad(0.1));
}

// Picker Map in Modal
let pickMap, pickMarker;
let editPickMap, editPickMarker;

function initPickMap() {
    if (!pickMap) {
        pickMap = L.map('pickStopMap').setView([27.7172, 85.3240], 14);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(pickMap);
        pickMarker = L.marker([27.7172, 85.3240], {draggable: true}).addTo(pickMap);
        
        const updateFields = (lat, lng) => {
            document.getElementById('stop_lat').value = lat.toFixed(6);
            document.getElementById('stop_lon').value = lng.toFixed(6);
        };
        
        updateFields(27.7172, 85.3240);
        
        pickMarker.on('dragend', function(e) {
            const pos = e.target.getLatLng();
            updateFields(pos.lat, pos.lng);
        });
        
        pickMap.on('click', function(e) {
            pickMarker.setLatLng(e.latlng);
            updateFields(e.latlng.lat, e.latlng.lng);
        });
    } else {
        // Reset to default
        pickMap.setView([27.7172, 85.3240], 14);
        pickMarker.setLatLng([27.7172, 85.3240]);
        document.getElementById('stop_lat').value = "27.717200";
        document.getElementById('stop_lon').value = "85.324000";
    }
    setTimeout(() => pickMap.invalidateSize(), 200);
}

function openEditModal(stop) {
    document.getElementById('edit_stop_id').value = stop.id;
    document.getElementById('edit_stop_name').value = stop.stop_name;
    document.getElementById('edit_stop_lat').value = stop.latitude;
    document.getElementById('edit_stop_lon').value = stop.longitude;
    
    document.getElementById('editStopModal').style.display = 'flex';
    
    setTimeout(() => {
        if (!editPickMap) {
            editPickMap = L.map('editPickStopMap').setView([stop.latitude, stop.longitude], 14);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(editPickMap);
            editPickMarker = L.marker([stop.latitude, stop.longitude], {draggable: true}).addTo(editPickMap);
            
            const updateFields = (lat, lng) => {
                document.getElementById('edit_stop_lat').value = lat.toFixed(6);
                document.getElementById('edit_stop_lon').value = lng.toFixed(6);
            };
            
            editPickMarker.on('dragend', function(e) {
                const pos = e.target.getLatLng();
                updateFields(pos.lat, pos.lng);
            });
            
            editPickMap.on('click', function(e) {
                editPickMarker.setLatLng(e.latlng);
                updateFields(e.latlng.lat, e.latlng.lng);
            });
        } else {
            editPickMap.setView([stop.latitude, stop.longitude], 14);
            editPickMarker.setLatLng([stop.latitude, stop.longitude]);
        }
        editPickMap.invalidateSize();
    }, 200);
}

// Initialize Add Stop button properly
const addStopBtn = document.querySelector('[onclick*="addStopModal"]');
if (addStopBtn) {
    addStopBtn.removeAttribute('onclick');
    addStopBtn.addEventListener('click', function() {
        document.getElementById('addStopModal').style.display = 'flex';
        initPickMap();
    });
}

function showStudents(stopName, detailsString) {
    document.getElementById('modalStopName').textContent = "Students at " + stopName;
    const container = document.getElementById('studentListContainer');
    container.innerHTML = '';
    
    if (!detailsString) {
        container.innerHTML = '<p style="color: var(--dark-gray); text-align: center;">No students enrolled at this stop.</p>';
    } else {
        const entries = detailsString.split('|');
        let html = '<table style="width: 100%; border-collapse: collapse;">';
        html += '<thead style="background: #f8f9fa;"><tr><th style="padding: 10px; border-bottom: 2px solid #dee2e6; text-align: left;">Name</th><th style="padding: 10px; border-bottom: 2px solid #dee2e6; text-align: left;">Grade</th></tr></thead>';
        html += '<tbody>';
        
        entries.forEach(entry => {
            const parts = entry.split(':');
            const name = parts[0];
            const grade = parts[1] || 'N/A';
            html += `<tr style="border-bottom: 1px solid #eee;">
                        <td style="padding: 10px;"><i class="fas fa-user" style="color: var(--primary); margin-right: 10px;"></i>${name}</td>
                        <td style="padding: 10px;">${grade}</td>
                    </tr>`;
        });
        
        html += '</tbody></table>';
        container.innerHTML = html;
    }
    
    document.getElementById('studentsModal').style.display = 'flex';
}
<?php endif; ?>
</script>

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