<?php
date_default_timezone_set('Africa/Lagos'); // Replace with your desired time zone

use Dotenv\Dotenv;

// Load Composer dependencies
require 'vendor/autoload.php';
// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$school_name = $_ENV['SCHOOL_NAME'];
$school_address = $_ENV['SCHOOL_ADDRESS'];
$prefix = $_ENV['Admission_prefix'];
$logo = $_ENV['WEBSITE_LOGO'];
$favicon = $_ENV['WEBSITE_FAVICON'];

// Resolve current session & term for auto-select across all pages
$_headCurrentSessionName = null;
$_headCurrentTermName = null;
$_headCurrentSessionId = null;
$_headCurrentTermId = null;

if (!function_exists('resolveCurrentSessionTerm')) {
    // Only load helper if not already loaded by the page
    $helperPath = __DIR__ . '/session_term_helper.php';
    if (file_exists($helperPath))
        require_once $helperPath;
}

// $con may already be defined by the including page
if (isset($con) && $con instanceof mysqli) {
    $_st = resolveCurrentSessionTerm($con);
    $_headCurrentSessionId = $_st['session_id'] ?: null;
    $_headCurrentSessionName = $_st['session_name'] ?? null;
    $_headCurrentTermId = $_st['term_id'] ?: null;
    $_headCurrentTermName = $_st['term_name'] ?? null;
}
?>



<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title><?php echo $school_name; ?> - School Payment & Management System</title>
    <link rel="icon" type="image/x-icon" href="<?php echo $favicon; ?>" class="favicon-icon-rounded">

    <!-- SEO Enhancements -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description"
        content="<?php echo $school_name; ?> - A modern school management system for seamless administration, payment and user experience.">
    <meta name="keywords"
        content="<?php echo $school_name; ?>, School Management System, Education, Ibadan, Online Payment, Student Portal">
    <meta name="author" content="<?php echo $school_name; ?>">

    <!-- Google Font: Source Sans Pro (non-blocking) -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=swap"
        media="print" onload="this.media='all'">
    <noscript>
        <link rel="stylesheet"
            href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=swap">
    </noscript>

    <!-- Font Awesome (local) -->
    <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">

    <!-- AdminLTE Theme (local) — load early, it's critical -->
    <link rel="stylesheet" href="dist/css/adminlte.min.css">

    <!-- Select2 (local) -->
    <link rel="stylesheet" href="dist/css/select2.min.css">

    <!-- DataTables (local) -->
    <link rel="stylesheet" href="plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="plugins/datatables-responsive/css/responsive.bootstrap4.min.css">

    <!-- Tempusdominus Bootstrap 4 (local) -->
    <link rel="stylesheet" href="plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css">

    <!-- iCheck (local) -->
    <link rel="stylesheet" href="plugins/icheck-bootstrap/icheck-bootstrap.min.css">

    <!-- JQVMap (local) -->
    <link rel="stylesheet" href="plugins/jqvmap/jqvmap.min.css">

    <!-- overlayScrollbars (local) -->
    <link rel="stylesheet" href="plugins/overlayScrollbars/css/OverlayScrollbars.min.css">

    <!-- Daterange Picker (local) -->
    <link rel="stylesheet" href="plugins/daterangepicker/daterangepicker.css">

    <!-- Summernote (local) -->
    <link rel="stylesheet" href="plugins/summernote/summernote-bs4.css">

    <!-- SweetAlert2 (local) -->
    <link rel="stylesheet" href="plugins/sweetalert2/sweetalert2.min.css">

    <!-- FullCalendar (local) -->
    <link rel="stylesheet" href="plugins/fullcalendar/main.min.css">

    <!-- Ionicons (non-blocking, low priority) -->
    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" media="print"
        onload="this.media='all'">

    <!-- Quill CSS (non-blocking, only needed on pages with editor) -->
    <link rel="stylesheet" href="https://cdn.quilljs.com/1.3.6/quill.snow.css" media="print" onload="this.media='all'">

    <!-- jQuery (local) -->
    <script src="plugins/jquery/jquery.min.js"></script>

    <!-- Paystack (must stay CDN — payment gateway) -->
    <script src="https://js.paystack.co/v1/inline.js" defer></script>

    <!-- Page loader: covers blank screen while JS loads, fades out when ready -->
    <style>
        #page-loader {
            position: fixed;
            inset: 0;
            z-index: 99999;
            background: #f8fafc;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 18px;
            transition: opacity 0.35s ease, visibility 0.35s ease;
        }

        #page-loader.hide {
            opacity: 0;
            visibility: hidden;
            pointer-events: none;
        }

        #page-loader .pl-logo {
            font-size: 1.15rem;
            font-weight: 700;
            color: #1e3a5f;
            letter-spacing: -0.01em;
        }

        #page-loader .pl-bar-track {
            width: 160px;
            height: 3px;
            background: #e2e8f0;
            border-radius: 99px;
            overflow: hidden;
        }

        #page-loader .pl-bar-fill {
            height: 100%;
            width: 40%;
            background: linear-gradient(90deg, #3b82f6, #6366f1);
            border-radius: 99px;
            animation: pl-slide 1.1s ease-in-out infinite;
        }

        @keyframes pl-slide {
            0% {
                transform: translateX(-100%);
            }

            50% {
                transform: translateX(150%);
            }

            100% {
                transform: translateX(350%);
            }
        }
    </style>
    <script>
        // Hide loader once all scripts at bottom have loaded (window.load)
        window.addEventListener('load', function () {
            var loader = document.getElementById('page-loader');
            if (loader) loader.classList.add('hide');
        });
        // Fallback: force hide after 4s no matter what
        setTimeout(function () {
            var loader = document.getElementById('page-loader');
            if (loader) loader.classList.add('hide');
        }, 4000);
    </script>

    <style>
        /*  Global Color Scheme */
        :root {
            --primary: #3b82f6;
            --primary-end: #6366f1;
            --dark: #0f172a;
            --secondary: #64748b;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --info: #06b6d4;
            --light: #f8fafc;
        }
    </style>

    <style>
        /* Calendar Container Modernization */
        #calendar {
            border: none !important;
            background: transparent !important;
            font-family: inherit;
            margin-bottom: 10px;
            /* Align left or keep auto for center */
            padding: 12px;
        }

        /* Modernize FullCalendar Buttons & Header */
        .fc .fc-button-primary {
            background-color: #0f172a !important;
            /* slate-900 */
            border: none !important;
            border-radius: 8px !important;
            text-transform: uppercase;
            font-size: 0.75rem !important;
            font-weight: 700 !important;
            padding: 8px 16px !important;
        }

        .fc .fc-toolbar-title {
            font-weight: 500 !important;
            color: #1e293b;
            /* slate-800 */
            letter-spacing: -0.025em;
        }

        .fc-theme-standard td,
        .fc-theme-standard th {
            border: 1px solid #f1f5f9 !important;
            /* slate-100 */
        }

        /* Event Tooltip Modernization */
        .event-tooltip {
            position: absolute;
            background: rgba(15, 23, 42, 0.9);
            backdrop-filter: blur(4px);
            color: #fff;
            padding: 8px 12px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            display: none;
            z-index: 9999;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }
    </style>
    <style type="text/tailwindcss">
        @layer components {
        .glass-header {
            @apply sticky top-0 z-[1020] transition-all duration-500 backdrop-blur-md bg-slate-900/90 border-b border-white/10;
        }
        /* Smaller card with light gray background */
        .bento-card {
            @apply relative bg-slate-200 border border-slate-200/60 rounded-2xl p-4 transition-all duration-500 
                   hover:shadow-[0_15px_30px_rgba(0,0,0,0.08)] hover:-translate-y-1 overflow-hidden;
        }
        .status-badge {
            @apply px-4 py-1 rounded-full text-xs font-bold uppercase tracking-wider;
        }
    }
</style>
    <?php
    // Extract the tab_id from the URL
    $tabSessionID = isset($_GET['tab_id']) ? htmlspecialchars($_GET['tab_id']) : '';
    ?>
    <script>
        // Store the tab_id from PHP to JavaScript
        const tabID = "<?php echo $tabSessionID; ?>";

        // Current session & term — used to auto-select dropdowns across all pages
        const CURRENT_SESSION_ID = <?php echo json_encode($_headCurrentSessionId); ?>;
        const CURRENT_SESSION_NAME = <?php echo json_encode($_headCurrentSessionName); ?>;
        const CURRENT_TERM_ID = <?php echo json_encode($_headCurrentTermId); ?>;
        const CURRENT_TERM_NAME = <?php echo json_encode($_headCurrentTermName); ?>;

        document.addEventListener("DOMContentLoaded", function () {

            // Append tab_id to all internal links
            document.querySelectorAll("a[href]:not([href^='http'])").forEach(link => {
                let url = new URL(link.href, window.location.origin);
                if (!url.searchParams.has("tab_id") && tabID) {
                    url.searchParams.set("tab_id", tabID);
                    link.href = url.toString();

                }
            });

            // Append tab_id to form actions
            document.querySelectorAll("form").forEach(form => {
                let action = new URL(form.action, window.location.origin);
                if (!action.searchParams.has("tab_id") && tabID) {
                    action.searchParams.set("tab_id", tabID);
                    form.action = action.toString();
                }
            });

            // Append tab_id to button clicks that trigger redirection
            document.querySelectorAll("button").forEach(button => {
                button.addEventListener("click", function (event) {
                    // Handle buttons inside forms
                    const form = button.closest('form');
                    if (form) {
                        let action = new URL(form.action, window.location.origin);
                        if (!action.searchParams.has("tab_id") && tabID) {
                            action.searchParams.set("tab_id", tabID);
                            form.action = action.toString();
                        }
                    }

                    // Handle buttons with inline redirections (location.href)
                    if (button.getAttribute("onclick")) {
                        let onclickCode = button.getAttribute("onclick").toString();
                        let match = onclickCode.match(/location\.href\s*=\s*['"](.*?)['"]/);
                        if (match) {
                            let url = new URL(match[1], window.location.origin);
                            if (!url.searchParams.has("tab_id") && tabID) {
                                url.searchParams.set("tab_id", tabID);
                                button.setAttribute("onclick", `location.href='${url.toString()}'`);
                            }
                        }
                    }
                });
            });
        });
    </script>
    <style>
        /* 2026 Header: Glassmorphism + Fluid Layout  */
        .content-header.premium-header {
            padding: 0.4rem 0 !important;
            margin: 0 !important;
            position: sticky;
            top: 0;
            z-index: 1030;
            background: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }

        .header-glass-card {
            background: rgba(255, 255, 255, 0.72);
            backdrop-filter: blur(16px) saturate(180%);
            -webkit-backdrop-filter: blur(16px) saturate(180%);
            border-radius: 16px;
            padding: 0.7rem 1.5rem;
            border: 1px solid rgba(255, 255, 255, 0.55);
            box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06), 0 1px 2px rgba(0, 0, 0, 0.04);
            transition: box-shadow 0.25s ease;
        }

        .header-glass-card:hover {
            box-shadow: 0 8px 32px rgba(59, 130, 246, 0.1), 0 1px 4px rgba(0, 0, 0, 0.05);
        }

        /* Desktop (768px+) */
        @media (min-width: 768px) {
            .title-section {
                display: flex;
                align-items: center;
                gap: 0.85rem;
            }

            .icon-box {
                width: 38px;
                height: 38px;
                border-radius: 10px;
                background: linear-gradient(135deg, var(--primary) 0%, var(--primary-end) 100%);
                display: flex;
                align-items: center;
                justify-content: center;
                color: #fff;
                font-size: 0.95rem;
                flex-shrink: 0;
                box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
            }

            .premium-title {
                font-size: 1.25rem;
                font-weight: 700;
                margin: 0;
                letter-spacing: -0.02em;
                background: linear-gradient(135deg, var(--dark), var(--primary));
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                background-clip: text;
                line-height: 1.2;
            }

            .premium-title .premium-subtitle {
                background: none;
                -webkit-background-clip: unset;
                -webkit-text-fill-color: unset;
                background-clip: unset;
            }

            .premium-subtitle {
                font-size: 0.7rem;
                font-weight: 500;
                color: #94a3b8;
                letter-spacing: 0.04em;
                text-transform: uppercase;
                display: block;
                margin-top: 1px;
            }

            .premium-breadcrumb {
                float: right;
                background: rgba(241, 245, 249, 0.8);
                padding: 4px 14px;
                border-radius: 999px;
                font-size: 0.78rem;
                color: #64748b;
            }

            .premium-breadcrumb .breadcrumb-item+.breadcrumb-item::before {
                color: #cbd5e1;
            }
        }

        /* Mobile (â‰¤767px) */
        @media (max-width: 767px) {
            .icon-box {
                display: none !important;
            }

            .header-glass-card {
                padding: 0.55rem 1rem !important;
                text-align: center;
                border-radius: 12px;
            }

            .premium-title {
                font-size: 1.05rem;
                font-weight: 700;
                display: block;
                margin: 0 auto;
                background: linear-gradient(135deg, var(--dark), var(--primary));
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                background-clip: text;
                letter-spacing: -0.01em;
            }

            .premium-subtitle {
                font-size: 0.62rem;
                display: block;
                margin-top: 2px;
                color: #94a3b8;
                text-transform: uppercase;
                letter-spacing: 0.05em;
            }

            .premium-breadcrumb {
                display: inline-flex;
                justify-content: center;
                margin-top: 0.45rem;
                padding: 3px 12px;
                font-size: 0.72rem;
                background: rgba(241, 245, 249, 0.9);
                border-radius: 999px;
                color: #64748b;
            }

            .row.mb-2 {
                margin-bottom: 0 !important;
            }
        }
    </style>
    <style>
        /*  Premium Button Styles (Global)  */
        .btn {
            display: inline-block !important;
            border-radius: 10px !important;
            font-weight: 600 !important;
            font-size: 0.82rem !important;
            letter-spacing: 0.02em !important;
            padding: 0.5rem 1.2rem !important;
            transition: all 0.2s ease !important;
            border: none !important;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08) !important;
        }

        .btn:hover {
            transform: translateY(-1px) !important;
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12) !important;
        }

        .btn:active {
            transform: translateY(0) !important;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1) !important;
        }

        /* Variant refinements */
        .btn-primary {
            background: linear-gradient(135deg, #1e3a5f 0%, var(--primary) 100%) !important;
            color: #fff !important;
            box-shadow: 0 4px 14px rgba(59, 130, 246, 0.4) !important;
        }

        .btn-primary:hover {
            box-shadow: 0 6px 20px rgba(59, 130, 246, 0.45) !important;
        }

        .btn-success {
            background: linear-gradient(135deg, #065f46 0%, var(--success) 100%) !important;
            color: #fff !important;
            box-shadow: 0 4px 14px rgba(16, 185, 129, 0.35) !important;
        }

        .btn-danger {
            background: linear-gradient(135deg, #7f1d1d 0%, var(--danger) 100%) !important;
            color: #fff !important;
            box-shadow: 0 4px 14px rgba(239, 68, 68, 0.4) !important;
        }

        .btn-warning {
            background: linear-gradient(135deg, #92400e 0%, var(--warning) 100%) !important;
            color: #fff !important;
            box-shadow: 0 4px 14px rgba(245, 158, 11, 0.35) !important;
        }

        .btn-secondary {
            background: linear-gradient(135deg, #1e293b 0%, var(--secondary) 100%) !important;
            color: #fff !important;
            box-shadow: 0 4px 14px rgba(100, 116, 139, 0.3) !important;
        }

        .btn-info {
            background: linear-gradient(135deg, #164e63 0%, var(--info) 100%) !important;
            color: #fff !important;
            box-shadow: 0 4px 14px rgba(6, 182, 212, 0.35) !important;
        }

        /* Small & large size adjustments */
        .btn-sm {
            padding: 0.35rem 0.85rem !important;
            font-size: 0.75rem !important;
            border-radius: 8px !important;
        }

        .btn-lg {
            padding: 0.7rem 1.8rem !important;
            font-size: 0.95rem !important;
            border-radius: 12px !important;
        }

        /* Premium Modal Styles (Global) */
        .modal-content {
            border-radius: 20px !important;
            border: 1px solid rgba(0, 0, 0, 0.06) !important;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15), 0 4px 16px rgba(0, 0, 0, 0.08) !important;
            overflow: hidden !important;
        }

        .modal-header {
            border-radius: 20px 20px 0 0 !important;
            border-bottom: 1px solid rgba(0, 0, 0, 0.06) !important;
            padding: 1.2rem 1.5rem !important;
            background-color: #fff !important;
        }

        .modal-title {
            font-weight: 700 !important;
            font-size: 1rem !important;
            color: #0f172a !important;
            letter-spacing: -0.01em !important;
        }

        .modal-body {
            padding: 1.5rem !important;
            background-color: #fff !important;
        }

        .modal-footer {
            border-radius: 0 0 20px 20px !important;
            border-top: 1px solid rgba(0, 0, 0, 0.06) !important;
            padding: 1rem 1.5rem !important;
            background-color: #f8fafc !important;
        }

        /* Close button */
        .modal-header .close,
        .modal-header .btn-close {
            opacity: 0.5 !important;
            transition: opacity 0.2s ease !important;
        }

        .modal-header .close:hover,
        .modal-header .btn-close:hover {
            opacity: 1 !important;
        }

        /* Backdrop blur */
        .modal-backdrop.show {
            backdrop-filter: blur(4px) !important;
            -webkit-backdrop-filter: blur(4px) !important;
            background-color: rgba(15, 23, 42, 0.5) !important;
            opacity: 1 !important;
        }

        /* Smooth entrance animation */
        .modal.fade .modal-dialog {
            transform: translateY(-16px) scale(0.98) !important;
            transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.2s ease !important;
        }

        .modal.show .modal-dialog {
            transform: translateY(0) scale(1) !important;
        }

        /*  Select2 Premium Override */
        .select2-container--default .select2-selection--single,
        .select2-container--default .select2-selection--multiple {
            border-radius: 10px !important;
            border: 1.5px solid #e2e8f0 !important;
            background-color: #f8fafc !important;
            min-height: 38px !important;
            padding: 0.15rem 0.4rem !important;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04) !important;
            transition: border-color 0.2s ease, box-shadow 0.2s ease !important;
        }

        .select2-container--default.select2-container--focus .select2-selection--single,
        .select2-container--default.select2-container--focus .select2-selection--multiple,
        .select2-container--default.select2-container--open .select2-selection--single,
        .select2-container--default.select2-container--open .select2-selection--multiple {
            border-color: var(--primary-end) !important;
            background-color: #fff !important;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.12) !important;
            outline: none !important;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            color: #1e293b !important;
            font-size: 0.875rem !important;
            line-height: 36px !important;
            padding-left: 6px !important;
        }

        .select2-container--default .select2-selection--single .select2-selection__placeholder {
            color: #94a3b8 !important;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 36px !important;
            right: 8px !important;
        }

        /* Dropdown panel */
        .select2-dropdown {
            border-radius: 12px !important;
            border: 1.5px solid #e2e8f0 !important;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1) !important;
            overflow: hidden !important;
            margin-top: 4px !important;
        }

        .select2-container--default .select2-results__option {
            font-size: 0.875rem !important;
            padding: 0.5rem 0.85rem !important;
            color: #334155 !important;
        }

        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: var(--primary-end) !important;
            color: #fff !important;
        }

        .select2-container--default .select2-results__option[aria-selected="true"] {
            background-color: #eef2ff !important;
            color: var(--primary-end) !important;
        }

        /* Search box inside dropdown */
        .select2-search--dropdown .select2-search__field {
            border-radius: 8px !important;
            border: 1.5px solid #e2e8f0 !important;
            padding: 0.4rem 0.7rem !important;
            font-size: 0.85rem !important;
            outline: none !important;
        }

        .select2-search--dropdown .select2-search__field:focus {
            border-color: #6366f1 !important;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1) !important;
        }

        /* Multiple select tags */
        .select2-container--default .select2-selection--multiple .select2-selection__choice {
            background-color: #eef2ff !important;
            border: 1px solid #c7d2fe !important;
            border-radius: 6px !important;
            color: #4f46e5 !important;
            font-size: 0.78rem !important;
            font-weight: 600 !important;
            padding: 2px 8px !important;
        }

        .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
            color: #6366f1 !important;
            margin-right: 4px !important;
        }

        /* Premium Form Elements (Global) */
        .form-control,
        .form-select,
        select,
        textarea,
        input[type="text"],
        input[type="email"],
        input[type="password"],
        input[type="number"],
        input[type="tel"],
        input[type="date"],
        input[type="time"],
        input[type="search"],
        input[type="url"],
        input[type="file"] {
            border-radius: 10px !important;
            border: 1.5px solid #e2e8f0 !important;
            background-color: #f8fafc !important;
            color: #1e293b !important;
            font-size: 0.875rem !important;
            padding: 0.55rem 0.9rem !important;
            transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease !important;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04) !important;
            outline: none !important;
        }

        .form-control:focus,
        .form-select:focus,
        select:focus,
        textarea:focus,
        input[type="text"]:focus,
        input[type="email"]:focus,
        input[type="password"]:focus,
        input[type="number"]:focus,
        input[type="tel"]:focus,
        input[type="date"]:focus,
        input[type="time"]:focus,
        input[type="search"]:focus,
        input[type="url"]:focus {
            border-color: var(--primary-end) !important;
            background-color: #fff !important;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.12) !important;
        }

        .form-control::placeholder,
        input::placeholder,
        textarea::placeholder {
            color: #94a3b8 !important;
            font-weight: 400 !important;
        }

        /* Labels */
        label,
        .form-label {
            font-size: 0.8rem !important;
            font-weight: 600 !important;
            color: #475569 !important;
            margin-bottom: 0.35rem !important;
            letter-spacing: 0.01em !important;
        }

        /* Select arrow refinement */
        select.form-control,
        select {
            appearance: auto !important;
            cursor: pointer !important;
        }

        /* Textarea */
        textarea.form-control,
        textarea {
            resize: vertical !important;
            min-height: 90px !important;
        }

        /* Input group */
        .input-group .form-control {
            border-radius: 10px !important;
        }

        .input-group-text {
            border-radius: 10px !important;
            border: 1.5px solid #e2e8f0 !important;
            background-color: #f1f5f9 !important;
            color: #64748b !important;
            font-size: 0.85rem !important;
        }

        .input-group>.form-control:not(:first-child),
        .input-group>.input-group-text:not(:first-child) {
            border-top-left-radius: 0 !important;
            border-bottom-left-radius: 0 !important;
        }

        .input-group>.form-control:not(:last-child),
        .input-group>.input-group-text:not(:last-child) {
            border-top-right-radius: 0 !important;
            border-bottom-right-radius: 0 !important;
        }

        /* Disabled state */
        .form-control:disabled,
        input:disabled,
        select:disabled,
        textarea:disabled {
            background-color: #f1f5f9 !important;
            color: #94a3b8 !important;
            cursor: not-allowed !important;
            opacity: 0.7 !important;
        }

        /* Form group spacing */
        .form-group {
            margin-bottom: 1.1rem !important;
        }

        /*  Premium Card Styles (Global)  */
        .card {
            border-radius: 16px !important;
            border: 1px solid rgba(0, 0, 0, 0.06) !important;
            box-shadow: 0 4px 24px rgba(0, 0, 0, 0.07), 0 1px 4px rgba(0, 0, 0, 0.04) !important;
        }

        .card .card-header {
            border-radius: 16px 16px 0 0 !important;
            border-bottom: 1px solid rgba(0, 0, 0, 0.06) !important;
            padding: 1rem 1.5rem !important;
            background: linear-gradient(135deg, var(--dark), var(--primary));

        }

        .card .card-footer {
            border-radius: 0 0 16px 16px !important;
            border-top: 1px solid rgba(0, 0, 0, 0.06) !important;
        }

        .card .card-body {
            padding: 1.5rem !important;
        }
    </style>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const loader = document.getElementById("loader");

            if (!loader) {
                console.error("âš ï¸ Loader element (#loader) not found!");
                return;
            }

            // Show the loader
            function showLoader() {
                loader.style.visibility = "visible";
                loader.style.opacity = "1";
                loader.style.transform = "translate(-50%, -50%) scale(1)";
            }

            // Hide the loader
            function hideLoader() {
                loader.style.opacity = "0";
                loader.style.transform = "translate(-50%, -50%) scale(0.9)";
                setTimeout(() => {
                    loader.style.visibility = "hidden";
                }, 300);
            }

            // Detect if button is for modal
            function isOpeningModal(element) {
                return element.classList.contains("edit_data") ||
                    element.classList.contains("edit_data2") ||
                    element.classList.contains("feedbackModal") ||
                    element.classList.contains("user") ||
                    element.classList.contains("btn-close") ||
                    element.classList.contains("viewResultBtn") ||
                    element.classList.contains("approve") ||
                    element.classList.contains("setDeadlineModal") ||
                    element.classList.contains("accNum") ||
                    element.classList.contains("viewModal");

            }

            // Loader for <a> tags
            document.querySelectorAll("a").forEach(link => {
                link.addEventListener("click", function () {
                    const href = link.getAttribute("href");

                    if (!href || href === "#" || href.endsWith("#")) return;

                    if (!link.target || link.target === "_self") {
                        showLoader();

                        setTimeout(() => {
                            // You should replace this with your real logic or AJAX call

                            hideLoader(); // hide loader manually
                        }, 2000);
                    }
                });
            });

            // Prevent calendar from triggering loader
            document.getElementById("calender")?.addEventListener("click", function (e) {
                e.stopPropagation();
            });

            // Loader for buttons
            document.querySelectorAll("button, input[type='submit'], input[type='button']").forEach(button => {
                button.addEventListener("click", function (e) {
                    if (isOpeningModal(button)) return;

                    showLoader();

                    // ðŸ‘‡ Example: Simulate action that completes in 1 second
                    setTimeout(() => {
                        // You should replace this with your real logic or AJAX call

                        hideLoader(); // hide loader manually
                    }, 2000);
                });
            });

            // Hide loader after full page load (for normal navigation)
            window.addEventListener("load", function () {
                hideLoader();
            });
        });
    </script>

    <!-- SweetAlert2: Global alert override -->
    <style>
        /* ── SweetAlert2 Portal Theme ── */
        .swal-portal-popup {
            border-radius: 24px !important;
            font-family: inherit !important;
            padding: 2rem 1.5rem 1.5rem !important;
            box-shadow: 0 25px 60px rgba(0, 0, 0, 0.15), 0 8px 24px rgba(0, 0, 0, 0.08) !important;
            border: 1px solid rgba(255, 255, 255, 0.6) !important;
        }

        .swal2-icon {
            margin: 0 auto 1rem !important;
            width: 64px !important;
            height: 64px !important;
        }

        .swal2-title {
            font-size: 1.15rem !important;
            font-weight: 700 !important;
            color: #0f172a !important;
            letter-spacing: -0.02em !important;
            margin-bottom: 0.4rem !important;
        }

        .swal2-html-container {
            font-size: 0.875rem !important;
            color: #64748b !important;
            line-height: 1.6 !important;
        }

        .swal2-confirm {
            background: linear-gradient(135deg, var(--primary), var(--primary-end)) !important;
            border-radius: 10px !important;
            font-weight: 600 !important;
            font-size: 0.85rem !important;
            padding: 0.55rem 1.8rem !important;
            box-shadow: 0 4px 14px rgba(99, 102, 241, 0.35) !important;
            border: none !important;
        }

        .swal2-cancel {
            border-radius: 10px !important;
            font-weight: 600 !important;
            font-size: 0.85rem !important;
            padding: 0.55rem 1.8rem !important;
            border: none !important;
        }

        .swal2-timer-progress-bar {
            background: linear-gradient(135deg, var(--primary), var(--primary-end)) !important;
        }

        /* Center popup overlay */
        .swal2-container {
            backdrop-filter: blur(4px) !important;
            -webkit-backdrop-filter: blur(4px) !important;
        }
    </style>

    <script>
        (function () {
            function detectType(msg) {
                if (/error|fail|wrong|invalid|missing|not found|denied|incorrect/i.test(msg)) return 'error';
                if (/success|added|updated|registered|sent|complete|admitted|assigned|reset|restored|promoted|demoted|deleted|saved/i.test(msg)) return 'success';
                if (/warning|already|exist|duplicate|cannot|unable/i.test(msg)) return 'warning';
                return 'info';
            }

            const TITLES = { success: 'Success', error: 'Error', warning: 'Warning', info: 'Info' };
            const COLORS = { success: '#10b981', error: '#ef4444', warning: '#f59e0b', info: '#3b82f6' };

            function portalAlert(msg, redirect) {
                msg = String(msg);
                const type = detectType(msg);
                return Swal.fire({
                    icon: type,
                    title: TITLES[type],
                    text: msg,
                    timer: type === 'success' || type === 'info' ? 5000 : undefined,
                    timerProgressBar: true,
                    showConfirmButton: true,
                    confirmButtonText: type === 'success' ? 'Great!' : 'OK',
                    customClass: { popup: 'swal-portal-popup' },
                    showClass: {
                        popup: 'animate__animated animate__fadeInDown animate__faster'
                    },
                    hideClass: {
                        popup: 'animate__animated animate__fadeOutUp animate__faster'
                    }
                }).then(function () {
                    if (redirect) window.location.href = redirect;
                });
            }

            // Override window.alert for any remaining inline calls
            window.alert = function (msg) { portalAlert(msg); };

            window._portalAlert = portalAlert;

            // ── Global confirm() interceptor ──────────────────────────────
            document.addEventListener('click', function (e) {
                var el = e.target.closest('[onclick]');
                if (!el) return;

                var onclickAttr = el.getAttribute('onclick') || '';
                var match = onclickAttr.match(/return\s+confirm\s*\(\s*['"](.+?)['"]\s*\)/);
                if (!match) return;

                e.preventDefault();
                e.stopImmediatePropagation();

                var msg = match[1];
                var href = el.getAttribute('href');
                var form = el.closest('form');
                var tag = el.tagName;

                Swal.fire({
                    icon: 'warning',
                    title: 'Are you sure?',
                    text: msg,
                    showCancelButton: true,
                    confirmButtonColor: 'var(--danger)',
                    cancelButtonColor: 'var(--secondary)',
                    confirmButtonText: 'Yes, proceed',
                    cancelButtonText: 'Cancel',
                    customClass: { popup: 'swal-portal-popup' }
                }).then(function (result) {
                    if (!result.isConfirmed) return;
                    if (href && href !== '#' && href !== 'javascript:void(0)') {
                        window.location.href = href;
                    } else if (form) {
                        // Remove onclick first to avoid re-triggering, then submit
                        el.removeAttribute('onclick');
                        form.submit();
                    }
                });
            }, true);
        })();
    </script>

    <!-- Modal form AJAX handler -->
    <script>
        document.addEventListener('DOMContentLoaded', function () {

            // When modal content loads via AJAX, stamp each form with the source URL
            $(document).on('click', '.edit_data, .edit_data2, .feedbackModal, .viewModal', function () {
                var $btn = $(this);
                // Find which modal this button targets
                setTimeout(function () {
                    var $modal = $('.modal.show, .modal.in').first();
                    var src = $btn.closest('[data-ajax-url]').data('ajax-url') ||
                        $modal.data('ajax-src');
                    if (src) {
                        $modal.find('form:not([action])').attr('data-ajax-action', src);
                    }
                }, 300);
            });

            // Track the last clicked submit button inside modals
            var _lastModalSubmitBtn = null;
            $(document).on('click', '.modal form [type="submit"]', function () {
                _lastModalSubmitBtn = this;
            });

            $(document).on('submit', '.modal form', function (e) {
                var $form = $(this);
                if ($form.data('no-ajax') !== undefined) return;
                if (this.checkValidity && !this.checkValidity()) return;

                var action = $form.attr('action');
                if (!action || action === '' || action === window.location.href || action === window.location.pathname) {
                    action = $form.attr('data-ajax-action') ||
                        $form.closest('.modal').data('ajax-src') ||
                        null;
                }
                if (!action) return;

                e.preventDefault();
                var $modal = $form.closest('.modal');

                // Build FormData and include the submit button name/value
                var fd = new FormData(this);
                if (_lastModalSubmitBtn && _lastModalSubmitBtn.name) {
                    fd.append(_lastModalSubmitBtn.name, _lastModalSubmitBtn.value || '1');
                }
                _lastModalSubmitBtn = null;
                fd.append('is_ajax', '1');

                $.ajax({
                    url: action,
                    type: $form.attr('method') || 'POST',
                    data: fd,
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        // If JSON response, handle success/error and close modal
                        if (typeof response === 'object' || (typeof response === 'string' && response.trim().charAt(0) === '{')) {
                            try {
                                var res = (typeof response === 'object') ? response : JSON.parse(response);
                                $modal.modal('hide');
                                if (res.success) {
                                    if (typeof Swal !== 'undefined') {
                                        Swal.fire({ icon: 'success', title: 'Updated!', text: 'Record updated successfully.', timer: 2500, showConfirmButton: false, customClass: { popup: 'swal-portal-popup' } });
                                    }
                                } else {
                                    if (typeof Swal !== 'undefined') {
                                        Swal.fire({ icon: 'error', title: 'Error', text: 'Something went wrong, please try again.', customClass: { popup: 'swal-portal-popup' } });
                                    }
                                }
                                return;
                            } catch (e) { /* fall through to HTML handling */ }
                        }

                        var pendingRedirect = null;
                        var alertMsg = null;
                        response.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function (m, code) {
                            var aMatch = code.match(/alert\s*\(\s*['"](.+?)['"]\s*\)/);
                            if (aMatch) alertMsg = aMatch[1];
                            var rMatch = code.match(/window\.location\.href\s*=\s*['"]([^'"]+)['"]/) ||
                                code.match(/document\.location\.href\s*=\s*['"]([^'"]+)['"]/) ||
                                code.match(/window\.location\s*=\s*['"]([^'"]+)['"]/);
                            if (rMatch) pendingRedirect = rMatch[1];
                        });

                        $modal.modal('hide');

                        if (alertMsg) {
                            window._portalAlert(alertMsg, pendingRedirect || '');
                        } else if (pendingRedirect) {
                            window.location.href = pendingRedirect;
                        }
                    },
                    error: function (xhr, status, err) {
                        window._portalAlert('Update failed. Please try again.');
                    }
                });
            });
        });
    </script>

    <?php if (!empty($_SESSION['_flash_alerts'])): ?>
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                var _flashAlerts = <?php echo json_encode($_SESSION['_flash_alerts']); ?>;
                <?php $_SESSION['_flash_alerts'] = []; ?>

                function runNext(index) {
                    if (index >= _flashAlerts.length) return;
                    var item = _flashAlerts[index];
                    window._portalAlert(item.msg, item.redirect || '').then(function () {
                        runNext(index + 1);
                    });
                }

                runNext(0);
            });
        </script>
    <?php endif; ?>
</head>