<?php session_start();?>
<?php include'includes/header.php'; ?>
<?php include'includes/sidebar.php';?>
<?php include'includes/functions.php';?>
<?php include'includes/navbar.php'; ?>

<!-- This page unique styles -->
<style>
/*Core setup styles*/
.sideNav{
    height: 100%;
    /*width: 220px;*/
    position: fixed;
    z-index: 9;
}
.navbar{
    top: 0;
    position: fixed;
    z-index: 9999;
}
.the-links{
    padding-top: 10px;
}
/*.nav-links{
    height: 100%;
    overflow-y: auto;
}*/
.insider{
    margin-top: 10px;
    position: relative;
}
.card{
    height: auto;
}
.cat-pag{
    position: relative;
}
.cat-page-header{
    position: sticky;
    width: 100%;
    height: 50px;
    background:#F7F9FB; 
    top: 60px;
    right: 60px;
    z-index: 1;
}
@media(max-width: 992px){
.insider{
    margin-top: 10px;
    padding-left: 10px;
    padding-right: 10px;
    }        
}
.card-header h5{
    font-size: 14px;
}
td span{
    padding: 10px; border-radius: 6px;
    font-size: 13px;
}
.assign-title{
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-self: center;
}
.assign-title h4{
    font-size: 16px;
    font-family: sans-serif;

}
.assign-title a{
    color: #fff;
}
.working-assign{
    width: 100%;
}
.working-assign h5{
    font-size: 15px;
    font-weight: bold;
}
.working-assign label{
    font-size: 14px;
    margin-top: -5px;
}
.sm-edit{
    font-size: 8px;
}
@media(max-width: 992px){
    .text-sm{
        font-size: 12px;
    }
    li h6{
        font-size: 12px;
        margin-top:5px;
    }
    input[type='checkbox']{
        width: 12px;
        height: 12px;
}
</style>
<?php
if (isset($_POST['DeleteSub'])) {
    $assignSub  = $_POST['subj-input'];
    $sliptVal = explode('*', $assignSub);
    $assignSubj = $sliptVal[0];
    $assignId   = $sliptVal[1];

    $sqlDelAsg = "DELETE FROM teacher_assignments WHERE staffId = ? AND subject = ?";
    $stmtDelAsg = $pdo->prepare($sqlDelAsg);
    $stmtDelAsg->execute([$assignId, $assignSubj]);
    // Msg
    $_SESSION['message'] = 'Subject deleted Successfully';
    $_SESSION['type'] = 'success';

}
$totalStaff = $pdo->query("SELECT COUNT(*) FROM staff")->fetchColumn();
?>

<div id="notification-containers" class="notification-containers"></div>
<div class="insider">
    <div class="container">
        <div class="cat-pag">
            <div class="cat-page-header d-flex justify-content-between align-items-center">
                <h5></h5>
                <div>
                    <a href="add-staff.php" class="btn btn-sm info text-white">
                        <i class="fa fa-user-plus"></i> Add New Staff
                    </a>

                    <button class="btn btn-sm danger text-white" onclick="handleDelete()">
                       <i class="fa fa-user-minus"></i> Remove Staff
                    </button>
                </div>
            </div>

            <div class="card mt-3">
                <div class="card-header text-left d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fa fa-users text-primary"></i> All Staffs
                    </h5>
                    <div class="d-flex align-items-center flex-wrap gap-2">
                      <span class="badge bg-primary me-2">Total: <?= $totalStaff ?></span>
                      
                      <a href="add-staff.php" class="btn btn-sm btn-success d-flex align-items-center">
                        <i class="fa fa-plus me-1"></i> <span>Add</span>
                      </a>
                      <button type="button" form="mainForm" name="delete-btn"
                          onclick="handleDelete()"
                        class="btn btn-sm btn-danger d-flex align-items-center">
                        <i class="fa fa-trash me-1"></i> <span>Remove</span>
                      </button>
                    </div>
                </div>
                <div class="card-body">
                    <form action="" method="POST" id="mainForm">
                        <!-- Delete Confirmation Modal -->
                        <div id="modal-delete" class="modal">
                            <div class="modal-content" style="margin-top:150px;">
                                <div class="modal-header">Delete Confirmation</div>
                                <div class="modal-body">Are you sure you want to remove the Staff (s) ?</div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" onclick="closeModal('modal-delete')">No, Cancel</button>
                                    <button type="submit" name="DeleteBtn" class="btn btn-danger">Yes, Delete</button>
                                </div>
                            </div>
                        </div>

                        <!-- Delete Subject Confirmation Modal -->
                        <div id="modal-delete-sub" class="modal" style="z-index: 999999">
                            <input type="hidden" name="subj-input" id="deleteSubValue">
                            <div class="modal-content" style="margin-top:50px;">
                                <div class="modal-header">Delete Confirmation</div>
                                <div class="modal-body">
                                Are you sure you want to remove the Subject ?
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" onclick="closeModal('modal-delete-sub')">No, Cancel
                                    </button>

                                    <button type="submit" name="DeleteSub" class="btn btn-danger">Yes, Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table id="example" class="display nowrap table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th></th> <!-- This will be used for the toggle (+) -->
                                        <th><input type="checkbox" id="SelectAllBoxes"></th>
                                        <th data-priority="3" class="text-sm">S/N</th>
                                        <th data-priority="1" class="text-sm">Names</th>
                                        <th data-priority="2" class="text-sm">Email</th>
                                        <th data-priority="1" class="text-sm">Roles</th>
                                        <th data-priority="4" class="text-sm">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sn = 0;
                                    $fetch = "SELECT * FROM staff order by staffId DESC";
                                    $stmt = $pdo->prepare($fetch);
                                    $stmt->execute();
                                    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                        $sn = $sn + 1;
                                        $staffId    = $row['staffId'];
                                        $names      = $row['fullname'];
                                        $email      = $row['email'];
                                        $roles       = $row['roles'];
                                        $mobile     = $row['phone_number'];
                                        if ($roles == 'vice_principal') {
                                          $dispRole = 'Vice Principal';
                                        }
                                        elseif ($roles == 'class_teacher') {
                                          $dispRole = 'Class Teacher';
                                        }
                                        elseif ($roles == 'subject_teacher') {
                                          $dispRole = 'Subject Teacher';
                                        }
                                        elseif ($roles == 'admin') {
                                          $dispRole = 'Admin';
                                        }
                                        else{
                                          $dispRole = 'Principal';
                                        }
                                        ?>
                                        <!-- Get class teacher -->
                                        <?php
                                        $teachSql = "SELECT class FROM class_teacher 
                                                WHERE staffId = ? ";
                                        $teachStmt = $pdo->prepare($teachSql);
                                        $teachStmt->execute([$staffId]);
                                        $teachRow = $teachStmt->fetch(PDO::FETCH_ASSOC);
                                        $staffX = isset($teachRow['class']) ? 
                                        $teachRow['class'] : ''; 
                                        ?>
                                        <tr>
                                            <td></td> <!-- Auto-filled by DataTables for toggle icon -->
                                            <td>
                                                <input type="checkbox" name="checkBoxArray[]" 
                                                value="<?= $staffId ?>" class='checkBoxes'>
                                            </td>
                                            <td><?= $sn ?></td>
                                            <td>
                                                <?=$names?>
                                            </td>
                                            <td>
                                                <?=$email?>
                                            </td>
                                            <td>
                                                <?=$dispRole?>
                                                <?php
                                                if ($roles == 'class_teacher') {
                                                    echo "($staffX)";
                                                }?>
                                            </td>
                                            
                                            <td class="text-center">
                                                <a href="edit-staff.php?editVal=<?=$staffId?>" class="btn btn-sm btn-primary">
                                                    <i class="fa fa-edit"></i> Edit 
                                                </a>
                                                <!-- <button type="button" class="btn btn-sm btn-primary" onclick="openModal('modal-<?= $staffId ?>')">
                                                    Edit <i class="fa fa-edit"></i>
                                                </button> -->

                                                <button type="button" class="btn btn-sm invoice text-white" onclick="openModal('modal-assign-<?= $staffId ?>')">
                                                    <i class="fa fa-plus-circle"></i> Assign 
                                                </button>
                                            </td>
                                                <!-- Edit Modal -->
                                                <?php EditStaff();?>
                                        </tr>

                                        <?php Assigning()?>
                                        
                                    <?php }?>
                                </tbody>
                            </table>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        
   
    </div>
</div>
<?php



if (isset($_POST['assigned-btn'])) {
    $assign_subject = $_POST['subject'];
    $assign_class   = $_POST['class'];
    $staffId        = $_POST['staffId'];

    if (!isset($_POST['class'])) {
        $_SESSION['message'] = "Class is empty";
        $_SESSION['type'] = "error";
    }else{
        foreach ($assign_class as $classList) {
            $select = "SELECT * FROM teacher_assignments WHERE subject = ? AND class = ?";
            $selectPdo = $pdo->prepare($select);
            $selectPdo->execute([$assign_subject, $classList]);
            $valdate = $selectPdo->rowCount();

            if ($valdate == TRUE) {
                // ERROR message, data already exist
               $_SESSION['message'] = "The subject and Class are already filled";
               $_SESSION['type'] = "error"; 
            }else{
                // Then assign the staff
                $insert = "INSERT INTO teacher_assignments (staffId, subject, class)VALUES(?, ?, ?)";
                $stme = $pdo->prepare($insert);
                $stme->execute([$staffId, $assign_subject, $classList]);

                $_SESSION['message'] = "Task Assigned Successfully";
                $_SESSION['type'] = "success";
                ?>
                <script type="text/javascript">
                  setTimeout("location.href='javascript:history.back()';", 2000);
                </script>
                <?php 
            }
        }

    }
    
}
?>
<style type="text/css">
.class-box {
    display: flex;
    gap: 15px;
    overflow-x: auto;
    padding: 10px 0;
    scrollbar-width: thin;
}

.class-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    white-space: nowrap;
    background-color: #f9f9f9;
    cursor: pointer;
    transition: all 0.2s ease;
}

.class-item:hover {
    background-color: #eef5ff;
    border-color: #5a9bff;
}

.class-item input[type="checkbox"] {
    accent-color: #007bff;
}

.class-item input[type="radio"] {
    accent-color: #007bff;
}
.box-overall{
    width: 100%;
    height: auto;
}
.class-box{
    margin-top: 20px;
    width: 100%;
    height: 100px;
    display: flex;
    gap:25px;
    padding-bottom: 20px;
    overflow-x: auto;
}
.sing-box{
    padding: 5px;
    border:1px solid #ccc;
    border-radius: 5px;
}


</style>

<?php

// update user
if (isset($_POST['upd-std'])) {
    $email = $_POST['email'];
    $name   = $_POST['name'];
    $mobile    = $_POST['mobile'];
    $role       = $_POST['role'];
    $staffId    = $_POST['staffId'];

    $updateStaff = "UPDATE staff SET email = ?, fullname = ?, 
                    phone_number = ?, roles = ? WHERE staffId = ?";
    $updateStmt = $pdo->prepare($updateStaff);
    $updateStmt->execute([$email, $name, $mobile, $role, $staffId]);

    $_SESSION['message'] = 'User Updated Successfully.';
    $_SESSION['type'] = 'success';

    ?>
    <script type="text/javascript">
      setTimeout("location.href='javascript:history.back()';", 2000);
    </script>
    <?php 
}

// Remove Staff
// Handle Delete Slider
if (isset($_POST['DeleteBtn'])) {
    if (!empty($_POST['checkBoxArray'])) {
        foreach ($_POST['checkBoxArray'] as $staffId) {
            // Then delete from the products table
            $delete = "DELETE FROM staff WHERE staffId = ?";
            $delStmt = $pdo->prepare($delete);
            $delStmt->execute([$staffId]);
            
            // Check if staff(s) exist in teacher_assignment as well
            $cheDel = "DELETE FROM teacher_assignments WHERE staffId = ?";
            $chePdo = $pdo->prepare($cheDel);
            $chePdo->execute([$staffId]);
            // Alert message
            $_SESSION['message'] = "Staff(s) deleted Successfully";
            $_SESSION['type'] = "success";
            // Then refresh the page for 2 Minutes
            ?>
            <script type="text/javascript">
              setTimeout("location.href='javascript:history.back()';", 2000);
            </script>
            <?php 
        }
    }
}
?>


<?php include 'includes/footer.php'; ?>

<script>
    document.addEventListener("DOMContentLoaded", () => {
        const selects = document.querySelectorAll('.subjectSelect');

        selects.forEach(select => {
            const staffId = select.getAttribute('data-staff');
            const container = document.getElementById(`classContainer-${staffId}`);

            select.addEventListener('change', () => {
                if (select.value !== '') {
                    container.style.display = 'block';
                } else {
                    container.style.display = 'none';
                }
            });
        });
    });
</script>


<!-- DataTables & jQuery -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css">

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
<script>
    $('#example').DataTable({
      responsive: {
        details: {
          type: 'column',
          target: 0 // (+) icon for toggling hidden info
        }
      },

      columnDefs: [
        { className: 'control', orderable: false, targets: 0 }, // (+) toggle
        { orderable: false, targets: [1, -1] }, // disable sorting on checkbox & action
        { targets: 1, responsivePriority: 1 }, // Checkbox always visible
        { targets: 3, responsivePriority: 1 }, // Names always visible
        { targets: 5, responsivePriority: 1 }, // Roles always visible
        { targets: 2, responsivePriority: 4 }, // S/N less important
        { targets: 4, responsivePriority: 3 }, // Email may hide on small screens
        { targets: -1, responsivePriority: 2 }, // Action visible after roles
      ],
      paging: true,
      searching: true,
      info: true
    });

    language: {
      emptyTable: "No staff records found. Click 'Add New' to register staff."
    }

</script>
<script type="">
    responsive: true,
    dom: '<"top"lf>rt<"bottom"ip><"clear">',
</script>
<script>
    $(document).ready(function () {
        $('#example').DataTable();
        $('#SelectAllBoxes').click(function () {
            $('.checkBoxes').prop('checked', this.checked);
        });
    });

    function openModal(id) {
        document.getElementById(id).style.display = "block";
    }

    function closeModal(id) {
        document.getElementById(id).style.display = "none";
    }

    function handleDelete() {
        const checked = document.querySelectorAll("input[name='checkBoxArray[]']:checked");
        if (checked.length === 0) {
            alert("No staff(s) selected!");
            return;
        }
        openModal('modal-delete');
    }
    function RemoveSubj(value) {
      // Set the hidden field inside modal
      document.getElementById('deleteSubValue').value = value;

      // Open the modal
      openModal('modal-delete-sub');
    }
   
</script>


<!-- Modal Styling -->
<style>
.modal {
    display: none;
    position: fixed;
    z-index: 99999;
    left: 0; top: 0;
    width: 100%; height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.5);

}

.modal-content {
    background-color: #fff;
    margin: auto;
    padding: 20px;
    border-radius: 8px;
    width: 80%;
    max-width: 500px;
    animation: fadeIn 0.3s;
}
@media(max-width: 992px){
    .modal-content{
        width: 90%;
    }
}

.modal-header, .modal-footer {
    font-weight: bold;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-20px); }
    to { opacity: 1; transform: translateY(0); }
}

.single-input{
    margin-top: 10px;
}
.single-input label{
    font-size: 15px;
    margin-left: 20px;
    font-family: sans-serif;
}
.my-input input{
    width: 100%;
    border:2px solid #ccc;
    outline: none;
    font-size: 16px;
    color: 888;
    height: 50px;
    border-radius: 10px;
    padding: 15px;
    text-align: left;
   /* height: 20px;*/
}
.my-input select{
    width: 100%;
    border:2px solid #ccc;
    outline: none;
    font-size: 16px;
    color: 888;
    height: 50px;
    border-radius: 10px;
    padding: 10px;
   /* height: 20px;*/
}
</style>

<!-- Notifications alert -->
<?php include'includes/notification-alert-js.php';?>

