<?php
session_start();
require_once '../config/database.php';

// Auth: only admin or teacher
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin', 'teacher'])) {
    header('Location: ../login.php');
    exit();
}

$classes = [];
try {
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status='active' ORDER BY name, section");
    $classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // ignore UI will show empty
}

// Get sessions for dropdown
$sessions = [];
try {
    $stmt = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL AND session != '' ORDER BY session DESC");
    $sessions = $stmt->fetchAll(PDO::FETCH_COLUMN);
    if (empty($sessions)) {
        $currentYear = date('Y');
        for ($i = 0; $i < 5; $i++) {
            $sessions[] = $currentYear - $i;
        }
    }
} catch (Exception $e) {
    // ignore
}

// Inputs
$selected_class = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
$selected_session = isset($_GET['session']) ? $_GET['session'] : date('Y');
$date = $_GET['date'] ?? date('Y-m-d');
// Normalize date
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) { $date = date('Y-m-d'); }

// Previous/next day
$prev_date = date('Y-m-d', strtotime($date . ' -1 day'));
$next_date = date('Y-m-d', strtotime($date . ' +1 day'));

$students = [];
$summary = [
    'present' => 0,
    'absent' => 0,
    'late' => 0,
    'excused' => 0,
    'marked' => 0,
    'total' => 0,
];

if ($selected_class > 0 && $selected_session) {
    try {
        // Load students with their attendance for the selected date and session
        $sql = "SELECT 
                    s.id as student_pk, s.student_id, s.first_name, s.last_name, s.roll_number,
                    a.status, a.remarks
                FROM students s
                LEFT JOIN attendance a 
                    ON a.student_id = s.id AND a.date = ?
                WHERE s.class_id = ? AND s.session = ? AND s.status = 'active'
                ORDER BY s.roll_number, s.first_name";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$date, $selected_class, $selected_session]);
        $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Calculate summary
        foreach ($students as $row) {
            $summary['total']++;
            if ($row['status'] === null || $row['status'] === '') { continue; }
            $summary['marked']++;
            if (isset($summary[$row['status']])) { $summary[$row['status']]++; }
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// CSV export
if (isset($_GET['export']) && $_GET['export'] === 'csv' && $selected_class > 0 && $selected_session) {
    header('Content-Type: text/csv; charset=utf-8');
    $clsName = 'class_' . $selected_class;
    foreach ($classes as $c) { if ((int)$c['id'] === $selected_class) { $clsName = $c['name'] . '_' . $c['section']; break; } }
    header('Content-Disposition: attachment; filename=attendance_view_' . $clsName . '_' . $selected_session . '_' . $date . '.csv');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Date', 'Class', 'Section', 'Session', 'Roll', 'Student ID', 'Name', 'Status', 'Remarks']);
    $className = '';
    $section = '';
    foreach ($classes as $c) { if ((int)$c['id'] === $selected_class) { $className = $c['name']; $section = $c['section']; break; } }
    foreach ($students as $row) {
        $name = trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''));
        fputcsv($out, [$date, $className, $section, $selected_session, $row['roll_number'], $row['student_id'], $name, $row['status'] ?: '-', $row['remarks'] ?: '']);
    }
    fclose($out);
    exit;
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>উপস্থিতি দেখুন</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container-fluid">
        <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম</a>
        <div class="navbar-nav ms-auto">
            <a class="nav-link" href="../index.php"><i class="fas fa-home"></i> হোম</a>
            <a class="nav-link" href="mark.php"><i class="fas fa-edit"></i> উপস্থিতি নিন</a>
            <a class="nav-link" href="report.php"><i class="fas fa-chart-bar"></i> রিপোর্ট</a>
            <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
        </div>
    </div>
</nav>
<div class="container-fluid mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h2><i class="fas fa-eye"></i> উপস্থিতি দেখুন</h2>
        <div>
            <a class="btn btn-success me-2 <?= ($selected_class > 0 && $selected_session) ? '' : 'disabled'; ?>" href="?<?= http_build_query(array_merge($_GET, ['export' => 'csv'])) ?>">
                <i class="fas fa-file-csv"></i> CSV
            </a>
            <button class="btn btn-primary" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট</button>
        </div>
    </div>
    <!-- Filters -->
    <form method="GET" class="card mb-4 p-3">
        <div class="row g-3 align-items-end">
            <div class="col-md-3">
                <label class="form-label">ক্লাস</label>
                <select class="form-select" name="class_id" required>
                    <option value="">ক্লাস নির্বাচন করুন</option>
                    <?php foreach ($classes as $c): ?>
                        <option value="<?= (int)$c['id'] ?>" <?= $selected_class == (int)$c['id'] ? 'selected' : ''; ?>>
                            <?= htmlspecialchars($c['name'] . ' - ' . $c['section']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label for="session" class="form-label">সেশন</label>
                <select class="form-select" id="session" name="session" required>
                    <option value="">সেশন নির্বাচন করুন</option>
                    <?php foreach ($sessions as $session): ?>
                        <option value="<?php echo $session; ?>" 
                                <?php echo ($selected_session == $session) ? 'selected' : ''; ?>>
                            <?php echo $session; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">তারিখ</label>
                <div class="input-group">
                    <a class="btn btn-outline-secondary" title="পূর্ববর্তী দিন" href="?<?= http_build_query(array_merge($_GET, ['date' => $prev_date])) ?>">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                    <input type="date" class="form-control" name="date" value="<?= htmlspecialchars($date) ?>" required>
                    <a class="btn btn-outline-secondary" title="পরবর্তী দিন" href="?<?= http_build_query(array_merge($_GET, ['date' => $next_date])) ?>">
                        <i class="fas fa-chevron-right"></i>
                    </a>
                </div>
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> দেখুন</button>
            </div>
        </div>
    </form>

    <?php if ($selected_class > 0 && $selected_session): ?>
        <!-- Summary -->
        <div class="row mb-3">
            <div class="col-md-2">
                <div class="card bg-success text-white"><div class="card-body text-center"><div class="fw-bold">উপস্থিত</div><div class="fs-4"><?= (int)$summary['present'] ?></div></div></div>
            </div>
            <div class="col-md-2">
                <div class="card bg-danger text-white"><div class="card-body text-center"><div class="fw-bold">অনুপস্থিত</div><div class="fs-4"><?= (int)$summary['absent'] ?></div></div></div>
            </div>
            <div class="col-md-2">
                <div class="card bg-warning text-white"><div class="card-body text-center"><div class="fw-bold">লেট</div><div class="fs-4"><?= (int)$summary['late'] ?></div></div></div>
            </div>
            <div class="col-md-2">
                <div class="card bg-info text-white"><div class="card-body text-center"><div class="fw-bold">Excused</div><div class="fs-4"><?= (int)$summary['excused'] ?></div></div></div>
            </div>
            <div class="col-md-2">
                <div class="card bg-secondary text-white"><div class="card-body text-center"><div class="fw-bold">মোট ছাত্র</div><div class="fs-4"><?= (int)$summary['total'] ?></div></div></div>
            </div>
            <div class="col-md-2">
                <?php $rate = $summary['marked']>0 ? round(($summary['present']*100.0)/max(1,$summary['marked']),2) : 0; ?>
                <div class="card bg-primary text-white"><div class="card-body text-center"><div class="fw-bold">Present %</div><div class="fs-4"><?= $rate ?></div></div></div>
            </div>
        </div>

        <!-- Table -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-list"></i> তালিকা (<?= htmlspecialchars($date) ?>)</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>রোল</th>
                                <th>নাম</th>
                                <th>স্টুডেন্ট আইডি</th>
                                <th>স্ট্যাটাস</th>
                                <th>মন্তব্য</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (!empty($students)): ?>
                            <?php foreach ($students as $row): ?>
                                <?php 
                                    $status = $row['status'] ?: '';
                                    $badgeClass = 'bg-secondary';
                                    $statusText = '—';
                                    if ($status === 'present') { $badgeClass = 'bg-success'; $statusText = 'Present'; }
                                    elseif ($status === 'absent') { $badgeClass = 'bg-danger'; $statusText = 'Absent'; }
                                    elseif ($status === 'late') { $badgeClass = 'bg-warning text-dark'; $statusText = 'Late'; }
                                    elseif ($status === 'excused') { $badgeClass = 'bg-info text-dark'; $statusText = 'Excused'; }
                                ?>
                                <tr>
                                    <td><span class="badge bg-info"><?= htmlspecialchars((string)$row['roll_number']) ?></span></td>
                                    <td><strong><?= htmlspecialchars(trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''))) ?></strong></td>
                                    <td><?= htmlspecialchars((string)$row['student_id']) ?></td>
                                    <td><span class="badge <?= $badgeClass ?>"><?= $statusText ?></span></td>
                                    <td><?= htmlspecialchars((string)($row['remarks'] ?? '')) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="5" class="text-center text-muted">তথ্য পাওয়া যায়নি</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php else: ?>
        <div class="alert alert-info"><i class="fas fa-info-circle"></i> ক্লাস, সেশন এবং তারিখ নির্বাচন করে অনুসন্ধান করুন।</div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>