<?php
/**
 * Bus Routes Management Module
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/SecurityHelper.php';

// Check authentication - redirect to login if not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

// Check admin role
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    die('❌ অ্যাক্সেস denied। আপনার এই পেজ দেখার অনুমতি নেই।<br><br>
    <a href="../login.php" class="btn btn-primary">লগইন পেজে যান</a>');
}

// Handle form submissions
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    SecurityHelper::validatePost();
    
    try {
        if (isset($_POST['add_route'])) {
            $stmt = $pdo->prepare("
                INSERT INTO bus_routes (route_name, route_code, start_point, end_point, 
                    estimated_time, status, fare_amount) 
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                sanitize($_POST['route_name']),
                sanitize($_POST['route_code']),
                sanitize($_POST['start_point']),
                sanitize($_POST['end_point']),
                sanitize($_POST['estimated_time']),
                $_POST['status'],
                floatval($_POST['fare_amount'])
            ]);
            $success_message = '✅ রুট সফলভাবে যোগ করা হয়েছে!';
            logAudit($pdo, $_SESSION['user_id'], $_SESSION['user_role'], 'INSERT', 'bus_routes', $pdo->lastInsertId(), null, $_POST);
        }
        
        if (isset($_POST['update_route'])) {
            $stmt = $pdo->prepare("
                UPDATE bus_routes SET route_name=?, route_code=?, start_point=?, 
                    end_point=?, estimated_time=?, status=?, fare_amount=?
                WHERE id=?
            ");
            $stmt->execute([
                sanitize($_POST['route_name']),
                sanitize($_POST['route_code']),
                sanitize($_POST['start_point']),
                sanitize($_POST['end_point']),
                sanitize($_POST['estimated_time']),
                $_POST['status'],
                floatval($_POST['fare_amount']),
                intval($_POST['route_id'])
            ]);
            $success_message = '✅ রুট তথ্য আপডেট হয়েছে!';
        }
        
        if (isset($_POST['delete_route'])) {
            // Check if route has active subscriptions
            $check = $pdo->prepare("SELECT COUNT(*) FROM student_bus_subscriptions WHERE route_id=? AND status='active'");
            $check->execute([intval($_POST['route_id'])]);
            if ($check->fetchColumn() > 0) {
                $error_message = '❌ এই রুটে অ্যাক্টিভ ছাত্র আছে। প্রথমে তাদের সরিয়ে নিন।';
            } else {
                // Delete related stops first
                $stmt = $pdo->prepare("DELETE FROM bus_route_stops WHERE route_id=?");
                $stmt->execute([intval($_POST['route_id'])]);
                // Delete the route
                $stmt = $pdo->prepare("DELETE FROM bus_routes WHERE id=?");
                $stmt->execute([intval($_POST['route_id'])]);
                $success_message = '✅ রুট মুছে ফেলা হয়েছে!';
            }
        }
        
        if (isset($_POST['add_stop'])) {
            $stmt = $pdo->prepare("
                INSERT INTO bus_route_stops (route_id, stop_name, stop_order, 
                    arrival_time, departure_time, landmark) 
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                intval($_POST['route_id']),
                sanitize($_POST['stop_name']),
                intval($_POST['stop_order']),
                $_POST['arrival_time'],
                $_POST['departure_time'],
                sanitize($_POST['landmark'])
            ]);
            $success_message = '✅ স্টপ সফলভাবে যোগ করা হয়েছে!';
        }
        
        if (isset($_POST['update_stop'])) {
            $stmt = $pdo->prepare("
                UPDATE bus_route_stops SET stop_name=?, stop_order=?, 
                    arrival_time=?, departure_time=?, landmark=?
                WHERE id=?
            ");
            $stmt->execute([
                sanitize($_POST['stop_name']),
                intval($_POST['stop_order']),
                $_POST['arrival_time'],
                $_POST['departure_time'],
                sanitize($_POST['landmark']),
                intval($_POST['stop_id'])
            ]);
            $success_message = '✅ স্টপ তথ্য আপডেট হয়েছে!';
        }
        
        if (isset($_POST['delete_stop'])) {
            $stmt = $pdo->prepare("DELETE FROM bus_route_stops WHERE id=?");
            $stmt->execute([intval($_POST['stop_id'])]);
            $success_message = '✅ স্টপ মুছে ফেলা হয়েছে!';
        }
    } catch(Exception $e) {
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Get all routes
$routes = $pdo->query("SELECT * FROM bus_routes ORDER BY route_code")->fetchAll();

// Get all buses for assignment
$buses = $pdo->query("SELECT id, bus_number, bus_name FROM buses WHERE status='active' ORDER BY bus_number")->fetchAll();

// Get stops for selected route
$selected_route_id = $_GET['route_id'] ?? null;
$route_stops = [];
if ($selected_route_id) {
    $stmt = $pdo->prepare("SELECT * FROM bus_route_stops WHERE route_id=? ORDER BY stop_order");
    $stmt->execute([intval($selected_route_id)]);
    $route_stops = $stmt->fetchAll();
}

function logAudit($pdo, $userId, $role, $action, $table, $recordId, $oldValues, $newValues) {
    $stmt = $pdo->prepare("
        INSERT INTO audit_log (user_id, user_role, action, table_name, record_id, 
            old_values, new_values, ip_address, user_agent, session_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $userId, $role, $action, $table, $recordId,
        $oldValues ? json_encode($oldValues) : null,
        $newValues ? json_encode($newValues) : null,
        $_SERVER['REMOTE_ADDR'],
        $_SERVER['HTTP_USER_AGENT'],
        session_id()
    ]);
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>বাস রুট ব্যবস্থাপনা - <?= APP_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">🛤️ বাস রুট ব্যবস্থাপনা</h1>
                    <div>
                        <a href="buses.php" class="btn btn-outline-secondary me-2">
                            <i class="fas fa-arrow-left"></i> বাস তালিকায় ফিরে যান
                        </a>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRouteModal">
                            <i class="fas fa-plus"></i> নতুন রুট যোগ করুন
                        </button>
                    </div>
                </div>
                
                <?php if ($success_message): ?>
                    <div class="alert alert-success"><?= $success_message ?></div>
                <?php endif; ?>
                
                <?php if ($error_message): ?>
                    <div class="alert alert-danger"><?= $error_message ?></div>
                <?php endif; ?>
                
                <!-- Routes List -->
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">বাস রুটের তালিকা</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>রুট কোড</th>
                                        <th>রুটের নাম</th>
                                        <th>শুরু পয়েন্ট</th>
                                        <th>শেষ পয়েন্ট</th>
                                        <th>সময় (ঘণ্টা)</th>
                                        <th>ভাড়া (৳)</th>
                                        <th>স্ট্যাটাস</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($routes as $route): ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($route['route_code']) ?></strong></td>
                                        <td><?= htmlspecialchars($route['route_name']) ?></td>
                                        <td><?= htmlspecialchars($route['start_point']) ?></td>
                                        <td><?= htmlspecialchars($route['end_point']) ?></td>
                                        <td><?= $route['estimated_time'] ?></td>
                                        <td>৳<?= number_format($route['fare_amount'], 2) ?></td>
                                        <td>
                                            <span class="badge bg-<?= $route['status'] == 'active' ? 'success' : 'secondary' ?>">
                                                <?= $route['status'] == 'active' ? 'অ্যাক্টিভ' : 'নিষ্ক্রিয়' ?>
                                            </span>
                                        </td>
                                        <td>
                                            <a href="?route_id=<?= $route['id'] ?>" class="btn btn-sm btn-info" title="স্টপ দেখুন">
                                                <i class="fas fa-map-marker-alt"></i>
                                            </a>
                                            <button class="btn btn-sm btn-warning" onclick="editRoute(<?= $route['id'] ?>)">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-sm btn-danger" onclick="deleteRoute(<?= $route['id'] ?>)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <?php if ($selected_route_id): ?>
                <!-- Route Stops -->
                <div class="card">
                    <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">🚏 রুট স্টপসমূহ</h5>
                        <button class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#addStopModal">
                            <i class="fas fa-plus"></i> নতুন স্টপ যোগ করুন
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead class="table-light">
                                    <tr>
                                        <th>ক্রম</th>
                                        <th>স্টপের নাম</th>
                                        <th>পৌঁছানোর সময়</th>
                                        <th>ছাড়ার সময়</th>
                                        <th>ল্যান্ডমার্ক</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($route_stops as $stop): ?>
                                    <tr>
                                        <td><?= $stop['stop_order'] ?></td>
                                        <td><strong><?= htmlspecialchars($stop['stop_name']) ?></strong></td>
                                        <td><?= $stop['arrival_time'] ?></td>
                                        <td><?= $stop['departure_time'] ?></td>
                                        <td><?= htmlspecialchars($stop['landmark'] ?? '') ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-warning" onclick="editStop(<?= $stop['id'] ?>)" title="স্টপ সম্পাদনা">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-sm btn-danger" onclick="deleteStop(<?= $stop['id'] ?>)" title="স্টপ মুছুন">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Navigation Links -->
                <div class="mt-4">
                    <a href="buses.php" class="btn btn-outline-primary">
                        <i class="fas fa-bus"></i> বাস ব্যবস্থাপনা
                    </a>
                    <a href="bus_subscriptions.php" class="btn btn-outline-success">
                        <i class="fas fa-users"></i> ছাত্র সাবস্ক্রিপশন
                    </a>
                    <a href="bus_attendance.php" class="btn btn-outline-info">
                        <i class="fas fa-clipboard-check"></i> বাস উপস্থিতি
                    </a>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Add Route Modal -->
    <div class="modal fade" id="addRouteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">নতুন রুট যোগ করুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <?= csrf_field() ?>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">রুটের নাম <span class="text-danger">*</span></label>
                            <input type="text" name="route_name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">রুট কোড <span class="text-danger">*</span></label>
                            <input type="text" name="route_code" class="form-control" required placeholder="যেমন: R001">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">শুরু পয়েন্ট <span class="text-danger">*</span></label>
                            <input type="text" name="start_point" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">শেষ পয়েন্ট <span class="text-danger">*</span></label>
                            <input type="text" name="end_point" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">প্রাক্কলিত সময় (ঘণ্টা)</label>
                            <input type="text" name="estimated_time" class="form-control" placeholder="যেমন: 1.5">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ভাড়া (টাকা) <span class="text-danger">*</span></label>
                            <input type="number" name="fare_amount" class="form-control" required min="0" step="0.01" value="500">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">স্ট্যাটাস</label>
                            <select name="status" class="form-select">
                                <option value="active">অ্যাক্টিভ</option>
                                <option value="inactive">নিষ্ক্রিয়</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                        <button type="submit" name="add_route" class="btn btn-primary">সংরক্ষণ করুন</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Add Stop Modal -->
    <?php if ($selected_route_id): ?>
    <div class="modal fade" id="addStopModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">নতুন স্টপ যোগ করুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <?= csrf_field() ?>
                    <input type="hidden" name="route_id" value="<?= $selected_route_id ?>">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">স্টপের নাম <span class="text-danger">*</span></label>
                            <input type="text" name="stop_name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ক্রম <span class="text-danger">*</span></label>
                            <input type="number" name="stop_order" class="form-control" required min="1" value="<?= count($route_stops) + 1 ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">পৌঁছানোর সময়</label>
                            <input type="time" name="arrival_time" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ছাড়ার সময়</label>
                            <input type="time" name="departure_time" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ল্যান্ডমার্ক / চিহ্ন</label>
                            <input type="text" name="landmark" class="form-control" placeholder="যেমন: কলেজ গেটের সামনে">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                        <button type="submit" name="add_stop" class="btn btn-primary">সংরক্ষণ করুন</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function editRoute(id) {
            // Implementation would fetch route data and populate a modal
            alert('রুট সম্পাদনা ফিচার বিকাশাধীন (ID: ' + id + ')');
        }
        
        function deleteRoute(id) {
            if (confirm('আপনি কি নিশ্চিতভাবে এই রুট মুছে ফেলতে চান?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <?= csrf_field() ?>
                    <input type="hidden" name="route_id" value="${id}">
                    <input type="hidden" name="delete_route" value="1">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function editStop(id) {
            alert('স্টপ সম্পাদনা ফিচার বিকাশাধীন (ID: ' + id + ')');
        }
        
        function deleteStop(id) {
            if (confirm('আপনি কি নিশ্চিতভাবে এই স্টপ মুছে ফেলতে চান?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <?= csrf_field() ?>
                    <input type="hidden" name="stop_id" value="${id}">
                    <input type="hidden" name="delete_stop" value="1">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>
