<?php
/**
 * Bus/Transport 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_bus'])) {
            $stmt = $pdo->prepare("
                INSERT INTO buses (bus_number, bus_name, model, capacity, driver_name, driver_phone, 
                    conductor_name, conductor_phone, registration_number, insurance_expiry, 
                    fitness_certificate_expiry) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                sanitize($_POST['bus_number']),
                sanitize($_POST['bus_name']),
                sanitize($_POST['model']),
                intval($_POST['capacity']),
                sanitize($_POST['driver_name']),
                sanitize($_POST['driver_phone']),
                sanitize($_POST['conductor_name']),
                sanitize($_POST['conductor_phone']),
                sanitize($_POST['registration_number']),
                $_POST['insurance_expiry'],
                $_POST['fitness_certificate_expiry']
            ]);
            $success_message = '✅ বাস সফলভাবে যোগ করা হয়েছে!';
            
            // Audit log
            logAudit($pdo, $_SESSION['user_id'], $_SESSION['user_role'], 'INSERT', 'buses', $pdo->lastInsertId(), null, $_POST);
        }
        
        if (isset($_POST['update_bus'])) {
            $stmt = $pdo->prepare("
                UPDATE buses SET bus_number=?, bus_name=?, model=?, capacity=?, driver_name=?, 
                    driver_phone=?, conductor_name=?, conductor_phone=?, registration_number=?, 
                    insurance_expiry=?, fitness_certificate_expiry=?, status=?
                WHERE id=?
            ");
            $stmt->execute([
                sanitize($_POST['bus_number']),
                sanitize($_POST['bus_name']),
                sanitize($_POST['model']),
                intval($_POST['capacity']),
                sanitize($_POST['driver_name']),
                sanitize($_POST['driver_phone']),
                sanitize($_POST['conductor_name']),
                sanitize($_POST['conductor_phone']),
                sanitize($_POST['registration_number']),
                $_POST['insurance_expiry'],
                $_POST['fitness_certificate_expiry'],
                $_POST['status'],
                intval($_POST['bus_id'])
            ]);
            $success_message = '✅ বাস তথ্য আপডেট হয়েছে!';
        }
        
        if (isset($_POST['delete_bus'])) {
            // Check if bus has active subscriptions
            $check = $pdo->prepare("SELECT COUNT(*) FROM student_bus_subscriptions WHERE bus_id=? AND status='active'");
            $check->execute([intval($_POST['bus_id'])]);
            if ($check->fetchColumn() > 0) {
                $error_message = '❌ এই বাসে অ্যাক্টিভ ছাত্র আছে। প্রথমে তাদের সরিয়ে নিন।';
            } else {
                $stmt = $pdo->prepare("DELETE FROM buses WHERE id=?");
                $stmt->execute([intval($_POST['bus_id'])]);
                $success_message = '✅ বাস মুছে ফেলা হয়েছে!';
            }
        }
    } catch(Exception $e) {
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Get all buses
$buses = $pdo->query("SELECT * FROM buses ORDER BY bus_number")->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">
            <!-- Sidebar (include your sidebar here) -->
            
            <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>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addBusModal">
                        <i class="fas fa-plus"></i> নতুন বাস যোগ করুন
                    </button>
                </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; ?>
                
                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body">
                                <h5>মোট বাস</h5>
                                <h2><?= count($buses) ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body">
                                <h5>অ্যাক্টিভ বাস</h5>
                                <h2><?= count(array_filter($buses, fn($b) => $b['status'] == 'active')) ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-dark">
                            <div class="card-body">
                                <h5>মেইনটেনেন্সে</h5>
                                <h2><?= count(array_filter($buses, fn($b) => $b['status'] == 'maintenance')) ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body">
                                <h5>মোট আসন</h5>
                                <h2><?= array_sum(array_column($buses, 'capacity')) ?></h2>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Buses List -->
                <div class="card">
                    <div class="card-header">
                        <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 ($buses as $bus): ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($bus['bus_number']) ?></strong></td>
                                        <td><?= htmlspecialchars($bus['bus_name']) ?></td>
                                        <td><?= htmlspecialchars($bus['driver_name']) ?></td>
                                        <td><?= htmlspecialchars($bus['driver_phone']) ?></td>
                                        <td><?= $bus['capacity'] ?></td>
                                        <td>
                                            <span class="badge bg-<?= $bus['status'] == 'active' ? 'success' : ($bus['status'] == 'maintenance' ? 'warning' : 'secondary') ?>">
                                                <?= $bus['status'] == 'active' ? 'অ্যাক্টিভ' : ($bus['status'] == 'maintenance' ? 'মেইনটেনেন্স' : 'অবসরপ্রাপ্ত') ?>
                                            </span>
                                        </td>
                                        <td><?= $bus['insurance_expiry'] ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-info" onclick="viewBus(<?= $bus['id'] ?>)">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="btn btn-sm btn-warning" onclick="editBus(<?= $bus['id'] ?>)">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-sm btn-danger" onclick="deleteBus(<?= $bus['id'] ?>)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- Navigation Links -->
                <div class="mt-4">
                    <a href="bus_routes.php" class="btn btn-outline-primary">
                        <i class="fas fa-route"></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 Bus Modal -->
    <div class="modal fade" id="addBusModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <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="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">বাস নম্বর <span class="text-danger">*</span></label>
                                <input type="text" name="bus_number" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">বাসের নাম</label>
                                <input type="text" name="bus_name" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">মডেল</label>
                                <input type="text" name="model" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">আসন সংখ্যা <span class="text-danger">*</span></label>
                                <input type="number" name="capacity" class="form-control" required min="1" value="50">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">ড্রাইভারের নাম</label>
                                <input type="text" name="driver_name" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">ড্রাইভারের ফোন</label>
                                <input type="text" name="driver_phone" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">কন্ডাক্টরের নাম</label>
                                <input type="text" name="conductor_name" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">কন্ডাক্টরের ফোন</label>
                                <input type="text" name="conductor_phone" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">রেজিস্ট্রেশন নম্বর</label>
                                <input type="text" name="registration_number" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">ইন্সুরেন্স মেয়াদ</label>
                                <input type="date" name="insurance_expiry" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">ফিটনেস সার্টিফিকেট মেয়াদ</label>
                                <input type="date" name="fitness_certificate_expiry" class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                        <button type="submit" name="add_bus" class="btn btn-primary">সংরক্ষণ করুন</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function editBus(id) {
            window.location.href = 'bus_edit.php?id=' + id;
        }
        
        function viewBus(id) {
            window.location.href = 'bus_view.php?id=' + id;
        }
        
        function deleteBus(id) {
            if (confirm('আপনি কি নিশ্চিতভাবে এই বাস মুছে ফেলতে চান?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <?= csrf_field() ?>
                    <input type="hidden" name="bus_id" value="${id}">
                    <input type="hidden" name="delete_bus" value="1">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>
