<?php
session_start();
if (!isset($_SESSION['student_id'])) {
    header('Location: student_login.php');
    exit;
}

// Handle language selection
if (isset($_GET['lang'])) {
    $lang = $_GET['lang'];
    if (in_array($lang, ['en', 'hi'])) {
        $_SESSION['lang'] = $lang;
    }
}
$lang = $_SESSION['lang'] ?? 'en';

// Load language strings
$lang_strings = include 'lang.php';

try {
    require_once 'connectiondb.php';

    // Fetch student name
    $stmt = $pdo->prepare("SELECT name FROM students WHERE id = ?");
    $stmt->execute([$_SESSION['student_id']]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
    $student_name = $student ? $student['name'] : 'Student';

    // Fetch exams assigned to the student with attempts and allowed_attempts
    $stmt = $pdo->prepare("
        SELECT e.id, e.exam_name, e.duration, se.status, se.attempts, e.allowed_attempts
        FROM exams e
        JOIN student_exams se ON e.id = se.exam_id
        WHERE se.student_id = ?
        ORDER BY e.exam_name
    ");
    $stmt->execute([$_SESSION['student_id']]);
    $exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch questions count for each exam
    $exam_ids = array_column($exams, 'id');
    $questions_count = [];
    if (!empty($exam_ids)) {
        $placeholders = implode(',', array_fill(0, count($exam_ids), '?'));
        $stmt = $pdo->prepare("SELECT exam_id, COUNT(*) as qcount FROM questions WHERE exam_id IN ($placeholders) GROUP BY exam_id");
        $stmt->execute($exam_ids);
        $counts = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($counts as $count) {
            $questions_count[$count['exam_id']] = $count['qcount'];
        }
    }

    // Fetch batch ids for the logged-in student
    $stmtBatch = $pdo->prepare("SELECT batch_id FROM batch_enrollments WHERE student_id = ?");
    $stmtBatch->execute([$_SESSION['student_id']]);
    $batch_ids = $stmtBatch->fetchAll(PDO::FETCH_COLUMN);

    $attendance_total_days = 0;
    $attendance_present_days = 0;
    $attendance_percentage = 0;

    // Fetch attendance summary for progress bar
    if (!empty($batch_ids)) {
        $placeholders = implode(',', array_fill(0, count($batch_ids), '?'));
        $params = $batch_ids;
        $params[] = $_SESSION['student_id'];

        $stmtAttendance = $pdo->prepare("
            SELECT status, COUNT(*) as count
            FROM attendance
            WHERE batch_id IN ($placeholders)
              AND student_id = ?
              AND status != 'holiday'
            GROUP BY status
        ");
        $stmtAttendance->execute($params);
        $attendance_counts = $stmtAttendance->fetchAll(PDO::FETCH_ASSOC);

        foreach ($attendance_counts as $row) {
            $attendance_total_days += $row['count'];
            if ($row['status'] === 'present') {
                $attendance_present_days = $row['count'];
            }
        }

        if ($attendance_total_days > 0) {
            $attendance_percentage = round(($attendance_present_days / $attendance_total_days) * 100);
        }
    }

    // Fetch detailed daily attendance for the student (last 30 days)
    $daily_attendance = [];
    if (!empty($batch_ids)) {
        $placeholders = implode(',', array_fill(0, count($batch_ids), '?'));
        $params = $batch_ids;
        $params[] = $_SESSION['student_id'];
        $params[] = date('Y-m-d', strtotime('-30 days'));

        $stmtDaily = $pdo->prepare("
            SELECT attendance_date, status
            FROM attendance
            WHERE batch_id IN ($placeholders)
              AND student_id = ?
              AND attendance_date >= ?
            ORDER BY attendance_date DESC
        ");
        $stmtDaily->execute($params);
        $daily_records = $stmtDaily->fetchAll(PDO::FETCH_ASSOC);

        foreach ($daily_records as $record) {
            $daily_attendance[$record['attendance_date']] = $record['status'];
        }
    }

    // Fetch monthly attendance summary for the last 6 months
    $monthly_attendance = [];
    if (!empty($batch_ids)) {
        $params = $batch_ids;
        $params[] = $_SESSION['student_id'];

        $stmtMonthly = $pdo->prepare("
            SELECT DATE_FORMAT(attendance_date, '%Y-%m') as month, status, COUNT(*) as count
            FROM attendance
            WHERE batch_id IN (" . implode(',', array_fill(0, count($batch_ids), '?')) . ")
              AND student_id = ?
            GROUP BY month, status
            ORDER BY month DESC
            LIMIT 6
        ");
        $stmtMonthly->execute(array_merge($params, [$params[count($params)-1]]));
        $monthly_records = $stmtMonthly->fetchAll(PDO::FETCH_ASSOC);

        $monthly_data = [];
        foreach ($monthly_records as $record) {
            $month = $record['month'];
            if (!isset($monthly_data[$month])) {
                $monthly_data[$month] = ['present' => 0, 'total' => 0];
            }
            if ($record['status'] !== 'holiday') {
                $monthly_data[$month]['total'] += $record['count'];
                if ($record['status'] === 'present') {
                    $monthly_data[$month]['present'] += $record['count'];
                }
            }
        }
        foreach ($monthly_data as $month => $data) {
            $percentage = $data['total'] > 0 ? round(($data['present'] / $data['total']) * 100) : 0;
            $monthly_attendance[$month] = [
                'present' => $data['present'],
                'total' => $data['total'],
                'percentage' => $percentage
            ];
        }
    }
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="<?php echo htmlspecialchars($lang); ?>">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Exam Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <style>
        .exam-card:hover {
            box-shadow: 0 0 11px rgba(33,33,33,.2);
            cursor: pointer;
            transform: translateY(-3px);
            transition: all 0.3s ease;
        }
        .badge-assigned {
            background-color: #0d6efd;
        }
        .badge-completed {
            background-color: #198754;
        }
        .no-exams-illustration {
            max-width: 300px;
            margin: 20px auto;
            display: block;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">MCQ Exam Portal</a>
    <div class="d-flex align-items-center">
      <span class="navbar-text text-white me-3"><?php echo htmlspecialchars($lang_strings[$lang]['welcome']); ?>, <?php echo htmlspecialchars($student_name); ?></span>
      <form method="get" class="me-3">
        <select name="lang" onchange="this.form.submit()" class="form-select form-select-sm" aria-label="Select language">
          <option value="en" <?php if($lang === 'en') echo 'selected'; ?>>English</option>
          <option value="hi" <?php if($lang === 'hi') echo 'selected'; ?>>हिन्दी</option>
        </select>
      </form>
      <a href="student_logout.php" class="btn btn-outline-light btn-sm"><?php echo htmlspecialchars($lang_strings[$lang]['logout']); ?></a>
    </div>
  </div>
</nav>
<div class="container my-4">
    <div class="mb-4">
        <h4>Attendance Progress</h4>
        <div class="progress" style="height: 25px; cursor: pointer;" data-bs-toggle="modal" data-bs-target="#attendanceModal" title="Click to view detailed attendance">
            <div class="progress-bar" role="progressbar" style="width: <?php echo $attendance_percentage; ?>%;" aria-valuenow="<?php echo $attendance_percentage; ?>" aria-valuemin="0" aria-valuemax="100">
                <?php echo $attendance_percentage; ?>%
            </div>
        </div>
        <p class="mt-2">Days Present: <?php echo $attendance_present_days; ?> / Total Days: <?php echo $attendance_total_days; ?></p>
    </div>

    <h2 class="mb-4"><?php echo htmlspecialchars($lang_strings[$lang]['your_exams']); ?></h2>
    <input type="text" id="searchInput" class="form-control mb-4" placeholder="<?php echo htmlspecialchars($lang_strings[$lang]['search_exams']); ?>" aria-label="Search exams" />

    <?php if (empty($exams)): ?>
        <div class="text-center">
            <img src="templates/no_exams.svg" alt="No exams" class="no-exams-illustration" />
            <p class="lead"><?php echo htmlspecialchars($lang_strings[$lang]['no_exams']); ?></p>
        </div>
    <?php else: ?>
        <div class="row" id="examsContainer">
            <?php foreach ($exams as $exam): ?>
            <div class="col-md-6 col-lg-4 mb-4 exam-card">
                <div class="card h-100 shadow-sm d-flex flex-column">
                    <div class="card-body d-flex flex-column">
                        <h5 class="card-title"><?php echo htmlspecialchars($exam['exam_name']); ?></h5>
                        <p class="card-text mb-2"><?php echo htmlspecialchars($lang_strings[$lang]['questions']); ?>: <?php echo isset($questions_count[$exam['id']]) ? $questions_count[$exam['id']] : 0; ?></p>
                        <p class="card-text mb-2">Duration: <?php echo htmlspecialchars($exam['duration']); ?> minutes</p>
                        <p class="card-text mb-2">Attempts Used: <?php echo htmlspecialchars($exam['attempts']); ?> / <?php echo htmlspecialchars($exam['allowed_attempts']); ?></p>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<!-- Attendance Details Modal -->
<div class="modal fade" id="attendanceModal" tabindex="-1" aria-labelledby="attendanceModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="attendanceModalLabel">Detailed Attendance</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <ul class="nav nav-tabs" id="attendanceTab" role="tablist">
          <li class="nav-item" role="presentation">
            <button class="nav-link active" id="daily-tab" data-bs-toggle="tab" data-bs-target="#daily" type="button" role="tab" aria-controls="daily" aria-selected="true">Daily</button>
          </li>
          <li class="nav-item" role="presentation">
            <button class="nav-link" id="monthly-tab" data-bs-toggle="tab" data-bs-target="#monthly" type="button" role="tab" aria-controls="monthly" aria-selected="false">Monthly</button>
          </li>
        </ul>
        <div class="tab-content mt-3" id="attendanceTabContent">
          <div class="tab-pane fade show active" id="daily" role="tabpanel" aria-labelledby="daily-tab">
            <?php if (!empty($daily_attendance)): ?>
            <table class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>Date</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($daily_attendance as $date => $status): ?>
                <tr>
                  <td><?php echo htmlspecialchars($date); ?></td>
                  <td><?php echo htmlspecialchars(ucfirst($status)); ?></td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
            <?php else: ?>
            <p>No daily attendance data available.</p>
            <?php endif; ?>
          </div>
          <div class="tab-pane fade" id="monthly" role="tabpanel" aria-labelledby="monthly-tab">
            <?php if (!empty($monthly_attendance)): ?>
            <table class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>Month</th>
                  <th>Days Present</th>
                  <th>Total Days</th>
                  <th>Attendance %</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($monthly_attendance as $month => $data): ?>
                <tr>
                  <td><?php echo htmlspecialchars($month); ?></td>
                  <td><?php echo htmlspecialchars($data['present']); ?></td>
                  <td><?php echo htmlspecialchars($data['total']); ?></td>
                  <td><?php echo htmlspecialchars($data['percentage']); ?>%</td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
            <?php else: ?>
            <p>No monthly attendance data available.</p>
            <?php endif; ?>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Enable Bootstrap tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    })

    // Search filter for exams
    const searchInput = document.getElementById('searchInput');
    const examsContainer = document.getElementById('examsContainer');
    const examCards = examsContainer ? examsContainer.getElementsByClassName('exam-card') : [];

    searchInput && searchInput.addEventListener('input', function() {
        const filter = this.value.toLowerCase();
        Array.from(examCards).forEach(card => {
            const title = card.querySelector('.card-title').textContent.toLowerCase();
            if (title.includes(filter)) {
                card.style.display = '';
            } else {
                card.style.display = 'none';
            }
        });
    });
</script>
</body>
</html>
