<?php
// ============================================================
// Missed Attendance Remark — Admin Audit Log View
// Read-only. Super admin only.
// Filterable by date range, class, section, teacher.
// ============================================================

session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
    mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();

error_reporting(0);
include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';

// Auth guard — Super User only
if (empty($_SESSION['sid']) || ($_SESSION['permission'] ?? '') !== 'Super User') {
    header('location:logout.php');
    exit;
}

$stResult           = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];

// ============================================================
// Sanitise filter inputs
// ============================================================
$f_date_from  = '';
$f_date_to    = '';
$f_class      = '';
$f_section    = '';
$f_teacher_id = 0;

if (!empty($_GET['date_from'])) {
    $d = DateTime::createFromFormat('Y-m-d', $_GET['date_from']);
    if ($d) $f_date_from = $d->format('Y-m-d');
}
if (!empty($_GET['date_to'])) {
    $d = DateTime::createFromFormat('Y-m-d', $_GET['date_to']);
    if ($d) $f_date_to = $d->format('Y-m-d');
}
if (!empty($_GET['class']))      $f_class      = trim($_GET['class']);
if (!empty($_GET['section']))    $f_section    = trim($_GET['section']);
if (!empty($_GET['teacher_id'])) $f_teacher_id = (int)$_GET['teacher_id'];

// ============================================================
// Build parameterised query
// ============================================================
$where  = [];
$params = [];
$types  = '';

if ($f_date_from !== '') { $where[] = 'mal.attendance_date >= ?'; $params[] = $f_date_from; $types .= 's'; }
if ($f_date_to   !== '') { $where[] = 'mal.attendance_date <= ?'; $params[] = $f_date_to;   $types .= 's'; }
if ($f_class     !== '') { $where[] = 'mal.class = ?';            $params[] = $f_class;      $types .= 's'; }
if ($f_section   !== '') { $where[] = 'mal.section = ?';          $params[] = $f_section;    $types .= 's'; }
if ($f_teacher_id > 0)   { $where[] = 'mal.teacher_id = ?';       $params[] = $f_teacher_id; $types .= 'i'; }

$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
    SELECT
        mal.id,
        mal.attendance_date,
        CONCAT(COALESCE(u.title,''), IF(u.title IS NOT NULL AND u.title != '', '. ', ''),
               u.name, ' ', u.lastname) AS teacher_name,
        mal.class,
        mal.section,
        s.studentName,
        mal.old_status,
        mal.new_status,
        mal.remarked_at,
        mal.ip_address
    FROM missed_attendance_log mal
    JOIN tblusers u  ON u.id  = mal.teacher_id
    JOIN students s  ON s.id  = mal.student_id
    $where_sql
    ORDER BY mal.remarked_at DESC
    LIMIT 500
";

$logs = [];
if ($params) {
    $stmt = $con->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) $logs[] = $row;
    $stmt->close();
} else {
    $result = $con->query($sql);
    if ($result) while ($row = $result->fetch_assoc()) $logs[] = $row;
}

// ============================================================
// Dropdown data for filter form
// ============================================================
$all_teachers = [];
$res = $con->query("SELECT id, name, lastname, title FROM tblusers WHERE permission != 'Super User' AND status > 0 ORDER BY name ASC");
if ($res) while ($row = $res->fetch_assoc()) $all_teachers[] = $row;

$all_classes = [];
$res = $con->query("SELECT DISTINCT class, section FROM class_section ORDER BY class ASC, section ASC");
if ($res) while ($row = $res->fetch_assoc()) $all_classes[] = $row;
?>
<!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/header.php'); ?>
    <?php include('includes/sidebar.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">
                                        Attendance Audit
                                        <span class="premium-subtitle text-secondary">Missed Attendance Remark Log</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="dashboard.php" class="text-primary">Home</a></li>
                                    <li class="breadcrumb-item"><a href="missed_attendance_settings.php" class="text-primary">Attendance Settings</a></li>
                                    <li class="breadcrumb-item active">Remark Log</li>
                                </ol>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </section>

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

                <!-- Filter Form -->
                <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-filter mr-2"></i>Filter Log
                        </h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="row">
                            <div class="col-md-2 mb-2">
                                <label class="small font-weight-bold">Date From</label>
                                <input type="date" name="date_from" class="form-control form-control-sm"
                                       value="<?= htmlspecialchars($f_date_from) ?>">
                            </div>
                            <div class="col-md-2 mb-2">
                                <label class="small font-weight-bold">Date To</label>
                                <input type="date" name="date_to" class="form-control form-control-sm"
                                       value="<?= htmlspecialchars($f_date_to) ?>">
                            </div>
                            <div class="col-md-2 mb-2">
                                <label class="small font-weight-bold">Class</label>
                                <select name="class" class="form-control form-control-sm">
                                    <option value="">All Classes</option>
                                    <?php foreach ($all_classes as $cls): ?>
                                        <option value="<?= htmlspecialchars($cls['class']) ?>"
                                            <?= $f_class === $cls['class'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($cls['class']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2 mb-2">
                                <label class="small font-weight-bold">Section</label>
                                <select name="section" class="form-control form-control-sm">
                                    <option value="">All Sections</option>
                                    <?php
                                    $sections = array_unique(array_column($all_classes, 'section'));
                                    sort($sections);
                                    foreach ($sections as $sec): ?>
                                        <option value="<?= htmlspecialchars($sec) ?>"
                                            <?= $f_section === $sec ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($sec) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3 mb-2">
                                <label class="small font-weight-bold">Teacher</label>
                                <select name="teacher_id" class="form-control form-control-sm">
                                    <option value="">All Teachers</option>
                                    <?php foreach ($all_teachers as $t): ?>
                                        <option value="<?= (int)$t['id'] ?>"
                                            <?= $f_teacher_id === (int)$t['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars(($t['title'] ? $t['title'] . '. ' : '') . $t['name'] . ' ' . $t['lastname']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-1 mb-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary btn-sm w-100">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                            <?php if ($f_date_from || $f_date_to || $f_class || $f_section || $f_teacher_id): ?>
                                <div class="col-12">
                                    <a href="missed_attendance_log_view.php" class="btn btn-sm btn-outline-secondary">
                                        <i class="fas fa-times mr-1"></i>Clear Filters
                                    </a>
                                </div>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>

                <!-- Log Table -->
                <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-list mr-2"></i>Remark Log
                        </h5>
                        <span class="badge badge-light ml-2"><?= count($logs) ?></span>
                        <?php if (count($logs) === 500): ?>
                            <small class="text-white ml-2" style="opacity:.8;">(showing latest 500 records)</small>
                        <?php endif; ?>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($logs)): ?>
                            <div class="text-center py-5 text-muted">
                                <i class="fas fa-history fa-2x mb-2 d-block opacity-50"></i>
                                <p class="mb-0">No remark log entries found.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover table-sm mb-0" id="example1">
                                    <thead style="background:linear-gradient(135deg,#343a40,#495057);color:#fff;">
                                        <tr>
                                            <th>#</th>
                                            <th>Attendance Date</th>
                                            <th>Teacher</th>
                                            <th>Class / Section</th>
                                            <th>Student</th>
                                            <th>Old Status</th>
                                            <th>New Status</th>
                                            <th>Remarked At</th>
                                            <th>IP Address</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($logs as $i => $log): ?>
                                        <tr>
                                            <td><?= $i + 1 ?></td>
                                            <td><?= htmlspecialchars(date('d M Y', strtotime($log['attendance_date']))) ?></td>
                                            <td><?= htmlspecialchars($log['teacher_name']) ?></td>
                                            <td><?= htmlspecialchars($log['class'] . ' - ' . $log['section']) ?></td>
                                            <td><?= htmlspecialchars($log['studentName']) ?></td>
                                            <td>
                                                <?php if ($log['old_status'] === null): ?>
                                                    <span class="badge badge-secondary">Not Marked</span>
                                                <?php elseif ($log['old_status'] === 'Present'): ?>
                                                    <span class="badge badge-success">Present</span>
                                                <?php else: ?>
                                                    <span class="badge badge-danger">Absent</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($log['new_status'] === 'Present'): ?>
                                                    <span class="badge badge-success">Present</span>
                                                <?php else: ?>
                                                    <span class="badge badge-danger">Absent</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?= htmlspecialchars(date('d M Y, h:i A', strtotime($log['remarked_at']))) ?></td>
                                            <td><code style="font-size:11px;"><?= htmlspecialchars($log['ip_address'] ?? '—') ?></code></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

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

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