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

<style>
    td span{
        padding: 10px; border-radius: 6px;
        font-size: 13px;
    }
    .card-header h3{
        font-size: 18px;
        font-weight: bold;
        font-family: sans-serif;
        color: #3C763D;
    }
    .card-header h5{
        font-size: 14px;
        /*font-weight: bold;*/
        font-family: sans-serif;

    }
    .cat-page-header h5{
        font-family: sans-serif;
        font-size: 18px;
        font-weight: bold;
    }
    .success_stutus{
        background: #E8FCEF; color: #4ECA74;
    }
    .error_status{
        background: #F8D7DA; color: #90151C;
    }
    .cat-page-header .warning-text{
        color: #90151C;
        font-weight: normal;
        /*font-style: italic;*/
    }
    .cat-page-header .success-text{
        color: #4ECA74;
        font-weight: normal;
        /*font-style: italic;*/
    }
    .negative{
        width: 100%;
        height: auto;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 10px;
        margin-top: 20px;
    }
    .negative i{
        font-size: 70px;
        color: #FE9C13;

    }
    .negative h5{
        font-size: 20px;
        color: #FE9C13;
        text-align: center;
        font-weight: bold;
        font-family: sans-serif; 
    }
    .negative a{
        padding: 10px;
        color: #fff;
        text-decoration: none;
        text-align: center;
        font-size: 17px;
        border-radius: 5px;
        /*font-weight: bold;*/
    }
    .negative a i{
        font-size: 17px;
        color: #fff;
    }
</style>
<?php

if (isset($_GET['class'])) {
    $getVal = $_GET['class'];
    $unvel = explode('*', $getVal);

    $class = $unvel[0];
    $subject = $unvel[1];
}
// Get your class student
$clastd = "SELECT class FROM class_teacher WHERE staffId = ?";
$thepdo = $pdo->prepare($clastd);
$thepdo->execute([$staffId]);
$filter = $thepdo->rowCount();
if ($filter == FALSE) {
    header('Location:index.php');
}else{
    $classRow = $thepdo->fetch(PDO::FETCH_ASSOC);
    $myClass = $classRow['class'];
}

// Validate to know if the test and exam is out for the current term and session
// Check for Test
$testExam = "SELECT test_score FROM results WHERE class = ? AND term = ? AND session = ?";
$stmt = $pdo->prepare($testExam);
$stmt->execute([$myClass, $current_term, $current_session]);
$validate = $stmt->rowCount();
if ($validate > 0) {
    $rstRow = $stmt->fetch(PDO::FETCH_ASSOC);
    $test_status = "Recorded";
}else{
    $test_status = "pending";
}

// Check for Exam
$testExam = "SELECT exam_score FROM results WHERE class = ? AND term = ? AND session = ?";
$stmt = $pdo->prepare($testExam);
$stmt->execute([$myClass, $current_term, $current_session]);
$validate = $stmt->rowCount();
if ($validate > 0) {
    $rstRow = $stmt->fetch(PDO::FETCH_ASSOC);
    $exam_status = "Recorded";
}else{
    $exam_status = "pending";
}


if ($test_status =='pending') {
    $ca_color = 'warning-text';
}else{
    $ca_color = 'success-text';
}

if ($exam_status =='pending') {
    $exam_color = 'warning-text';
}else{
    $exam_color = 'success-text';
}



?>

<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-student.php" class="btn btn-sm info text-white">Add New Student <i class="fa fa-user-plus"></i></a>

                    <button class="btn danger text-white" onclick="handleDelete()">
                        Remove Student <i class="fa fa-user-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card mt-3">
                <div class="card-header text-center">
                    <h3>OBACCO COLLEGE</h3>
                    <h5 class="text-success"><?= $myClass?> | 
                        <?= $current_term?>Term <?= $current_session?> Academic Session
                    </h5>
                </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 delete the selected Student(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>

                        <div class="table-responsive">
                            <table id="example" class="display table table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th><input type="checkbox" id="SelectAllBoxes"></th>
                                        <th>ID</th>
                                        <th>Surname</th>
                                        <th>Othernames</th>
                                        <th>Image</th>
                                        <th>Gender</th>
                                        <!-- <th>Total</th> -->
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <!-- Display all student in this class -->
                                <?php
                                $sn = 0;
                                $allstd = "SELECT * FROM student WHERE class = ? 
                                        AND term = ? AND session = ?";
                                $stmt = $pdo->prepare($allstd);
                                $stmt->execute([$myClass, $current_term, $current_session]);
                                while ($stdRow = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                    $stdId      = $stdRow['studId'];
                                    $surName    = $stdRow['surname'];
                                    $otherNames = $stdRow['otherNames'];
                                    $gender     = $stdRow['gender'];
                                    $password   = $stdRow['password'];
                                    
                                    $encryptId = encryptData($stdId);

                                $stdImg = "SELECT photo_path, dob 
                                        FROM student_image WHERE studentId = ?";
                                $imgStmt = $pdo->prepare($stdImg);
                                $imgStmt->execute([$stdId]);
                                while ($imgRow = $imgStmt->fetch(PDO::FETCH_ASSOC)) {
                                    $theImg = $imgRow['photo_path'];
                                    $dob    = $imgRow['dob'];
                                    $sn = $sn + 1;

                                ?>
                                    <tr>
                                        <td>
                                            <input type="checkbox" name="checkBoxArray[]" 
                                            value="<?= $stdId ?>" class='checkBoxes'>
                                        </td>
                                        <td><?= $sn ?></td>
                                        <td>
                                            <?=$surName?>
                                        </td>
                                        <td>
                                            <?=$otherNames?>
                                        </td>
                                        <td>
                                            <img alt="Student Image" src="../../student/images/avatar/<?=$theImg?>" id = "image-<?=$stdId?>" width="60px" height="40px" >
                                        </td>
                                        <td><?=$gender?></td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-primary" onclick="openModal('modal-<?= $stdId ?>')">
                                                Edit <i class="fa fa-edit"></i>
                                            </button>

                                            <button type="button" class="btn btn-sm invoice text-white" 
                                            onclick="openModal('avatar-<?= $stdId?>')">
                                                Image <i class="fa fa-edit"></i>
                                            </button>
                                        </td>
                                        <!-- Edit Modal -->
                                        <?php EditStd();?>


                                        <!-- Modal Avater -->
                                        <div id="avatar-<?=$stdId?>" class="modal">
                                            <div class="modal-content" style="margin-top:50px;">
                                                <div class="modal-header text-success">Student Image <i class="fa fa-plus-circle"></i></div>
                                                <div class="modal-body">
                                                    <form action="" method="POST" enctype="multipart/form-data">
                                                        <div class="avatar">
                                                            <input type="hidden" name="feature_image" value="<?=$stdId?>">
                                                            <div class="uploads" style="margin-top: -5px;">
                                                              <img alt="Student Image" src="../../student/images/avatar/<?=$theImg?>" id = "image-<?=$stdId?>" >
                                                              <div class="rightRound" id = "upload">

                                                            <input type="file" name="the_avatar" 
                                                            id = "fileImg-<?=$stdId?>" accept=".jpg, .jpeg, .png" value="<?=$theImg?>">
                                                                <i class = "fa fa-camera"></i>
                                                              </div>

                                                              <div class="leftRound" id ="cancel-<?=$stdId?>" style = "display: none;">
                                                                <i class = "fa fa-times"></i>
                                                              </div>
                                                            </div>
                                                            <input type="hidden" name="stdId" value="<?=$stdId?>">
                                                        </div>

                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-danger" onclick="closeModal('avatar-<?=$stdId?>')">Cancel <i class="fa fa-cancel"></i> &times;</button>
                                                            <!-- Add product button -->
                                                            <button name="upd-avatar" class="btn btn-success">Update Image <i class="fa fa-refresh"></i></button>
                                                        </div>
                                                        
                                                    </form>
                                                </div>
                                                
                                            </div>
                                        </div>
                                    </tr>
                                   <?php } } ?> 
                                </tbody>
                            </table>
                        </div>
                        
                    </form>
                </div>
            </div>
        </div>
   
    </div>
</div>


<?php
// Update Student Details
if (isset($_POST['upd-std'])) {
    $surname        = $_POST['surname'];
    $othername      = $_POST['othername'];
    $gender         = $_POST['gender'];
    $dob            = $_POST['dob'];
    $stdId          = $_POST['stdId'];
    $password       = $_POST['new_pass'];
    $confirm        = $_POST['confirm'];

    if ($password != $confirm) {
        $_SESSION['message'] = 'Password does not match';
        $_SESSION['type'] = 'error';
    }else{
        $valPass = password_hash($password, PASSWORD_DEFAULT);
        // update now
        $upStd = "UPDATE student SET surname = ?, otherNames = ?, 
                gender = ?, password = ? WHERE studId = ? ";
        $upStmt = $pdo->prepare($upStd);
        $upStmt->execute([$surname, $othername, $gender, $valPass, $stdId]);

        $updob = "UPDATE student_image SET dob = ? WHERE studentId = ?";
        $dobStmt = $pdo->prepare($updob);
        $dobStmt->execute([$dob, $stdId]);

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

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

}

// Uploading Image 
if (isset($_POST['upd-avatar'])) {
    $stdId  = $_POST['stdId'];
    $the_avatar_image          = $_FILES['the_avatar']['name'];
    $the_avatar_img_temp       = $_FILES['the_avatar']['tmp_name'];
    move_uploaded_file($the_avatar_img_temp, "../../student/images/avatar/$the_avatar_image");

    $updImg = "UPDATE student_image SET photo_path = ? WHERE studentId = ?";
    $imgstmt = $pdo->prepare($updImg);
    $imgstmt->execute([$the_avatar_image, $stdId]);

    $_SESSION['message'] = 'Image Updated Successfully.';
    $_SESSION['type'] = 'success';?>

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

// Handle Delete Student
if (isset($_POST['DeleteBtn'])) {
    if (!empty($_POST['checkBoxArray'])) {
        foreach ($_POST['checkBoxArray'] as $stdId) {

           
            // Then delete from the products table
            $delete = "DELETE FROM student WHERE studId = ?";
            $delStmt = $pdo->prepare($delete);
            $delStmt->execute([$stdId]);
            $_SESSION['message'] = "Student(s) deleted Successfully";
            $_SESSION['type'] = "success";?>

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

<!-- Uploading image js -->
<script>
  document.querySelectorAll('[id^="avatar-"]').forEach(modal => {
    const studentId = modal.id.split('-')[1];
    const uploadsDiv = modal.querySelector(`#upload`);

    const fileInput = document.getElementById(`fileImg-${studentId}`);
    const imagePreview = document.getElementById(`image-${studentId}`);
    const cancelBtn = document.getElementById(`cancel-${studentId}`);

    if (fileInput && imagePreview && cancelBtn && uploadsDiv) {
      const originalImageSrc = imagePreview.src;

      fileInput.onchange = function () {
        if (fileInput.files && fileInput.files[0]) {
          imagePreview.src = URL.createObjectURL(fileInput.files[0]);
          cancelBtn.style.display = "block";
          uploadsDiv.style.display = "none";
        }
      };

      cancelBtn.onclick = function () {
        imagePreview.src = originalImageSrc;
        cancelBtn.style.display = "none";
        uploadsDiv.style.display = "block";
        fileInput.value = ''; // Reset file input
      };
    }
  });
</script>

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

<!-- 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 students selected!");
            return;
        }
        openModal('modal-delete');
    }
   
</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';?>

