<?php
// ============================================================
// Missed Attendance Remark — Teacher Page
// Class teachers can select any past date and mark/correct
// attendance for students in their assigned class.
// Access is gated by the three-level toggle.
// ============================================================

include('includes/session1.php');
error_reporting(0);
include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';
require_once __DIR__ . '/includes/flash.php';
require_once __DIR__ . '/includes/missed_attendance_helper.php';

// ============================================================
// 1. Authentication
// ============================================================
if (!isset($_SESSION['sid'])) {
    header('location:logoutteacher.php');
    exit;
}

$teacher_id = (int)$_SESSION['sid'];

// ============================================================
// 2. Class teacher check — resolve class/section from DB
// ============================================================
$ct_stmt = $con->prepare(
    "SELECT cs.class, cs.section
     FROM teacher_assignments ta
     JOIN class_section cs ON ta.class_id = cs.id
     WHERE ta.teacher_id = ? AND ta.is_class_teacher = 1
     LIMIT 1"
);
$ct_stmt->bind_param('i', $teacher_id);
$ct_stmt->execute();
$ct_row = $ct_stmt->get_result()->fetch_assoc();
$ct_stmt->close();

if (!$ct_row) {
    flash_alert('You are not assigned as a class teacher.');
    header('location:teacher_dashboard.php');
    exit;
}

$class   = $ct_row['class'];
$section = $ct_row['section'];

// ============================================================
// 3. Effective access check
// ============================================================
if (!checkMissedAttendanceAccess($con, $teacher_id, $class, $section)) {
    flash_alert('Missed attendance remark is not currently enabled for your account.');
    header('location:teacher_dashboard.php');
    exit;
}

// ============================================================
// 4. Session / term
// ============================================================
$stResult           = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];

// ============================================================
// 5. Date handling
// ============================================================
$yesterday    = date('Y-m-d', strtotime('-1 day'));
$date_error   = '';
$selected_date = '';
$students      = [];
$attendance_data = [];

$raw_date = trim($_GET['date'] ?? '');

if ($raw_date !== '') {
    $date_obj = DateTime::createFromFormat('Y-m-d', $raw_date);
    $valid    = $date_obj && $date_obj->format('Y-m-d') === $raw_date;

    if (!$valid) {
        $date_error = 'Invalid date format. Please use the date picker.';
    } elseif ($date_obj >= new DateTime('today')) {
        $date_error = 'Please select a past date. Today\'s and future dates are not allowed.';
    } else {
        $selected_date = $date_obj->format('Y-m-d');

        // Fetch active students
        $s_stmt = $con->prepare(
            "SELECT id, studentName, studentno
             FROM students
             WHERE class = ? AND section = ? AND status < 3
             ORDER BY studentName ASC"
        );
        $s_stmt->bind_param('ss', $class, $section);
        $s_stmt->execute();
        $s_result = $s_stmt->get_result();
        while ($row = $s_result->fetch_assoc()) {
            $students[] = $row;
        }
        $s_stmt->close();

        // Fetch existing attendance for the selected date
        $a_stmt = $con->prepare(
            "SELECT student_id, status
             FROM attendance
             WHERE class = ? AND section = ? AND date = ?"
        );
        $a_stmt->bind_param('sss', $class, $section, $selected_date);
        $a_stmt->execute();
        $a_result = $a_stmt->get_result();
        while ($row = $a_result->fetch_assoc()) {
            $attendance_data[(int)$row['student_id']] = $row['status'];
        }
        $a_stmt->close();
    }
}

// Teacher display info
$t_stmt = $con->prepare("SELECT name, lastname, title FROM tblusers WHERE id = ? LIMIT 1");
$t_stmt->bind_param('i', $teacher_id);
$t_stmt->execute();
$t_row = $t_stmt->get_result()->fetch_assoc();
$t_stmt->close();
$teacher_name = ($t_row['title'] ? $t_row['title'] . '. ' : '') . ($t_row['name'] ?? '') . ' ' . ($t_row['lastname'] ?? '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php @include('includes/head.php'); ?>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <?php @include('includes/headert.php'); ?>
    <?php @include('includes/sidebart.php'); ?>

    <div class="content-wrapper">

        <!-- Page Header -->
        <section class="content-header premium-header">
            <div class="container-fluid">
                <div class="header-glass-card">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <div class="title-section">
                                <div class="icon-box bg-primary-gradient shadow-sm">
                                    <i class="fas fa-history"></i>
                                </div>
                                <div>
                                    <h1 class="premium-title text-primary">
                                        Missed Attendance
                                        <span class="premium-subtitle text-secondary">
                                            <?= htmlspecialchars($class . ' - ' . $section) ?>
                                        </span>
                                    </h1>
                                    <div class="mt-1">
                                        <?php if ($currentSessionName): ?>
                                            <span class="badge badge-primary mr-1">
                                                <i class="fas fa-calendar-alt"></i>
                                                <?= htmlspecialchars($currentSessionName) ?>
                                            </span>
                                        <?php endif; ?>
                                        <?php if ($currentTermName): ?>
                                            <span class="badge badge-success">
                                                <i class="fas fa-bookmark"></i>
                                                <?= htmlspecialchars($currentTermName) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge badge-warning">
                                                <i class="fas fa-exclamation-triangle"></i> No active term
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <nav aria-label="breadcrumb">
                                <ol class="breadcrumb premium-breadcrumb">
                                    <li class="breadcrumb-item">
                                        <a href="teacher_dashboard.php" class="text-primary">Home</a>
                                    </li>
                                    <li class="breadcrumb-item active">Missed Attendance</li>
                                </ol>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <section class="content">
            <div class="container-fluid">

                <!-- Flash messages -->
                <div id="flash-area"></div>

                <!-- Date Picker Card -->
                <div class="card shadow-sm mb-4" style="border-radius:12px;">
                    <div class="card-header" style="background:linear-gradient(135deg,#007bff,#0056b3);border-radius:12px 12px 0 0;">
                        <h5 class="card-title mb-0 text-white font-weight-bold">
                            <i class="fas fa-calendar-day mr-2"></i>Select Date
                        </h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="form-inline">
                            <div class="form-group mr-3">
                                <label for="date" class="mr-2 font-weight-bold">Attendance Date:</label>
                                <input type="date"
                                       id="date"
                                       name="date"
                                       class="form-control <?= $date_error ? 'is-invalid' : '' ?>"
                                       max="<?= htmlspecialchars($yesterday) ?>"
                                       value="<?= htmlspecialchars($selected_date ?: $raw_date) ?>"
                                       required>
                                <?php if ($date_error): ?>
                                    <div class="invalid-feedback d-block ml-2">
                                        <i class="fas fa-exclamation-circle mr-1"></i><?= htmlspecialchars($date_error) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search mr-1"></i>Load Students
                            </button>
                        </form>
                        <?php if ($selected_date): ?>
                            <small class="text-muted mt-2 d-block">
                                <i class="fas fa-info-circle mr-1"></i>
                                Showing attendance for <strong><?= htmlspecialchars(date('l, F j, Y', strtotime($selected_date))) ?></strong>
                            </small>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if ($selected_date && !$date_error): ?>

                <!-- Attendance Form Card -->
                <div class="card shadow-sm" style="border-radius:12px;">
                    <div class="card-header d-flex align-items-center" style="background:linear-gradient(135deg,#007bff,#0056b3);border-radius:12px 12px 0 0;">
                        <h5 class="card-title mb-0 text-white font-weight-bold">
                            <i class="fas fa-clipboard-list mr-2"></i>
                            Attendance — <?= htmlspecialchars($class . ' ' . $section) ?>
                            &nbsp;<small style="opacity:.85;"><?= htmlspecialchars(date('d M Y', strtotime($selected_date))) ?></small>
                        </h5>
                        <?php
                        $marked   = count(array_filter($attendance_data));
                        $total    = count($students);
                        $present  = count(array_filter($attendance_data, fn($s) => $s === 'Present'));
                        $absent   = count(array_filter($attendance_data, fn($s) => $s === 'Absent'));
                        $unmarked = $total - count($attendance_data);
                        ?>
                        <div class="ml-auto d-flex gap-2" style="gap:6px;">
                            <span class="badge badge-success"><?= $present ?> Present</span>
                            <span class="badge badge-danger"><?= $absent ?> Absent</span>
                            <?php if ($unmarked > 0): ?>
                                <span class="badge badge-secondary"><?= $unmarked ?> Not Marked</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="card-body">

                        <?php if (empty($students)): ?>
                            <div class="alert alert-warning mb-0">
                                <i class="fas fa-exclamation-circle mr-2"></i>
                                No active students found in <?= htmlspecialchars($class . ' - ' . $section) ?>.
                            </div>
                        <?php else: ?>

                        <div class="alert alert-info border-0 mb-3" style="background:linear-gradient(135deg,#e3f2fd,#bbdefb);">
                            <i class="fas fa-info-circle mr-2"></i>
                            Mark attendance for each student below, then click <strong>Save Attendance</strong>.
                            Existing records will be updated; new records will be created.
                        </div>

                        <div class="table-responsive">
                            <table class="table table-hover table-sm" id="example1">
                                <thead style="background:linear-gradient(135deg,#343a40,#495057);color:#fff;">
                                    <tr>
                                        <th style="width:50px;">#</th>
                                        <th>Adm. No</th>
                                        <th>Student Name</th>
                                        <th style="width:120px;">Present</th>
                                        <th style="width:120px;">Absent</th>
                                        <th style="width:120px;">Current Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($students as $idx => $student):
                                        $sid        = (int)$student['id'];
                                        $cur_status = $attendance_data[$sid] ?? null;
                                        $is_present = $cur_status === 'Present';
                                        $is_absent  = $cur_status === 'Absent';
                                    ?>
                                    <tr id="row-<?= $sid ?>">
                                        <td><?= $idx + 1 ?></td>
                                        <td><?= htmlspecialchars($student['studentno']) ?></td>
                                        <td><?= htmlspecialchars($student['studentName']) ?></td>
                                        <td>
                                            <div class="custom-control custom-radio">
                                                <input type="radio"
                                                       class="custom-control-input attendance-radio"
                                                       id="present_<?= $sid ?>"
                                                       name="attendance[<?= $sid ?>]"
                                                       value="Present"
                                                       data-student-id="<?= $sid ?>"
                                                       <?= $is_present ? 'checked' : '' ?>>
                                                <label class="custom-control-label text-success font-weight-bold"
                                                       for="present_<?= $sid ?>">Present</label>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="custom-control custom-radio">
                                                <input type="radio"
                                                       class="custom-control-input attendance-radio"
                                                       id="absent_<?= $sid ?>"
                                                       name="attendance[<?= $sid ?>]"
                                                       value="Absent"
                                                       data-student-id="<?= $sid ?>"
                                                       <?= $is_absent ? 'checked' : '' ?>>
                                                <label class="custom-control-label text-danger font-weight-bold"
                                                       for="absent_<?= $sid ?>">Absent</label>
                                            </div>
                                        </td>
                                        <td>
                                            <?php if ($cur_status === 'Present'): ?>
                                                <span class="badge badge-success" id="status-badge-<?= $sid ?>">Present</span>
                                            <?php elseif ($cur_status === 'Absent'): ?>
                                                <span class="badge badge-danger" id="status-badge-<?= $sid ?>">Absent</span>
                                            <?php else: ?>
                                                <span class="badge badge-secondary" id="status-badge-<?= $sid ?>">Not Marked</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <div class="mt-3 d-flex align-items-center">
                            <button type="button" id="save-attendance-btn" class="btn btn-primary mr-3">
                                <i class="fas fa-save mr-1"></i>Save Attendance
                            </button>
                            <button type="button" id="mark-all-present-btn" class="btn btn-outline-success btn-sm mr-2">
                                <i class="fas fa-check-double mr-1"></i>Mark All Present
                            </button>
                            <button type="button" id="mark-all-absent-btn" class="btn btn-outline-danger btn-sm">
                                <i class="fas fa-times-circle mr-1"></i>Mark All Absent
                            </button>
                            <span id="save-spinner" class="ml-3" style="display:none;">
                                <i class="fas fa-spinner fa-spin text-primary"></i> Saving...
                            </span>
                        </div>

                        <?php endif; // end if students ?>
                    </div>
                </div>

                <?php endif; // end if selected_date ?>

            </div>
        </section>
    </div>

    <?php @include('includes/footer.php'); ?>
    <?php @include('includes/foot.php'); ?>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
(function ($) {
    var selectedDate = <?= json_encode($selected_date) ?>;
    var classVal     = <?= json_encode($class) ?>;
    var sectionVal   = <?= json_encode($section) ?>;

    // Mark all present
    $('#mark-all-present-btn').on('click', function () {
        $('input.attendance-radio[value="Present"]').prop('checked', true);
    });

    // Mark all absent
    $('#mark-all-absent-btn').on('click', function () {
        $('input.attendance-radio[value="Absent"]').prop('checked', true);
    });

    // Save attendance via AJAX
    $('#save-attendance-btn').on('click', function () {
        var attendance = {};
        var allMarked  = true;

        $('input.attendance-radio:checked').each(function () {
            attendance[$(this).data('student-id')] = $(this).val();
        });

        // Check if any student has no selection
        $('input.attendance-radio').each(function () {
            var sid = $(this).data('student-id');
            if (!attendance[sid]) {
                allMarked = false;
            }
        });

        if (!allMarked) {
            showFlash('warning', 'Please mark attendance (Present or Absent) for all students before saving.');
            return;
        }

        if (Object.keys(attendance).length === 0) {
            showFlash('warning', 'No students to save.');
            return;
        }

        $('#save-attendance-btn').prop('disabled', true);
        $('#save-spinner').show();

        $.ajax({
            url: 'save_missed_attendance.php',
            type: 'POST',
            data: {
                date:       selectedDate,
                class:      classVal,
                section:    sectionVal,
                attendance: attendance
            },
            dataType: 'json',
            success: function (resp) {
                if (resp.success) {
                    showFlash('success', 'Attendance saved successfully for ' + selectedDate + '.');
                    // Update status badges
                    $.each(attendance, function (sid, status) {
                        var badge = $('#status-badge-' + sid);
                        if (status === 'Present') {
                            badge.removeClass('badge-danger badge-secondary').addClass('badge-success').text('Present');
                        } else {
                            badge.removeClass('badge-success badge-secondary').addClass('badge-danger').text('Absent');
                        }
                    });
                } else {
                    showFlash('danger', resp.message || 'Failed to save attendance. Please try again.');
                }
            },
            error: function (xhr) {
                var msg = 'An error occurred. Please try again.';
                try { msg = JSON.parse(xhr.responseText).message || msg; } catch (e) {}
                showFlash('danger', msg);
            },
            complete: function () {
                $('#save-attendance-btn').prop('disabled', false);
                $('#save-spinner').hide();
            }
        });
    });

    function showFlash(type, message) {
        var icons = { success: 'fa-check-circle', danger: 'fa-exclamation-circle', warning: 'fa-exclamation-triangle', info: 'fa-info-circle' };
        var icon  = icons[type] || 'fa-info-circle';
        var html  = '<div class="alert alert-' + type + ' alert-dismissible shadow-sm border-0 mt-2">' +
                    '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
                    '<i class="fas ' + icon + ' mr-2"></i>' + message + '</div>';
        $('#flash-area').html(html);
        $('html, body').animate({ scrollTop: 0 }, 300);
        // Auto-dismiss success after 4 s
        if (type === 'success') {
            setTimeout(function () { $('#flash-area .alert').fadeOut(400, function () { $(this).remove(); }); }, 4000);
        }
    }
}(jQuery));
</script>
</body>
</html>
