<?php
session_name('small_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/small')) { mkdir(dirname(__DIR__) . '/session_data/small', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/small');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
include('includes/dbconnection.php');
require_once 'includes/wallet_helpers.php';
$payments_enabled = (int)getWalletSetting($con, 'payments_enabled', 1);
$transfers_enabled = (int)getWalletSetting($con, 'transfers_enabled', 1);
if (!isset($_SESSION['sid']) || strlen($_SESSION['sid']) == 0) {
    header('location:logoutsmall.php');
    exit();
}

if (!isset($_SESSION['permission']) || $_SESSION['permission'] !== 'Student Search') {
    header('location:logoutsmall.php');
    exit();
}
$admin = $_SESSION['sid'];

$sql = "SELECT * FROM tblusers WHERE id = ?";
$stmt = $dbh->prepare($sql);
$stmt->execute([$admin]);

if ($stmt->rowCount() > 0) {
    $fecthemail = $stmt->fetch(PDO::FETCH_ASSOC);
    $request = $fecthemail['id'];
}



$id = $_SESSION['sid'];

// Get admin details
$sql1 = "SELECT * FROM tblusers WHERE id = '$id'";
$result = mysqli_query($con, $sql1);
$row = mysqli_fetch_assoc($result);

// Assign variables
$status     = isset($row['status']) ? (int)$row['status'] : 0;
$firstname  = $row['name'] ?? '';
$lastname   = $row['lastname'] ?? '';
$permission = $row['permission'] ?? '';
$userimage  = !empty($row['userimage']) && file_exists("staff_images/".$row['userimage'])
                ? "staff_images/" . htmlspecialchars($row['userimage'])
                : "default.png";
?>
<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>


<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php @include("includes/header3.php"); ?>
        <?php @include("includes/sidebar3.php"); ?>
        
        <div class="content-wrapper">

<!-- Admin Header -->
<div id="pageHeader" 
     class="content-header py-4 rounded shadow-sm mb-4 sticky-top" 
     style="background: linear-gradient(135deg, var(--dark), var(--primary)); color: #fff; z-index: 1020; transition: all 0.3s ease;">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center flex-wrap">
            
            <!-- Profile & Welcome -->
            <div class="d-flex align-items-center mb-2 mb-md-0">
                <div style="width:60px; height:60px; border-radius:50%; overflow:hidden; background:#fff; display:flex; align-items:center; justify-content:center; margin-right:15px; transition: all 0.3s ease;">
                    <?php if ($userimage !== "default.png"): ?>
                        <img src="<?php echo $userimage; ?>" 
                             alt="Admin Picture" 
                             style="width:100%; height:100%; object-fit:cover;" 
                             class="img-circle img-fluid">
                    <?php else: ?>
                        <i class="fas fa-user-circle" style="font-size:60px; color:var(--primary);"></i>
                    <?php endif; ?>
                </div>
                <div>
                    <h4 class="mb-1 fw-bold" style="transition: all 0.3s ease;">
                        <?php echo htmlspecialchars($firstname . ' ' . $lastname); ?>,
                    </h4>
                    <h6 class="mb-0">Welcome to your dashboard</h6>
                    <small style="opacity:0.9;">Manage students, teachers, feedback and more.</small>
                </div>
            </div>  

<!-- Admin Status -->
<div>
    <h6 class="fw-bold mb-2 student-status-heading">Admin Status</h6>
    <?php 
        $admissionStatusOptions = [
            2 => ['text' => 'Active', 'class' => 'bg-success'],
            1 => ['text' => 'Active', 'class' => 'bg-success'],
        ];
        $admissionStatus = $admissionStatusOptions[$status] ?? ['text' => 'Unknown', 'class' => 'bg-secondary'];
    ?>
    <div>
        <span class="badge <?= $admissionStatus['class']; ?> d-block p-2" style="font-size:1rem;">
            <?= htmlspecialchars($admissionStatus['text']); ?>
        </span>
    </div>
</div>

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

<style>
    .student-status-heading {
        position: relative;
        display: inline-block;
        color: #fff;
        padding-bottom: 4px;
    }
    .student-status-heading::after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        height: 2px;
        width: 0;
        background-color: rgba(255,255,255,0.3);
        transition: width 0.6s ease-in-out;
    }
    body.loaded .student-status-heading::after {
        width: 100%;
    }
</style>

<script>
    window.addEventListener("load", function() {
        document.body.classList.add("loaded");
    });

    // Shrink header on scroll
    window.addEventListener('scroll', function() {
        let header = document.getElementById('pageHeader');
        let profilePic = header.querySelector("div[style*='width:60px']");
        let nameTag = header.querySelector("h4");

        if (window.scrollY > 50) {
            header.style.padding = "0.5rem 0";
            profilePic.style.width = "40px";
            profilePic.style.height = "40px";
            nameTag.style.fontSize = "1rem";
        } else {
            header.style.padding = "1rem 0";
            profilePic.style.width = "60px";
            profilePic.style.height = "60px";
            nameTag.style.fontSize = "1.25rem";
        }
    });
</script>

            <!-- Main Content -->
            <section class="content px-6">
                <div class="container-fluid">
                    
                    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-4 mb-10">
                        <?php
    $dashboard_items = [
        // Students
        ["query" => "SELECT * FROM students WHERE status =1", "label" => "FULLY ENROLLED", "icon" => "fas fa-user-graduate", "bg" => "bg-info", "link" => "student_list11.php", "id" => "admittedStudents", "class" => "text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter"],
        ["query" => "SELECT * FROM students WHERE status IN (2, 4)", "label" => "PROVISIONAL STUDENTS", "icon" => "fas fa-users", "bg" => "bg-primary", "link" => "studentlist11.php", "class" => "text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter", "id" => "registeredStudents"],
        ["query" => "SELECT * FROM tblusers WHERE status =2 AND name !='Developer' AND lastname !='Account' AND username !='Developer'", "label" => "ACTIVE TEACHER", "icon" => "fas fa-user-tie", "bg" => "bg-success", "link" => "teacher_list11.php", "id" => "activeTeachers", "class" => "text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter"],
        ["query" => null, "label" => "TRANSACTIONS HISTORY", "icon" => "fas fa-receipt", "bg" => "bg-warning", "link" => "transaction_history.php", "id" => "transactionHistory", "class" => "text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter", "display_text" => "TRANSACTIONS"],
        ["query" => null, "label" => "PAY STUDENT FEE", "icon" => "fas fa-money-bill-wave", "bg" => "bg-purple", "link" => "small_wallet_pay_fee.php", "id" => "payStudentFeeBtn", "class" => "text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter", "display_text" => "PAY FEE", "disabled" => !$payments_enabled],
        ["query" => null, "label" => "TRANSFER FUNDS", "icon" => "fas fa-exchange-alt", "bg" => "bg-teal", "link" => "small_transfer_funds.php", "id" => "transferFundsBtn", "class" => "text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter", "display_text" => "TRANSFER", "disabled" => !$transfers_enabled],
        ["query" => null, "label" => "GENERATE WALLET", "icon" => "fas fa-university", "bg" => "bg-indigo", "link" => "small_generate_wallet.php", "id" => "generateWalletBtn", "class" => "text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter", "display_text" => "WALLET"],
        ["query" => null, "label" => "FEEDBACK", "desc" => "Provide Your Feedback", "icon" => "fas fa-comments", "bg" => "bg-danger", "link" => "#", "id" => "feedbackBtn","class" => "text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter feedbackModal", "display_text" => "FEEDBACK"],
        ];





                        $styleMap = [
                            "bg-primary"   => ["bg" => "bg-blue-50", "text" => "text-blue-600"],
                            "bg-success"   => ["bg" => "bg-emerald-50", "text" => "text-emerald-600"],
                            "bg-warning"   => ["bg" => "bg-orange-50", "text" => "text-orange-600"],
                            "bg-info"      => ["bg" => "bg-cyan-50", "text" => "text-cyan-600"],
                            "bg-danger"    => ["bg" => "bg-rose-50", "text" => "text-rose-600"],
                            "bg-secondary" => ["bg" => "bg-slate-50", "text" => "text-slate-600"],
                            "bg-purple"    => ["bg" => "bg-purple-50", "text" => "text-purple-600"],
                            "bg-teal"      => ["bg" => "bg-teal-50",   "text" => "text-teal-600"],
                            "bg-indigo"    => ["bg" => "bg-indigo-50", "text" => "text-indigo-600"],
                        ];

foreach ($dashboard_items as $item) {

    $count = null;

    if (!empty($item['query'])) {
        $res = mysqli_query($con, $item['query']);
        if ($res) {
            $count = mysqli_num_rows($res);
        }
    }

    $st = $styleMap[$item['bg']] ?? $styleMap["bg-secondary"];
?>
    <div class="bento-card group">
        <div class="flex justify-between items-start mb-3">
            <div class="w-10 h-10 <?php echo $st['bg']; ?> <?php echo $st['text']; ?> rounded-xl flex items-center justify-center text-base group-hover:scale-110 transition-transform">
                <i class="<?php echo $item['icon']; ?>"></i>
            </div>
            <a href="<?php echo $item['link']; ?>" class="<?php echo $item['class']; ?><?php echo ($item['disabled'] ?? false) ? ' opacity-50 pointer-events-none' : ''; ?>" id="<?php echo $item['id']; ?>"<?php echo ($item['disabled'] ?? false) ? ' title="Currently disabled by administrator"' : ''; ?>>
                <i class="fas fa-arrow-right"></i> CLICK HERE
            </a>
        </div>

        <h2 class="text-2xl font-black text-slate-800 tracking-tight">
            <?php
                echo $count !== null
                    ? number_format($count)
                    : strtoupper($item['display_text']);
            ?>
        </h2>

        <p class="text-[10px] font-bold text-slate-500 uppercase tracking-tight truncate">
            <?php echo $item['label']; ?>
        </p>

        <div class="mt-4 w-full h-1 bg-slate-200/50 rounded-full overflow-hidden">
            <div class="h-full <?php echo str_replace('text-', 'bg-', $st['text']); ?> opacity-40 w-full transform -translate-x-1/2 group-hover:translate-x-0 transition-transform duration-1000"></div>
        </div>
    </div>
<?php } ?>
</div>

                    <div class="mt-12">
                        <hr>
                         <h5 class="text-lg font-black text-slate-600 mb-6 flex items-center">
                            <span class="w-8 h-8 bg-white shadow-sm rounded-lg flex items-center justify-center mr-3 text-sm">📅</span>
                            School Calendar
                         </h5>
                         <hr>
                         <div id="calendar" class="bg-white p-6 rounded-3xl border border-slate-100 shadow-sm mb-8"></div>
                         

                    </div>

                </div>
            </section>

                <!-- Feedback Modal -->
        <div id="feedbackModal" class="modal-custom" role="dialog" aria-labelledby="feedbackModalLabel" aria-describedby="feedbackModalDesc">
            <div class="modal-dialog-custom">
                <div class="modal-content-custom">
                    <h4 id="feedbackModalLabel" class="text-center mb-4">Feedback Form</h4>
                    <form id="feedbackForm" action="includes/submit_feedback.php" method="post" enctype="multipart/form-data">
                        <div class="row">
                            <div class="form-group col-12 col-md-6">
                                <label for="name">Name:</label>
                                <input type="text" class="form-control" id="name" name="name" placeholder="Your Name" required>
                            </div>
                            <div class="form-group col-12 col-md-6">
                                <label for="email">Email:</label>
                                <input type="email" class="form-control" id="email" name="email" placeholder="Your Email" required>
                            </div>
                            <div class="form-group col-12 col-md-6">
                                <label for="stdname">Student's Name:</label>
                                <input type="text" class="form-control" id="stdname" name="stdname" placeholder="Student's Name" required>
                            </div>
                            <div class="form-group col-12 col-md-6">
                                <label for="adno">Student's Class:</label>
                                <input type="text" class="form-control" id="adno" name="adno" placeholder="Student's Class" required>
                            </div>
                            <div class="form-group col-12 col-md-6">
                                <label for="message">Message:</label>
                                <textarea class="form-control" id="message" name="message" placeholder="Your Feedback" rows="4" required></textarea>
                                              <!-- Honeypot Field (Hidden from humans) -->
              <input type="text" name="honeypot" id="honeypot" style="display:none;" autocomplete="off">
                            </div>
                            <div class="form-group col-12 col-md-6">
                                <label for="file">Attach File (optional):</label>
                                <input type="file" class="form-control-file" id="file" name="file" accept=".jpg,.jpeg,.png,.pdf,.doc,.docx">
                            </div>

                        </div>

                        <div class="text-center mt-4">
                            <button type="submit" class="btn btn-primary">Submit</button>
                            <button id="closeModal" type="button" class="btn btn-danger approve">Close</button>
                        </div>
                    </form>

                    <div id="responseMessage" class="mt-3"></div>
                    <div id="verifiedMessage" class="mt-3 text-success" style="display: none;">
                        <i class="fas fa-check-circle verified-icon"></i> Feedback Submitted. Thank you!
                    </div>
                </div>
            </div>
        </div>



        <script>
            // Modal Logic
            const feedbackModal = document.getElementById('feedbackModal');
            const feedbackBtn = document.getElementById('feedbackBtn');
            const closeModal = document.getElementById('closeModal');
            const responseMessage = document.getElementById('responseMessage');
            const verifiedMessage = document.getElementById('verifiedMessage');

            feedbackBtn.addEventListener('click', () => {
                feedbackModal.style.display = 'flex';
            });

            closeModal.addEventListener('click', () => {
                feedbackModal.style.display = 'none';
            });

            window.addEventListener('click', (event) => {
                if (event.target === feedbackModal) {
                    feedbackModal.style.display = 'none';
                }
            });

            document.addEventListener('keydown', (event) => {
                if (event.key === 'Escape') {
                    feedbackModal.style.display = 'none';
                }
            });

            document.getElementById('feedbackForm').addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(this);
                const xhr = new XMLHttpRequest();
                xhr.open('POST', 'includes/submit_feedback.php', true);

                xhr.onload = function() {
                    if (xhr.status === 200) {
                        const response = JSON.parse(xhr.responseText);
                        responseMessage.style.display = 'block';
                        responseMessage.textContent = response.message;
                        document.getElementById('feedbackForm').style.display = 'none';
                        verifiedMessage.style.display = 'block';
                        setTimeout(() => {
                            feedbackModal.style.display = 'none';
                        }, 5000);
                    } else {
                        responseMessage.style.display = 'block';
                        responseMessage.textContent = 'An error occurred. Please try again.';
                    }
                };
                xhr.send(formData);
            });
        </script>
</div>


        <!-- Footer -->
        <?php @include("includes/footer.php"); ?>
    </div>

    <!-- Scripts -->
    <?php @include("includes/foot.php"); ?>
</body>
</html>
