<?php
chdir('../');
ob_start();
?>

<?php
require_once("public/connection.php");
require_once("public/functions.php");
?>

<?php
session_start();

// If both staff and student are set, deny access
if (isset($_SESSION['staff']) && isset($_SESSION['student'])) {
    unset($_SESSION['staff']);
	unset($_SESSION['student']);
	$_SESSION['login_msg'] = "Session conflict detected. Please log in again.";
	$_SESSION['alert_type'] = "error";
	header("Location: ../");
	exit();

}

// If neither is set, redirect to login
if (!isset($_SESSION['staff']) && !isset($_SESSION['student'])) {
    header("Location: ../");
    exit();
}
?>

<?php
if (isset($_SESSION['staff'])) {
    $staff_id = $_SESSION['staff'];

    $query = "
        SELECT staff.*, role.role_name 
        FROM staff 
        JOIN role ON staff.role = role.id 
        WHERE staff.id = ?
    ";
    $stmt = $connection->prepare($query);
    $stmt->bind_param("i", $staff_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows === 1) {
        $staff = $result->fetch_assoc();

        $staff_id = $staff['id'];
        $passport = "./" . $staff['passport'];
//        $passport = "https://cps.net.ng/" . $staff['passport'];
        $staff_username = ucwords($staff['username']);
        $full_name = ucwords($staff['name']);
        $role_id = $staff['role'];
        $role = $staff['role_name'];
        $staff_address = ucwords($staff['address']);
        $staff_phone = $staff['phone'];
        $staff_state = ucwords($staff['state']);
        $staff_lga = ucwords($staff['lga']);
        $staff_nationality = ucwords($staff['country']);
        $staff_email = $staff['email'];
        $staff_gender = ucfirst($staff['sex']);

        $msg_fullname = $full_name;
        $msg_title = ($staff_gender === "Male") ? "Mr" : (($staff_gender === "Female") ? "Ms" : "");
    }

    $stmt->close();
}
?>

<?php
if (isset($_SESSION['student'])) {
    $student_id = $_SESSION['student'];

    $query = "
        SELECT students.*, role.role_name 
        FROM students 
        JOIN role ON students.role = role.id 
        WHERE students.id = ?
    ";
    $stmt = $connection->prepare($query);
    $stmt->bind_param("i", $student_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows === 1) {
        $student = $result->fetch_assoc();

        $student_gender = ucfirst($student['gender']);
        $surname = ucfirst($student['firstname']);
        $lastname = ucfirst($student['lastname']);
        $othername = ucfirst($student['othername']);
        $student_class = $student['class'];
        $student_reg_number = $student['reg_number'];
        $student_dob = $student['dob'];
        $weight = $student['weight'];
        $height = $student['height'];
        $club = $student['club'];
        $health_conditions = $student['health_conditions'];
        $student_address = ucwords($student['address']);
        $student_state = ucwords($student['state']);
        $student_lga = ucwords($student['lga']);
        $student_level = ucwords($student['level']);
        $student_nationality = ucwords($student['nationality']);
        $guardian_name = $student['guardian_name'];
        $guardian_occupation = $student['guardian_occupation'];
        $guardian_phone = $student['guardian_phone'];
       $passport = "./" . $student['passport'];
//          $passport = 'https://cps.net.ng/portal/pages/'. $student['passport'];
        $student_reg_date = $student['date_of_reg'];        
        $current_year = date('Y');
        $student_yob = date('Y', strtotime($student_dob));
        $student_age = $current_year - $student_yob;
        $full_name = $surname . " " . $othername . " " . $lastname;
        

        // Role info (new)
        $role_id = $student['role'];
        $role = $student['role_name']; // e.g. "Student"
    }

    $stmt->close();
}
?>



<?php
//////////////// DEFAULT NULL VALUES ///////////////
date_default_timezone_set('Africa/Lagos');
$date = date('d-M-Y');
$select = "--select--";
$oge = time();
$time = date('H:i:s', $oge);
$error = array();
$year = date('Y');
?>

<?php
////////// POST ACTION TO VIEW ALL THE UPLOADED ADMINISTRATIVE INFORMATION ////////////
$query = " SELECT * FROM `administratives` ";
$run_query = mysqli_query($connection, $query);

if (mysqli_num_rows($run_query) > 0) {
    while ($result = mysqli_fetch_assoc($run_query)) {
        $administratives_id = $result['id'];
        $school_name = $result['school_name'];
        $school_motto = $result['school_motto'];
        $school_logo = $result['school_logo'];
        $school_address = $result['school_address'];
        $school_phone = $result['school_phone'];
        $school_mail = $result['school_mail'];
        $school_website = $result['school_website'];
        $school_whatsapp = $result['school_whatsapp'];
        $school_short_name = $result['school_short_name'];
        $school_favicon = $result['school_favicon'];
        $school_initial = $result['adm_no_initials'];
        $school_stamp = $result['school_stamp'];
    }
}
?>
<?php
$query = " SELECT * FROM `current_season` ";
$run_query = mysqli_query($connection, $query);
if (mysqli_num_rows($run_query) == 1) {
    while ($result = mysqli_fetch_assoc($run_query)) {
        $current_term = $result['current_term'];
        $current_session = $result['current_session'];
    }
}
?>
<?php
$permitted_pages = [];
$student_pages = [];
$role_id = $_SESSION['role'];
$is_super_admin = false;

// Step 1: Get the current role name
$role_stmt = $connection->prepare("SELECT role_name FROM role WHERE id = ?");
$role_stmt->bind_param("i", $role_id);
$role_stmt->execute();
$role_result = $role_stmt->get_result();

$role_name = '';
if ($role_row = $role_result->fetch_assoc()) {
    $role_name = strtolower($role_row['role_name']);
    $is_super_admin = $role_name === '';
}
$role_stmt->close();

// Step 2: Get all permitted pages for the current user's role
$stmt = $connection->prepare("
    SELECT permissions.permission_name FROM role_permissions 
    JOIN permissions ON role_permissions.permission_id = permissions.id 
    WHERE role_permissions.role_id = ?
");
$stmt->bind_param("i", $role_id);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    $permitted_pages[] = $row['permission_name'];
}
$stmt->close();

// Step 3: Get all pages assigned to the 'student' role (independent of current user)
$student_stmt = $connection->prepare("
    SELECT permissions.permission_name FROM role_permissions
    JOIN permissions ON role_permissions.permission_id = permissions.id
    JOIN role ON role_permissions.role_id = role.id
    WHERE LOWER(role.role_name) = 'student'
");
$student_stmt->execute();
$student_result = $student_stmt->get_result();

while ($row = $student_result->fetch_assoc()) {
    $student_pages[] = $row['permission_name'];
}
$student_stmt->close();

// Step 4: Control sidebar rendering
function showIfPermitted($page, $html) {
    global $permitted_pages, $is_super_admin, $student_pages;

    // Allow everyone to see 'dashboard' and 'index'
    if ($page === 'dashboard' || $page === 'index') {
        return $html;
    }

    // Super Admins should NOT see student-only pages
    if ($is_super_admin && in_array($page, $student_pages)) {
        return '';
    }

    // Show if Super Admin or user has this permission
    return $is_super_admin || in_array($page, $permitted_pages) ? $html : '';
}
?>


<!DOCTYPE html>
<html>

<head>
    <meta charset='utf-8'>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <!-- CSS-->
    <link rel='stylesheet' href='../assets/css/table.css'>
    <link rel='stylesheet' href='../assets/css/main.css'>
    <link rel="icon" href="../<?php echo $school_favicon; ?>" type="image/png">
    <link rel="stylesheet" href="../assets/vendor/loader/loader.css">
    <!-- Font-icon css and simple line icon-->
    <link rel="stylesheet" href="../assets/vendor/font-awesome/css/all.min.css">
    <link rel='stylesheet' href='../assets/vendor/simple-line-icons/css/simple-line-icons.css'>
    <link rel="stylesheet" href="../assets/vendor/datatables/media/css/dataTables.bootstrap.min.css">
	<link rel="stylesheet" href="../assets/vendor/select2/css/select2.css">
	<link rel="stylesheet" href="../assets/vendor/select2-bootstrap-theme/select2-bootstrap.min.css">
	<link rel="stylesheet" href="../assets/vendor/bootstrap-datepicker/css/bootstrap-datepicker3.min.css">
    <!-- Date picker and sweet_alert --> 
    <link href="../assets/SweetAlerts/sweetalert.css" rel="stylesheet">
    <link href="../assets/Datepicker/bootstrap-datepicker.min.css" rel="stylesheet">

    
    

    <title><?php echo $full_name; ?> ~ <?php echo $school_short_name; ?></title>
    <script src="../assets/js/jquery-2.1.4.min.js"></script>
    <script type="text/javascript">
        $(function() {
            // add multiple select / deselect functionality
            $("#selectall").click(function() {
                $('.subgroup').attr('checked', this.checked);
            });
            // if all checkbox are selected, then check the select all checkbox
            // and viceversa
            $(".subgroup").click(function() {
                if ($(".subgroup").length == $(".subgroup:checked").length) {
                    $("#selectall").attr("checked", "checked");
                } else {
                    $("#selectall").removeAttr("checked");
                }
            });
        });
    </script>
    <script type="text/javascript">
        window.onload = initClock;

        function initClock() {
            var now = new Date();
            var hr = now.getHours();
            var min = now.getMinutes();
            var sec = now.getSeconds();
            if (min < 10) min = "0" + min; // insert a leading zero
            if (sec < 10) sec = "0" + sec;
            document.getElementById('clockDisplay').innerHTML = hr + ":" + min + ":" + sec;
            setTimeout('initClock()', 500);
        }
    </script>
    <style type="text/css">
        .print_div {
            /*width: 21cm;
        min-height: 29.7cm;
        padding: 2cm;
        margin: 1cm auto;
        border: 1px #D3D3D3 solid;
        border-radius: 5px;
        background: white;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);*/
        }

        @page {
            size: A4;
            margin: 0;
        }

        @media print {
            .print_div {
                margin: 0;
                margin-top: -20%;
                padding-right: 4%;
                padding-left: 4%;
                border: 0;
                font-size: 12px;
                border-radius: 5px;
                /*width: 21cm;*/
                /*min-height: 29.7cm;*/
                box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
                background: white;
                page-break-after: always;
            }

            table.table-bordered {
                border: 2px solid #dee2e6;
                /* Light gray border for the table */
            }

            table.table-bordered th,
            table.table-bordered td {
                border: 1px solid #dee2e6;
                /* Borders around cells */
            }
            
            
    </style>
        <style>
        /* WhatsApp Floating Button */
        .whatsapp-button {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background-color: #25D366;
            color: white;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 28px;
            cursor: pointer;
            box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            transition: background 0.3s ease;
        }

        .whatsapp-button:hover {
            background-color: #1ebd5a;
        }

        /* Chat Box */
        .chat-box {
            position: fixed;
            bottom: 90px;
            right: 20px;
            width: 300px;
            background: white;
            border-radius: 10px;
            box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
            display: none;
            flex-direction: column;
            overflow: hidden;
        }

        /* Chat Header */
        .chat-header {
            background: #25D366;
            color: white;
            padding: 10px;
            text-align: center;
            font-weight: bold;
            font-size: 16px;
            position: relative;
        }

        .close-btn {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: white;
            font-size: 18px;
            cursor: pointer;
        }

        /* Chat Messages */
        .chat-body {
            padding: 10px;
            height: 200px;
            overflow-y: auto;
            background: #f5f5f5;
        }

        .chat-message {
            background: #DCF8C6;
            padding: 8px;
            border-radius: 5px;
            margin: 5px 0;
            font-size: 14px;
            width: fit-content;
            max-width: 80%;
        }

        /* Chat Input Area */
        .chat-footer {
            display: flex;
            align-items: center;
            padding: 5px;
            background: white;
            border-top: 1px solid #ddd;
        }

        .chat-footer input {
            flex: 1;
            padding: 8px;
            border: none;
            outline: none;
            font-size: 14px;
            border-radius: 5px;
            background: #f0f0f0;
        }

        .chat-footer button {
            background: #25D366;
            color: white;
            border: none;
            padding: 8px 12px;
            font-size: 16px;
            margin-left: 5px;
            cursor: pointer;
            border-radius: 5px;
        }

        .chat-footer button:hover {
            background: #1ebd5a;
        }

        /* Responsive Design */
        @media (max-width: 400px) {
            .chat-box {
                width: 90%;
                right: 5%;
            }
        }
    </style>
</head>

<body class='sidebar-mini fixed'>
    <div class='wrapper'>
        <!-- Navbar-->
        <header class='main-header hidden-print'><a class='logo' href='#'><?php echo $school_short_name; ?></a>
            <nav class='navbar navbar-static-top'>
                <!-- Sidebar toggle button-->
                <a class='sidebar-toggle' href='#' data-toggle='offcanvas'></a>
                <!-- Navbar Right Menu-->
                <div class='navbar-custom-menu'>
                    <ul class='top-nav'>
                        <!--Notification Menu-->

                        <!-- User Menu-->

                    <!-- User Menu-->
                        <li class='dropdown'><a class='dropdown-toggle' href='#' data-toggle='dropdown' role='button' aria-haspopup='true' aria-expanded='false'><img class="img-circle" 
     src="../<?php echo htmlspecialchars($passport); ?>" 
     width="31" 
     alt="User Photo" 
     onerror="this.onerror=null; this.src='../uploads/students/none.jpg';">
</a>

                            <ul class='dropdown-menu settings-menu'>
                                <?= showIfPermitted('settings', "<li><a href='settings'><i class='fa fa-cog fa-lg'></i>Settings</a></li>"); ?>
                                <?= showIfPermitted('staff_profile', "<li><a href='staff_profile'><i class='fa fa-user fa-lg'></i>Profile</a></li>"); ?>
								<?= showIfPermitted('student_profile', "<li><a href='student_profile'><i class='fa fa-user fa-lg'></i>Profile</a></li>"); ?>
                                <li><a href='../login.php'><i class='fa fa-sign-out fa-lg'></i> Logout</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>
                <?php
$role = $_SESSION['role'] ?? ''; // 'staff' or 'student'
$target = ($role === 'staff') ? "'staff','all'" : "'student','all'";
$sql = "SELECT message FROM notifications WHERE is_active = 1 AND target IN ($target) ORDER BY id DESC";

$result = $connection->query($sql);
$messages = [];
while ($row = $result->fetch_assoc()) {
    $messages[] = $row['message'];
}

$notif_content = implode(" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  |   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ", $messages);
?>

<?php if (!empty(trim($notif_content))): ?>
  <style>
    #notif-banner {
      position: relative;
      background-color: #f1c40f;
      color: #000;
      padding: 10px 40px 10px 15px;
      font-weight: bold;
      font-size: 16px;
      overflow: hidden;
      white-space: nowrap;
    }

    .scrolling-text-wrapper {
      display: inline-block;
      white-space: nowrap;
    }

    .scrolling-text {
      display: inline-block;
      white-space: nowrap;
      animation: scroll-left 40s linear infinite;
    }

    @keyframes scroll-left {
      0% {
        transform: translateX(100%);
      }
      100% {
        transform: translateX(-100%);
      }
    }

    #notif-banner .close-btn {
      position: absolute;
      right: 10px;
      top: 8px;
      font-size: 20px;
      font-weight: bold;
      color: #000;
      cursor: pointer;
      background: none;
      border: none;
      z-index: 10;
    }
  </style>

  <div id="notif-banner">
    <button class="close-btn" onclick="document.getElementById('notif-banner').style.display='none';">&times;</button>
    <div class="scrolling-text-wrapper">
      <div class="scrolling-text"><?= $notif_content ?></div>
    </div>
  </div>
<?php endif; ?>
            </nav>
        </header>
        <div class="loading">
  <div class="spinner">
    <div class="rect1"></div>
    <div class="rect2"></div>
    <div class="rect3"></div>
    <div class="rect4"></div>
  </div>
</div>
       <?php 

include 'sidebar.php';
include 'includes.php';



 ?>


