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

<!-- Handle Add Slider -->
<style>
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;
}
</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';

}

?>
<?php include'includes/edit_assign_query.php';?>
<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">
                        Add New Staff <i class="fa fa-user-plus"></i>
                    </a>

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

            <div class="card mt-3">
                <div class="card-header text-left">
                    <h5>All Staffs <i class="fa fa-users"></i></h5>
                </div>
                <div class="card-body">
                    <form action="" method="POST" id="mainForm">
                        
                        <div class="table-responsive">
                            <table id="example" class="display table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th><input type="checkbox" id="SelectAllBoxes"></th>
                                        <th>S/N</th>
                                        <th>Names</th>
                                        <th>Email</th>
                                        <th>Roles</th>
                                        
                                        <th>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';
                                        }

                                        ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" name="checkBoxArray[]" 
                                                value="<?= $staffId ?>" class='checkBoxes'>
                                            </td>
                                            <td><?= $sn ?></td>
                                            <td>
                                                <?=$names?>
                                            </td>
                                            <td>
                                                <?=$email?>
                                            </td>
                                            <td><?=$dispRole?></td>
                                            
                                            <td class="text-center">
                                                <a href="edit-staff.php?editVal=<?=$staffId?>" class="btn btn-sm btn-primary">
                                                    Edit <i class="fa fa-edit"></i>
                                                </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 ?>')">
                                                    Assign <i class="fa fa-edit"></i>
                                                </button>
                                            </td>
                                                
                                        </tr>

                    
                                    <?php }?>
                                </tbody>
                            </table>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        
   
    </div>
</div>
<?php
if (isset($_POST['edit-assign-btn'])) {
    $subj_name = $_POST['subj_name'];
    $sub_box = $_POST['subj_box'];
    $staffId = $_POST['staffId'];

    // Delete first
    $sql = "DELETE FROM teacher_assignments 
        WHERE staffId = ? AND subject = ?";
    $query = $pdo->prepare($sql);
    $query->execute([$staffId, $subj_name]);

    // Then Insert new items
    $sub_sql = "INSERT INTO teacher_assignments(staffId, subject, class)VALUES(?,?,?)";
    $sub_query = $pdo->prepare($sub_sql);

    foreach ($sub_box as $key_sub) {
        $select = "SELECT * FROM teacher_assignments WHERE subject = ? AND class = ?";
        $selectPdo = $pdo->prepare($select);
        $selectPdo->execute([$subj_name, $key_sub]);
        $valdate = $selectPdo->rowCount();
        if ($valdate == TRUE) {
            // ERROR message, data already exist
           $_SESSION['message'] = "The subject and Class are already filled";
           $_SESSION['type'] = "error"; 
        }else{
            $sub_query->execute([$staffId, $subj_name, $key_sub]);
        }
    }
    $_SESSION['message'] = "Updated Successfully";
    $_SESSION['type'] = 'success';

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

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

    }
    
}
?>


<?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">
<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>
    $(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>
.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;
}
.box-overall{
    width: 100%;
    height: auto;
}

.modal {
    display: block;
    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';?>

