<?php
/**
 * Bus Attendance 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 - support both new and legacy session variables
$user_role = $_SESSION['user_role'] ?? $_SESSION['role'] ?? '';
if (!isset($_SESSION['user_id']) || ($user_role !== 'admin' && $user_role !== 'teacher')) {
    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['mark_attendance'])) {
            $student_id = intval($_POST['student_id']);
            $date = $_POST['date'];
            $status = $_POST['status'];
            $bus_id = intval($_POST['bus_id']);
            $route_id = intval($_POST['route_id']);
            
            // Check if attendance already exists for this student and date
            $check = $pdo->prepare("SELECT id FROM bus_attendance WHERE student_id=? AND date=?");
            $check->execute([$student_id, $date]);
            $existing = $check->fetch();
            
            if ($existing) {
                // Update existing attendance
                $stmt = $pdo->prepare("
                    UPDATE bus_attendance SET status=?, bus_id=?, route_id=?, pickup_time=?, 
                        drop_time=?, marked_by=?, updated_at=NOW()
                    WHERE id=?
                ");
                $stmt->execute([
                    $status,
                    $bus_id,
                    $route_id,
                    $_POST['pickup_time'] ?? null,
                    $_POST['drop_time'] ?? null,
                    $_SESSION['user_id'],
                    $existing['id']
                ]);
            } else {
                // Insert new attendance
                $stmt = $pdo->prepare("
                    INSERT INTO bus_attendance (student_id, bus_id, route_id, date, status, 
                        pickup_time, drop_time, marked_by, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                ");
                $stmt->execute([
                    $student_id,
                    $bus_id,
                    $route_id,
                    $date,
                    $status,
                    $_POST['pickup_time'] ?? null,
                    $_POST['drop_time'] ?? null,
                    $_SESSION['user_id']
                ]);
            }
            $success_message = '✅ উপস্থিতি সফলভাবে চিহ্নিত হয়েছে!';
        }
        
        if (isset($_POST['bulk_attendance'])) {
            $date = $_POST['date'];
            $bus_id = intval($_POST['bus_id']);
            $route_id = intval($_POST['route_id']);
            
            // Get all active subscribers for this bus
            $stmt = $pdo->prepare("
                SELECT sbs.student_id 
                FROM student_bus_subscriptions sbs
                WHERE sbs.bus_id=? AND sbs.status='active' AND sbs.start_date <= ?
                AND (sbs.end_date IS NULL OR sbs.end_date >= ?)
            ");
            $stmt->execute([$bus_id, $date, $date]);
            $subscribers = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            $marked_count = 0;
            foreach ($subscribers as $student_id) {
                $status = $_POST['student_' . $student_id] ?? 'absent';
                
                // Check if attendance exists
                $check = $pdo->prepare("SELECT id FROM bus_attendance WHERE student_id=? AND date=?");
                $check->execute([$student_id, $date]);
                $existing = $check->fetch();
                
                if ($existing) {
                    $stmt = $pdo->prepare("UPDATE bus_attendance SET status=?, marked_by=?, updated_at=NOW() WHERE id=?");
                    $stmt->execute([$status, $_SESSION['user_id'], $existing['id']]);
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO bus_attendance (student_id, bus_id, route_id, date, status, marked_by, created_at, updated_at)
                        VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())
                    ");
                    $stmt->execute([$student_id, $bus_id, $route_id, $date, $status, $_SESSION['user_id']]);
                }
                $marked_count++;
            }
            $success_message = "✅ {$marked_count} জন ছাত্রের উপস্থিতি চিহ্নিত হয়েছে!";
        }
        
        if (isset($_POST['delete_attendance'])) {
            $stmt = $pdo->prepare("DELETE FROM bus_attendance WHERE id=?");
            $stmt->execute([intval($_POST['attendance_id'])]);
            $success_message = '✅ উপস্থিতি রেকর্ড মুছে ফেলা হয়েছে!';
        }
    } catch(Exception $e) {
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Get filter parameters
$selected_date = $_GET['date'] ?? date('Y-m-d');
$selected_bus = $_GET['bus_id'] ?? null;
$selected_route = $_GET['route_id'] ?? null;
$selected_class = $_GET['class_id'] ?? null;

// Get buses and routes for filters
$buses = $pdo->query("SELECT id, bus_number, bus_name FROM buses WHERE status='active' ORDER BY bus_number")->fetchAll();
$routes = $pdo->query("SELECT id, route_name, route_code FROM bus_routes WHERE status='active' ORDER BY route_code")->fetchAll();
$classes = $pdo->query("SELECT id, name FROM classes WHERE status='active' ORDER BY name")->fetchAll();

// Get attendance records with filters
$query = "
    SELECT ba.*, 
        CONCAT(s.first_name, ' ', s.last_name) as student_name,
        s.student_id as student_roll,
        c.name as class_name,
        b.bus_number,
        br.route_name,
        br.route_code,
        u.username as marked_by_name
    FROM bus_attendance ba
    LEFT JOIN students s ON ba.student_id = s.id
    LEFT JOIN classes c ON s.class_id = c.id
    LEFT JOIN buses b ON ba.bus_id = b.id
    LEFT JOIN bus_routes br ON ba.route_id = br.id
    LEFT JOIN users u ON ba.marked_by = u.id
    WHERE ba.date = ?
";
$params = [$selected_date];

if ($selected_bus) {
    $query .= " AND ba.bus_id = ?";
    $params[] = intval($selected_bus);
}
if ($selected_route) {
    $query .= " AND ba.route_id = ?";
    $params[] = intval($selected_route);
}
if ($selected_class) {
    $query .= " AND s.class_id = ?";
    $params[] = intval($selected_class);
}

$query .= " ORDER BY ba.created_at DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$attendance_records = $stmt->fetchAll();

// Get statistics for today
$total_present = count(array_filter($attendance_records, fn($a) => $a['status'] == 'present'));
$total_absent = count(array_filter($attendance_records, fn($a) => $a['status'] == 'absent'));
$total_late = count(array_filter($attendance_records, fn($a) => $a['status'] == 'late'));

// Get students for bulk attendance (active subscribers)
$bulk_students = [];
if ($selected_bus) {
    $stmt = $pdo->prepare("
        SELECT s.id, CONCAT(s.first_name, ' ', s.last_name) as name, s.student_id, c.name as class_name,
            bs1.stop_name as pickup_stop, bs2.stop_name as drop_stop
        FROM student_bus_subscriptions sbs
        LEFT JOIN students s ON sbs.student_id = s.id
        LEFT JOIN classes c ON s.class_id = c.id
        LEFT JOIN bus_route_stops bs1 ON sbs.pickup_stop_id = bs1.id
        LEFT JOIN bus_route_stops bs2 ON sbs.drop_stop_id = bs2.id
        WHERE sbs.bus_id=? AND sbs.status='active' AND sbs.start_date <= ?
        AND (sbs.end_date IS NULL OR sbs.end_date >= ?)
        ORDER BY c.name, s.first_name
    ");
    $stmt->execute([intval($selected_bus), $selected_date, $selected_date]);
    $bulk_students = $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 class="btn-toolbar mb-2 mb-md-0">
                        <a href="../../index.php" class="btn btn-outline-primary btn-sm me-2">
                            <i class="fas fa-home"></i> হোম পেজ
                        </a>
                        <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="#markAttendanceModal">
                            <i class="fas fa-check"></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; ?>
                
                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body">
                                <h5>আজ উপস্থিত</h5>
                                <h2><?= $total_present ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-danger text-white">
                            <div class="card-body">
                                <h5>আজ অনুপস্থিত</h5>
                                <h2><?= $total_absent ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-dark">
                            <div class="card-body">
                                <h5>দেরীতে এসেছে</h5>
                                <h2><?= $total_late ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body">
                                <h5>মোট রেকর্ড</h5>
                                <h2><?= count($attendance_records) ?></h2>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Filter Form -->
                <div class="card mb-4">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="fas fa-filter"></i> ফিল্টার</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">তারিখ</label>
                                <input type="date" name="date" class="form-control" value="<?= $selected_date ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">বাস</label>
                                <select name="bus_id" class="form-select">
                                    <option value="">সব বাস</option>
                                    <?php foreach ($buses as $bus): ?>
                                        <option value="<?= $bus['id'] ?>" <?= $selected_bus == $bus['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($bus['bus_number']) ?> - <?= htmlspecialchars($bus['bus_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">রুট</label>
                                <select name="route_id" class="form-select">
                                    <option value="">সব রুট</option>
                                    <?php foreach ($routes as $route): ?>
                                        <option value="<?= $route['id'] ?>" <?= $selected_route == $route['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($route['route_code']) ?> - <?= htmlspecialchars($route['route_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">শ্রেণী</label>
                                <select name="class_id" class="form-select">
                                    <option value="">সব শ্রেণী</option>
                                    <?php foreach ($classes as $class): ?>
                                        <option value="<?= $class['id'] ?>" <?= $selected_class == $class['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($class['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-12">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-search"></i> ফিল্টার করুন
                                </button>
                                <?php if ($selected_bus && count($bulk_students) > 0): ?>
                                    <button type="button" class="btn btn-success ms-2" data-bs-toggle="modal" data-bs-target="#bulkAttendanceModal">
                                        <i class="fas fa-users"></i> বাল্ক উপস্থিতি চিহ্নিত করুন
                                    </button>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Attendance Records -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">উপস্থিতি রেকর্ড (<?= $selected_date ?>)</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>
                                        <th>চিহ্নিত করেছেন</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($attendance_records as $record): ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($record['student_name']) ?></strong></td>
                                        <td><?= $record['student_roll'] ?></td>
                                        <td><?= htmlspecialchars($record['class_name']) ?></td>
                                        <td><?= htmlspecialchars($record['bus_number']) ?></td>
                                        <td><?= htmlspecialchars($record['route_code']) ?></td>
                                        <td>
                                            <?php
                                            $status_class = [
                                                'present' => 'success',
                                                'absent' => 'danger',
                                                'late' => 'warning',
                                                'excused' => 'info'
                                            ][$record['status']] ?? 'secondary';
                                            $status_text = [
                                                'present' => 'উপস্থিত',
                                                'absent' => 'অনুপস্থিত',
                                                'late' => 'দেরীতে',
                                                'excused' => 'অনুমোদিত অনুপস্থিতি'
                                            ][$record['status']] ?? $record['status'];
                                            ?>
                                            <span class="badge bg-<?= $status_class ?>"><?= $status_text ?></span>
                                        </td>
                                        <td><?= $record['pickup_time'] ?? '-' ?></td>
                                        <td><?= $record['drop_time'] ?? '-' ?></td>
                                        <td><?= htmlspecialchars($record['marked_by_name'] ?? 'অজানা') ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-danger" onclick="deleteAttendance(<?= $record['id'] ?>)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php if (empty($attendance_records)): ?>
                                    <tr>
                                        <td colspan="10" class="text-center text-muted py-4">
                                            কোন উপস্থিতি রেকর্ড পাওয়া যায়নি
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- 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_routes.php" class="btn btn-outline-success">
                        <i class="fas fa-route"></i> রুট ব্যবস্থাপনা
                    </a>
                    <a href="bus_subscriptions.php" class="btn btn-outline-info">
                        <i class="fas fa-users"></i> ছাত্র সাবস্ক্রিপশন
                    </a>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Mark Single Attendance Modal -->
    <div class="modal fade" id="markAttendanceModal" 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="number" name="student_id" class="form-control" required placeholder="ছাত্র আইডি">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">তারিখ <span class="text-danger">*</span></label>
                            <input type="date" name="date" class="form-control" required value="<?= date('Y-m-d') ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">বাস আইডি <span class="text-danger">*</span></label>
                            <select name="bus_id" class="form-select" required>
                                <option value="">বাস নির্বাচন করুন</option>
                                <?php foreach ($buses as $bus): ?>
                                    <option value="<?= $bus['id'] ?>"><?= htmlspecialchars($bus['bus_number']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">রুট আইডি <span class="text-danger">*</span></label>
                            <select name="route_id" class="form-select" required>
                                <option value="">রুট নির্বাচন করুন</option>
                                <?php foreach ($routes as $route): ?>
                                    <option value="<?= $route['id'] ?>"><?= htmlspecialchars($route['route_code']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">স্ট্যাটাস <span class="text-danger">*</span></label>
                            <select name="status" class="form-select" required>
                                <option value="present">উপস্থিত</option>
                                <option value="absent">অনুপস্থিত</option>
                                <option value="late">দেরীতে</option>
                                <option value="excused">অনুমোদিত অনুপস্থিতি</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">পিকআপ সময়</label>
                            <input type="time" name="pickup_time" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ড্রপ সময়</label>
                            <input type="time" name="drop_time" class="form-control">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                        <button type="submit" name="mark_attendance" class="btn btn-primary">সংরক্ষণ করুন</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Bulk Attendance Modal -->
    <?php if ($selected_bus && count($bulk_students) > 0): ?>
    <div class="modal fade" id="bulkAttendanceModal" 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() ?>
                    <input type="hidden" name="date" value="<?= $selected_date ?>">
                    <input type="hidden" name="bus_id" value="<?= $selected_bus ?>">
                    <input type="hidden" name="route_id" value="<?= $selected_route ?? $routes[0]['id'] ?? 1 ?>">
                    <div class="modal-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 ($bulk_students as $student): ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($student['name']) ?></strong></td>
                                        <td><?= $student['student_id'] ?></td>
                                        <td><?= htmlspecialchars($student['class_name']) ?></td>
                                        <td><?= htmlspecialchars($student['pickup_stop'] ?? 'N/A') ?></td>
                                        <td><?= htmlspecialchars($student['drop_stop'] ?? 'N/A') ?></td>
                                        <td>
                                            <select name="student_<?= $student['id'] ?>" class="form-select form-select-sm">
                                                <option value="present">উপস্থিত</option>
                                                <option value="absent">অনুপস্থিত</option>
                                                <option value="late">দেরীতে</option>
                                                <option value="excused">অনুমোদিত অনুপস্থিতি</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                        <button type="submit" name="bulk_attendance" class="btn btn-success">
                            <i class="fas fa-save"></i> সব উপস্থিতি সংরক্ষণ করুন
                        </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 deleteAttendance(id) {
            if (confirm('আপনি কি নিশ্চিতভাবে এই উপস্থিতি রেকর্ড মুছে ফেলতে চান?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <?= csrf_field() ?>
                    <input type="hidden" name="attendance_id" value="${id}">
                    <input type="hidden" name="delete_attendance" value="1">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>
