<?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;
  }
  .small-text{
    font-size: 13px;
  }
  .text-sm{
    font-size: 12px;
  }
  input[type='checkbox']{
    width: 12px;
    height: 12px;
  } 

}
.card-header h5{
    font-size: 14px;
}
td span{
    padding: 10px; border-radius: 6px;
    font-size: 13px;
}
.success_stutus{
    background: #E8FCEF; color: #4ECA74;
}
.error_status{
    background: #F8D7DA; color: #90151C;
}
.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
// Handle Delete Slider
if (isset($_POST['DeleteBtn'])) {
  if (!empty($_POST['checkBoxArray'])) {
    foreach ($_POST['checkBoxArray'] as $adminNo) {
    // Then delete from the products table
      $delete = "DELETE FROM student WHERE adminNo = ?";
      $delStmt = $pdo->prepare($delete);
      $delStmt->execute([$adminNo]);
      
      // Also delete their details
      $delDe = "DELETE FROM student_image WHERE adminNo = ?";
      $delDpdo = $pdo->prepare($delDe);
      $delDpdo->execute([$adminNo]);

      $_SESSION['message'] = "Student(s) deleted Successfully";
      $_SESSION['type'] = "success";
    }      
  }
}
$totalStd = $pdo->query("SELECT COUNT(*) FROM student")->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-student.php" class="btn btn-sm info text-white">
            <i class="fa fa-user-plus"></i> New Student
          </a>

          <button class="btn btn-sm primary text-white" onclick="openModal('modal-add')">
            <i class="fa fa-users"></i> Upload
          </button>

          <button class="btn btn-sm danger text-white" onclick="handleDelete()">
            <i class="fa fa-user-minus"></i> Remove 
          </button>
        </div>
      </div>
      <div class="card mt-3">
                <div class="card-header text-left d-flex justify-content-between align-items-center">
                  <h5>All Students <i class="fa fa-users"></i></h5>
                  <span class="badge bg-primary me-2">Total: <?= $totalStd ?></span>
                </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, Remove</button>
                                </div>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                          <table id="example" class="display 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="1" class="text-sm">Admin No</th>
                                <th data-priority="2">Names</th>
                                <th data-priority="3">Images</th>
                                <th data-priority="1" class="text-sm">Class</th>
                                <th data-priority="1" class="text-sm">Action</th>
                              </tr>
                            </thead>
                            <tbody>
                              <?php
                              $snr = 0;
                              $fetch = "SELECT * FROM student order by studId DESC";
                              $stmt = $pdo->prepare($fetch);
                              $stmt->execute();
                              while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                  $snr ++;
                                  $stdId          = $row['studId'];
                                  $adminNo        = $row['adminNo'];
                                  $surname        = $row['surname'];
                                  $otherNames     = $row['otherNames'];
                                  $class          = $row['class'];  
                                 
                                 // Get student Image
                              $stdImg = "SELECT * FROM student_image WHERE adminNo = ?";
                              $imgStmt = $pdo->prepare($stdImg);
                              $imgStmt->execute([$adminNo]);
                              while ($imgRow = $imgStmt->fetch(PDO::FETCH_ASSOC)) {
                                  $imageName = $imgRow['photo_path'];
                                  $stdDate   = $imgRow['dob'];?>
                              <tr>
                                <td></td> <!-- Auto-filled by DataTables for toggle icon -->
                                <td>
                                  <input type="checkbox" name="checkBoxArray[]" 
                                      value="<?= $adminNo ?>" class='checkBoxes'>
                                </td>
                                <td class="text-sm"><?= $adminNo ?></td>
                                <td class="text-sm">
                                    <?=$surname.' '.$otherNames?>
                                </td>
                                <td>
                                    <img alt="Student Image" 
                                    src="../../student/images/avatar/<?=$imageName?>" 
                                    id = "image-<?=$stdId?>"
                                    loading = "lazy" 
                                    width="60px" height="40px" >
                                </td>
                                <td class="text-sm"><?=$class?></td>
                                
                                <td class="text-center">
                                    <a href="edit-student.php?stdId=<?=$adminNo?>" class="btn btn-sm btn-primary">
                                        Edit <i class="fa fa-edit"></i>
                                    </a>

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

        <!-- Upload Modal -->
        <div id="modal-add" class="modal">
            <div class="modal-content" style="margin-top:50px;">
                <div class="modal-header text-success">Upload File <i class="fa fa-file"></i></div>
                <div class="modal-body">
                    <form action="" method="POST" enctype="multipart/form-data">

                       <div class="file-upload-wrapper">
                         <input type="file" id="excelFile" name="excelFile" accept=".xls,.xlsx" required>
                         <label for="excelFile" class="upload-label">
                           <i class="fa fa-file-excel"></i>
                           <span id="fileName">Choose Excel File</span>
                         </label>
                       </div>

                       <div class="modal-footer mt-4">
                           <button type="button" 
                               class="btn btn-danger btn-sm" 
                               onclick="closeModal('modal-add')">Cancel 
                               <i class="fa fa-cancel"></i> &times;
                           </button>

                           <button
                               onclick="exportTableToExcel()"
                               class="btn btn-sm info text-white">Download Format 
                               <i class="fa fa-download"></i>
                           </button>

                           <button type="submit"
                                name="upload-btn" 
                               id="uploadBtn" class="upload-btn btn-sm" disabled>
                               <i class="fa fa-upload"></i> Upload File
                           </button>
                       </div>
                        
                    </form>
                </div>
                
            </div>
        </div>
   
    </div>
</div>
<?php
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

if (isset($_POST['upload-btn'])) {

    $fileName = $_FILES['excelFile']['name'];
    $file_ext = pathinfo($fileName, PATHINFO_EXTENSION);
    $allowed_ext = ['xls', 'csv', 'xlsx'];

    if (in_array(strtolower($file_ext), $allowed_ext)) {
        
        $inputFileNamePath = $_FILES['excelFile']['tmp_name'];
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileNamePath);
        $data = $spreadsheet->getActiveSheet()->toArray();

        $count = 0; // total records processed
        $inserted = 0; // successfully inserted count
        $skipped = 0;  // optional: count skipped rows (if needed)

        foreach ($data as $index => $row) {
            if ($index > 0) { // skip header row
                $surname   = trim($row[0]);
                $firstName = trim($row[1]);
                $lastName  = trim($row[2]);
                $class     = trim($row[3]);
                $gender    = trim($row[4]);
                $dob       = trim($row[5]);

                // Skip completely empty rows
                if (empty($surname) && empty($firstName) && empty($class)) {
                    $skipped++;
                    continue;
                }

                $pass = $surname . '123';
                $password = password_hash($pass, PASSWORD_DEFAULT);
                $otherNames = $firstName . ' ' . $lastName;

                if ($gender =='') {
                  $gender = 'Male';
                }
                if ($dob == '') {
                  $dob = date('Y-m-d');
                }

                // Insert into student table
                $sqlInsert = "INSERT INTO student (surname, otherNames, gender, password, class, term, session)
                              VALUES (?, ?, ?, ?, ?, ?, ?)";
                $stmtInsert = $pdo->prepare($sqlInsert);
                $stmtInsert->execute([
                    $surname, 
                    $otherNames, 
                    $gender, 
                    $password, 
                    $class, 
                    $current_term, 
                    $current_session
                ]);

                $lastId = $pdo->lastInsertId();

                // Update to insert the admission Number for the student
                $adminNo = "DEG/25/P" . str_pad($lastId, 3, "0", STR_PAD_LEFT);
                $upadmin = "UPDATE student SET adminNo = ? WHERE studId = ?";
                $adminPdo = $pdo->prepare($upadmin);
                $adminPdo->execute([$adminNo, $lastId]);

                // Insert into student_image table
                $inserts = "INSERT INTO student_image (adminNo, dob) VALUES (?, ?)";
                $insertPdo = $pdo->prepare($inserts);
                $insertPdo->execute([$adminNo, $dob]);

                $inserted++;
            }
        }

        // Store total number of inserted students in session
        $_SESSION['stdNo'] = $inserted;

        // ✅ Professional Success Message
        $msgTitle = "<b>Upload Successful</b>";
        $msgBody = "
          <center>
            All student details have been uploaded successfully.<br>
            <b>Total Students Added:</b> $inserted
          </center>";
        $msgCloseBtn = "Okay, Got it.";

        include 'includes/checkmark-alert.php';

    } else {
        // ❌ Professional Error Message
        $_SESSION['message'] = "Invalid file format. Please upload a valid Excel document (.xls, .xlsx, or .csv).";
        $_SESSION['type'] = 'error';
    }
}

?>




<!-- Design Excel Table -->
<table class="table table-bordered table-hover" id="tblData" style="display: none">
    <tr>
      <th>Surname</th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Class</th>
      <th>Gender</th>
      <th>Date of birth</th>
    </tr>
    <tbody>
      <tr>
        <td>Adamawa</td>
        <td>Joshua</td>
        <td>Francis</td>
        <td>Primary 3B</td>
        <td>Male</td>
        <td>05/10/2010</td>
      </tr>
    </tbody>
  </table>

<style type="text/css">
    .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;
    }
/* Wrapper */
.file-upload-wrapper {
  position: relative;
  display: inline-block;
  width: 100%;
  max-width: 400px;
  margin: 20px auto;
  text-align: center;
}

/* Hide the real input */
.file-upload-wrapper input[type="file"] {
  display: none;
}

/* Custom label */
.upload-label {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: #1F282F;
  color: #fff;
  border: 2px solid #1F282F;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  font-weight: 500;
  font-size: 16px;
}

.upload-label i {
  font-size: 20px;
  color: #28a745;
}

.upload-label:hover {
  background: #28a745;
  border-color: #28a745;
  color: #fff;
}

.upload-label:hover i {
  color: #fff;
}

/* Upload Button */
.upload-btn {
  /*margin-top: 15px;*/
  padding: 6px;
  background: #6c757d;
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: not-allowed;
  font-size: 13px;
  transition: background 0.3s ease, transform 0.3s ease;
}

/* Active (enabled) state */
.upload-btn.active {
  background: #388E71;
  cursor: pointer;
}

.upload-btn.active:hover {
  background: #2e735c;
  transform: scale(1.05); /* Slightly zooms in */
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

</style>


<?php include 'includes/footer.php'; ?>
<!-- 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: 2, responsivePriority: 1 }, // Names always visible
        { targets: 5, responsivePriority: 1 }, // Roles always visible
        { targets: 2, responsivePriority: 4 }, // S/N less important
        { targets: 3, responsivePriority: 3 }, // Email may hide on small screens
        { targets: -1, responsivePriority: 2 }, // Action visible after roles
      ],
      paging: true,
      searching: true,
      "deferRender": true,
      info: true
    });

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

</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 student 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';?>

<script>
    const excelInput = document.getElementById("excelFile");
    const fileNameDisplay = document.getElementById("fileName");
    const uploadBtn = document.getElementById("uploadBtn");

    excelInput.addEventListener("change", function () {
      if (this.files.length > 0) {
        fileNameDisplay.textContent = this.files[0].name;
        uploadBtn.disabled = false;
        uploadBtn.classList.add("active");
      } else {
        fileNameDisplay.textContent = "Choose Excel File";
        uploadBtn.disabled = true;
        uploadBtn.classList.remove("active");
      }
    });
</script>

<!-- Table to Excel -->
<script>
    function exportTableToExcel(){
        TableToExcel.convert(document.getElementById("tblData"));
    }
</script>
<script type="text/javascript" src="tableToExcel/dist/tableToExcel.js"></script>