<?php
// ============================================================
// Missed Attendance Remark — Admin Settings Page
// Super admin controls the three-level feature toggle:
//   1. Global on/off
//   2. Per-teacher on/off
//   3. Per-class/section on/off
// ============================================================

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;
}

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

// CSRF token — generate once per session
if (empty($_SESSION['_csrf_mar'])) {
    $_SESSION['_csrf_mar'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['_csrf_mar'];

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

$msg = '';

// ============================================================
// POST handler
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // CSRF validation
    if (!hash_equals($csrf_token, $_POST['_csrf_mar'] ?? '')) {
        $msg = 'danger|Invalid security token. Please refresh and try again.';
    } else {
        $action = $_POST['action'] ?? '';

        // ----------------------------------------------------------
        // Action: save_global — update the global toggle
        // ----------------------------------------------------------
        if ($action === 'save_global') {
            $is_enabled = isset($_POST['global_enabled']) ? 1 : 0;
            $stmt = $con->prepare(
                "INSERT INTO portal_feature_settings (feature_key, is_enabled, updated_by, updated_at)
                 VALUES ('missed_attendance_remark', ?, ?, NOW())
                 ON DUPLICATE KEY UPDATE is_enabled = VALUES(is_enabled),
                                         updated_by  = VALUES(updated_by),
                                         updated_at  = VALUES(updated_at)"
            );
            $stmt->bind_param('ii', $is_enabled, $admin_id);
            $stmt->execute();
            $stmt->close();
            $msg = 'success|Global toggle updated successfully.';

        // ----------------------------------------------------------
        // Action: save_teacher — update a per-teacher toggle
        // ----------------------------------------------------------
        } elseif ($action === 'save_teacher') {
            $teacher_id = (int)($_POST['teacher_id'] ?? 0);
            $is_enabled = isset($_POST['teacher_enabled']) ? 1 : 0;
            if ($teacher_id > 0) {
                $stmt = $con->prepare(
                    "INSERT INTO missed_attendance_permissions (scope, teacher_id, is_enabled, updated_by, updated_at)
                     VALUES ('teacher', ?, ?, ?, NOW())
                     ON DUPLICATE KEY UPDATE is_enabled = VALUES(is_enabled),
                                             updated_by  = VALUES(updated_by),
                                             updated_at  = VALUES(updated_at)"
                );
                $stmt->bind_param('iii', $teacher_id, $is_enabled, $admin_id);
                $stmt->execute();
                $stmt->close();
                $msg = 'success|Teacher permission updated successfully.';
            } else {
                $msg = 'danger|Invalid teacher ID.';
            }

        // ----------------------------------------------------------
        // Action: save_class — update a per-class/section toggle
        // ----------------------------------------------------------
        } elseif ($action === 'save_class') {
            $class      = trim($_POST['class']   ?? '');
            $section    = trim($_POST['section'] ?? '');
            $is_enabled = isset($_POST['class_enabled']) ? 1 : 0;
            if ($class !== '' && $section !== '') {
                $stmt = $con->prepare(
                    "INSERT INTO missed_attendance_permissions (scope, class, section, is_enabled, updated_by, updated_at)
                     VALUES ('class', ?, ?, ?, ?, NOW())
                     ON DUPLICATE KEY UPDATE is_enabled = VALUES(is_enabled),
                                             updated_by  = VALUES(updated_by),
                                             updated_at  = VALUES(updated_at)"
                );
                $stmt->bind_param('ssii', $class, $section, $is_enabled, $admin_id);
                $stmt->execute();
                $stmt->close();
                $msg = 'success|Class permission updated successfully.';
            } else {
                $msg = 'danger|Invalid class or section.';
            }
        }
    }
}

// ============================================================
// Load current state
// ============================================================

// Global toggle
$global_row = null;
$res = $con->query("SELECT is_enabled, updated_by, updated_at FROM portal_feature_settings WHERE feature_key = 'missed_attendance_remark' LIMIT 1");
if ($res) {
    $global_row = $res->fetch_assoc();
}
$global_enabled = (int)($global_row['is_enabled'] ?? 0);

// All teachers (non-super-admin, active)
$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()) {
        $teachers[] = $row;
    }
}

// Per-teacher permissions (keyed by teacher_id)
$teacher_perms = [];
$res = $con->query("SELECT teacher_id, is_enabled FROM missed_attendance_permissions WHERE scope = 'teacher'");
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $teacher_perms[(int)$row['teacher_id']] = (int)$row['is_enabled'];
    }
}

// All class/section pairs
$classes = [];
$res = $con->query("SELECT class, section FROM class_section ORDER BY class ASC, section ASC");
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $classes[] = $row;
    }
}

// Per-class permissions (keyed by "class||section")
$class_perms = [];
$res = $con->query("SELECT class, section, is_enabled FROM missed_attendance_permissions WHERE scope = 'class'");
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $class_perms[$row['class'] . '||' . $row['section']] = (int)$row['is_enabled'];
    }
}
?>
<!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-calendar-times"></i>
                                </div>
                                <div>
                                    <h1 class="premium-title text-primary">
                                        Attendance Settings
                                        <span class="premium-subtitle text-secondary">Missed Attendance Remark Permissions</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 active">Missed Attendance Settings</li>
                                </ol>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </section>

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

                <?php if ($msg):
                    [$type, $text] = explode('|', $msg, 2); ?>
                    <div class="alert alert-<?= htmlspecialchars($type) ?> alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        <i class="fas <?= $type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle' ?> mr-2"></i>
                        <?= htmlspecialchars($text) ?>
                    </div>
                <?php endif; ?>

                <!-- ================================================
                     Section 1: Global Toggle
                ================================================ -->
                <div class="card card-primary 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-globe mr-2"></i>Global Toggle
                        </h5>
                    </div>
                    <div class="card-body">
                        <p class="text-muted mb-3">
                            Master switch for the Missed Attendance Remark feature. When disabled, no teacher can access
                            the feature regardless of individual or class-level settings.
                        </p>
                        <form method="POST">
                            <input type="hidden" name="_csrf_mar" value="<?= htmlspecialchars($csrf_token) ?>">
                            <input type="hidden" name="action" value="save_global">
                            <div class="d-flex align-items-center">
                                <div class="custom-control custom-switch mr-4">
                                    <input type="checkbox" class="custom-control-input" id="global_enabled"
                                           name="global_enabled" value="1"
                                           <?= $global_enabled ? 'checked' : '' ?>>
                                    <label class="custom-control-label font-weight-bold" for="global_enabled">
                                        <?= $global_enabled ? '<span class="text-success">Enabled</span>' : '<span class="text-danger">Disabled</span>' ?>
                                    </label>
                                </div>
                                <button type="submit" class="btn btn-primary btn-sm">
                                    <i class="fas fa-save mr-1"></i>Save
                                </button>
                            </div>
                            <?php if (!empty($global_row['updated_at'])): ?>
                                <small class="text-muted mt-2 d-block">
                                    Last updated: <?= htmlspecialchars(date('d M Y, h:i A', strtotime($global_row['updated_at']))) ?>
                                    by Admin #<?= (int)$global_row['updated_by'] ?>
                                </small>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>

                <!-- ================================================
                     Section 2: Per-Teacher Toggles
                ================================================ -->
                <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-chalkboard-teacher mr-2"></i>Per-Teacher Permissions
                        </h5>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($teachers)): ?>
                            <div class="text-center py-4 text-muted">
                                <i class="fas fa-users fa-2x mb-2 d-block"></i>No teachers found.
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover table-sm mb-0">
                                    <thead style="background:linear-gradient(135deg,#343a40,#495057);color:#fff;">
                                        <tr>
                                            <th style="width:50px;">#</th>
                                            <th>Teacher Name</th>
                                            <th style="width:160px;">Access</th>
                                            <th style="width:100px;">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($teachers as $i => $teacher):
                                            $tid     = (int)$teacher['id'];
                                            $enabled = $teacher_perms[$tid] ?? 0;
                                            $title   = htmlspecialchars($teacher['title'] ?? '');
                                            $name    = htmlspecialchars($teacher['name'] . ' ' . $teacher['lastname']);
                                        ?>
                                        <tr>
                                            <td><?= $i + 1 ?></td>
                                            <td><?= $title ? $title . '. ' : '' ?><?= $name ?></td>
                                            <td>
                                                <span class="badge <?= $enabled ? 'badge-success' : 'badge-secondary' ?>">
                                                    <?= $enabled ? 'Enabled' : 'Disabled' ?>
                                                </span>
                                            </td>
                                            <td>
                                                <form method="POST" class="d-inline">
                                                    <input type="hidden" name="_csrf_mar" value="<?= htmlspecialchars($csrf_token) ?>">
                                                    <input type="hidden" name="action" value="save_teacher">
                                                    <input type="hidden" name="teacher_id" value="<?= $tid ?>">
                                                    <?php if ($enabled): ?>
                                                        <button type="submit" class="btn btn-sm btn-outline-danger"
                                                                title="Disable for this teacher">
                                                            <i class="fas fa-toggle-on mr-1"></i>Disable
                                                        </button>
                                                    <?php else: ?>
                                                        <input type="hidden" name="teacher_enabled" value="1">
                                                        <button type="submit" class="btn btn-sm btn-outline-success"
                                                                title="Enable for this teacher">
                                                            <i class="fas fa-toggle-off mr-1"></i>Enable
                                                        </button>
                                                    <?php endif; ?>
                                                </form>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- ================================================
                     Section 3: Per-Class Toggles
                ================================================ -->
                <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-school mr-2"></i>Per-Class Permissions
                        </h5>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($classes)): ?>
                            <div class="text-center py-4 text-muted">
                                <i class="fas fa-school fa-2x mb-2 d-block"></i>No classes found.
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover table-sm mb-0">
                                    <thead style="background:linear-gradient(135deg,#343a40,#495057);color:#fff;">
                                        <tr>
                                            <th style="width:50px;">#</th>
                                            <th>Class</th>
                                            <th>Section</th>
                                            <th style="width:160px;">Access</th>
                                            <th style="width:100px;">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($classes as $i => $cls):
                                            $key     = $cls['class'] . '||' . $cls['section'];
                                            $enabled = $class_perms[$key] ?? 0;
                                        ?>
                                        <tr>
                                            <td><?= $i + 1 ?></td>
                                            <td><?= htmlspecialchars($cls['class']) ?></td>
                                            <td><?= htmlspecialchars($cls['section']) ?></td>
                                            <td>
                                                <span class="badge <?= $enabled ? 'badge-success' : 'badge-secondary' ?>">
                                                    <?= $enabled ? 'Enabled' : 'Disabled' ?>
                                                </span>
                                            </td>
                                            <td>
                                                <form method="POST" class="d-inline">
                                                    <input type="hidden" name="_csrf_mar" value="<?= htmlspecialchars($csrf_token) ?>">
                                                    <input type="hidden" name="action" value="save_class">
                                                    <input type="hidden" name="class"   value="<?= htmlspecialchars($cls['class']) ?>">
                                                    <input type="hidden" name="section" value="<?= htmlspecialchars($cls['section']) ?>">
                                                    <?php if ($enabled): ?>
                                                        <button type="submit" class="btn btn-sm btn-outline-danger"
                                                                title="Disable for this class">
                                                            <i class="fas fa-toggle-on mr-1"></i>Disable
                                                        </button>
                                                    <?php else: ?>
                                                        <input type="hidden" name="class_enabled" value="1">
                                                        <button type="submit" class="btn btn-sm btn-outline-success"
                                                                title="Enable for this class">
                                                            <i class="fas fa-toggle-off mr-1"></i>Enable
                                                        </button>
                                                    <?php endif; ?>
                                                </form>
                                            </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>

<script>
// Update the global toggle label dynamically
document.getElementById('global_enabled').addEventListener('change', function () {
    var label = this.closest('.custom-control').querySelector('.custom-control-label');
    label.innerHTML = this.checked
        ? '<span class="text-success">Enabled</span>'
        : '<span class="text-danger">Disabled</span>';
});
</script>
</body>
</html>
