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

.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>
<style>
.package-box {
  background: #fff;
  border-radius: 10px;
  padding: 25px;
  transition: all 0.3s ease;
  box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}
.package-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0,0,0,0.15);
}
#basic{
    border-left: 1px solid blue;
    border-top: 1px solid blue;
}
#junior{
    border-left: 1px solid #157347;
    border-top: 1px solid #157347;
}
#senior{
    border-right: 1px solid #255f91;
    border-top: 1px solid #255f91;
}
.the-text-info{
    color: #255f91;
}
.package-header {
  font-weight: bold;
  text-align: center;
  font-size: 1.2rem;
  margin-bottom: 15px;
}
.package-price {
  text-align: center;
  font-size: 1.5rem;
  color: #007bff;
  font-weight: 600;
  margin-bottom: 15px;
}
.package-items li {
  padding: 6px 0;
  border-bottom: 1px solid #eee;
}
.package-items li{
    display: flex; 
    align-items: center; 
    justify-content: space-between;
}
</style>
<?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 style="font-size: 13px;"> Payment Packages <i class="fa fa-wallet"></i> | </h5>
                <div>
                    <button class="btn btn-sm info text-white" onclick="openModal('modal-add')">
                        <i class="fa fa-plus-circle"></i> Add Package
                    </button>

                    <button class="btn btn-sm success text-white" 
                        onclick="openModal('modal-search')">
                       <i class="fa fa-credit-card"></i> Add Payment
                    </button>

                    <!-- <button class="btn btn-sm success text-white" onclick="handleDelete()">
                       Activate <i class="fa fa-check-circle"></i>
                    </button> -->
                </div>
            </div>

            <div class="card mt-3">
               <div class="card-header text-left">
                   <h5 style="font-size: 15px;">DE GOODNESS PAYMENT PACKAGES</h5>
               </div>
                <div class="card-body">
                    <div class="container mt-2">
                      <div class="row justify-content-center g-4">
                        
                        <!-- Basic -->
                        <div class="col-md-4">
                          <div class="package-box" id="basic">
                            <div class="package-header text-primary" style="border-bottom: 1px solid #ccc; font-weight: bold;">
                                <i class="fa fa-seedling"></i>Basic 1-5 Package
                            </div>
                            <!-- <div class="package-price">₦10,000</div> -->
                            <ul class="list-unstyled package-items">
                                <?php
                                $fetch1 = 'Basic';
                                $callBasic = "SELECT items, price FROM packages 
                                            WHERE package_name = ?";
                                $basicStmt = $pdo->prepare($callBasic);
                                $basicStmt->execute([$fetch1]);
                                $totalBasic = $basicStmt->rowCount();
                                
                                // get total payment
                                $basicPay = "SELECT SUM(price) AS totalPrice
                                            FROM packages WHERE package_name = ?";
                                $payStmt = $pdo->prepare($basicPay);
                                $payStmt->execute([$fetch1]);

                                $payRow = $payStmt->fetch(PDO::FETCH_ASSOC);
                                $totalBasicPay = $payRow['totalPrice'];

                                while ($basicRow = $basicStmt->fetch(PDO::FETCH_ASSOC)) {
                                    $dataItems = $basicRow['items'];
                                    $dataPrice = $basicRow['price'];
                                ?>
                              <li>
                                <div><i class="fa fa-check text-primary"></i>
                                    <label><?=$dataItems?></label>
                                </div>
                                <div><span>₦<?php echo number_format($dataPrice, 2);?></span></div>
                             </li>
                              <?php } ?>
                            </ul>
                            <div class="text-center mt-3">
                                <button class="btn btn-primary btn-sm">
                                    Total: ₦<?php echo number_format($totalBasicPay, 2);?>
                                </button>
                              <small>All Packages: <?=$totalBasic?></small>
                            </div>
                          </div>
                        </div>

                        <!-- Junior -->
                        <div class="col-md-4">
                          <div class="package-box" id="junior">
                            <div class="package-header text-success" 
                                style="border-bottom: 1px solid #ccc; 
                                font-weight: bold;">
                                <i class="fa fa-user-graduate"></i> Junior Package
                            </div>
                            <ul class="list-unstyled package-items">
                                <?php
                                $fetch2 = 'Junior';
                                $callJunior = "SELECT items, price FROM packages 
                                            WHERE package_name = ?";
                                $juniorStmt = $pdo->prepare($callJunior);
                                $juniorStmt->execute([$fetch2]);
                                $totalJunior = $juniorStmt->rowCount();
                                
                                // get total payment
                                $juniorPay = "SELECT SUM(price) AS totalPrice
                                            FROM packages WHERE package_name = ?";
                                $payStmt = $pdo->prepare($juniorPay);
                                $payStmt->execute([$fetch2]);
                                
                                $payRow = $payStmt->fetch(PDO::FETCH_ASSOC);
                                $totalJuniorPay = $payRow['totalPrice'];

                                while ($juniorRow = $juniorStmt->fetch(PDO::FETCH_ASSOC)) {
                                    $dataItems = $juniorRow['items'];
                                    $dataPrice = $juniorRow['price'];
                                ?>
                               <li>
                                 <div><i class="fa fa-check-square text-success"></i>
                                     <label><?=$dataItems?></label>
                                 </div>
                                 <div><span>₦<?php echo number_format($dataPrice, 2);?></span>
                                 </div>
                              </li>
                              <?php } ?>
                            </ul>
                            <div class="text-center mt-3">
                                <button class="btn btn-success btn-sm">
                                    Total: ₦<?php echo number_format($totalJuniorPay, 2);?>
                                </button>
                              <small>All Packages: <?=$totalJunior?></small>
                            </div>
                          </div>
                        </div>

                        <!-- Senior -->
                        <div class="col-md-4">
                          <div class="package-box" id="senior">
                            <div class="package-header the-text-info" 
                                style="border-bottom: 1px solid #ccc; 
                                font-weight: bold;">
                                <i class="fa fa-layer-group"></i> Senior Package
                            </div>
                            <ul class="list-unstyled package-items">
                                <?php
                                $fetch3 = 'Senior';
                                $callSenior = "SELECT items, price FROM packages 
                                            WHERE package_name = ?";
                                $seniorStmt = $pdo->prepare($callSenior);
                                $seniorStmt->execute([$fetch3]);
                                $totalSenior = $seniorStmt->rowCount();
                                
                                // get total payment
                                $seniorPay = "SELECT SUM(price) AS totalPrice
                                            FROM packages WHERE package_name = ?";
                                $payStmt = $pdo->prepare($seniorPay);
                                $payStmt->execute([$fetch3]);
                                
                                $payRow = $payStmt->fetch(PDO::FETCH_ASSOC);
                                $totalSeniorPay = $payRow['totalPrice'];

                                while ($seniorRow = $seniorStmt->fetch(PDO::FETCH_ASSOC)) {
                                    $dataItems = $seniorRow['items'];
                                    $dataPrice = $seniorRow['price'];
                                ?>
                               <li>
                                 <div><i class="fa fa-check-circle the-text-info"></i>
                                     <label><?=$dataItems?></label>
                                 </div>
                                 <div><span>₦<?php echo number_format($dataPrice, 2);?></span>
                                 </div>
                              </li>
                              <?php } ?>
                              
                            </ul>
                            <div class="text-center mt-3">
                                <small>All Packages: <?=$totalSenior?></small><br>
                                <button class="btn info text-white btn-sm">
                                    Total: ₦<?php echo number_format($totalSeniorPay, 2);?>
                                </button>
                            </div>
                          </div>
                        </div>

                      </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Add Modal -->
        <div id="modal-add" class="modal">
            <div class="modal-content" style="margin-top:50px;">
                <div class="modal-header">Add New Package 
                    <i class="fa fa-plus-circle"></i>
                </div>
                <div class="modal-body">
                    <form action="" method="POST">
                        <div class="single-input">
                            <label>Item Name</label>
                            <div class="my-input">
                                <input type="text" required="" autocomplete="off" name="items" placeholder="Enter Item names">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-6 mt-4">
                                <label>Select Package</label>
                                <div class="my-input">
                                    <select name="package">
                                        <option hidden="">Select Package</option>
                                        <option value="Basic">Basic Package</option>
                                        <option value="Junior">Junior Package</option>
                                        <option value="Senior">Senior Package</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-lg-6 mt-4">
                                <label>Amount 
                                    <del class="text-danger">[₦]</del> 
                                    <small>Amount only</small>
                                </label>
                                <div class="my-input">
                                    <input type="text" required="" 
                                    id="priceInput" 
                                    autocomplete="off" name="price" placeholder="Amount">
                                </div>
                            </div>
                        </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>
                            <!-- Add product button -->
                            <button name="add-package" 
                                class="btn btn-success btn-sm">Add Package 
                                <i class="fa fa-plus-circle"></i>
                            </button>
                        </div>
                        
                    </form>
                </div>
                
            </div>
        </div>
   
    </div>
</div>

<!-- Add Payment Modal -->
<div id="modal-search" class="modal">
    <div class="modal-content" style="margin-top:50px; transition: height 0.5s ease-in">
        <div class="modal-header">Add Payment 
            <i class="fa fa-plus-circle"></i>
        </div>
        <div class="modal-body">
            <form action="" method="POST">
                <div class="single-input">
                    <label>Enter to search</label>
                    <div class="my-input">
                        <input type="text" 
                        autofocus="" 
                        required="" 
                        id="searchInput"
                        autocomplete="off" 
                        name="studId" 
                        placeholder="Student ID or Names"
                        onkeyup="searchStudent(this.value)">
                    </div>
                    <div id="suggestionsBox" class="suggestions"></div>
                </div>
                

                <div class="modal-footer mt-4">
                    <button type="button" class="btn btn-danger btn-sm" 
                        onclick="closeModal('modal-search')">
                        Cancel <i class="fa fa-cancel"></i> &times;
                    </button>
                    <!-- Add product button -->
                    <button name="cont-btn" 
                        class="btn btn-success btn-sm">Continue 
                        <i class="fa fa-play-circle"></i>
                    </button>
                </div>
                
            </form>
        </div>
        
    </div>
</div>

<?php
if (isset($_POST['cont-btn'])) {
    $studId = $_POST['studId'];
    $_SESSION['payStudId'] = $studId;
    header("Location:pay.php");
} 
if (isset($_POST['add-package'])) {
    $items = $_POST['items'];
    $package = $_POST['package'];
    $price  = str_replace(',', '', $_POST['price']);

    if (empty($package)) {
        $_SESSION['message'] = 'All fields are required';
        $_SESSION['type'] = 'error';
    }else{
        // Query begins here
        // validate query
        $validateSql = "SELECT * FROM packages WHERE package_name = ? 
                    AND items = ? AND session = ? AND term = ?";
        $validateStmt = $pdo->prepare($validateSql);
        $validateStmt->execute([$package, $items, $current_session, $current_term]);
        $countPaks = $validateStmt->rowCount();
        if ($countPaks == TRUE) {
            $_SESSION['message'] = 'Package already exist';
            $_SESSION['type'] = 'error';
        }else{
            // Add new package
            $insertPackage = "INSERT INTO packages (package_name, items, price, session, term)VALUES(?,?,?,?,?)";
            $packaStmt = $pdo->prepare($insertPackage);
            $packaStmt->execute([$package, $items, $price, $current_session, $current_term]);
            $_SESSION['message'] = 'Package added successfully';
            $_SESSION['type'] = 'success';?>
            <script type="text/javascript">
              setTimeout("location.href='javascript:history.back()';", 2000);
            </script>
            <?php 
        }
    }
}

?>
<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;
    }
</style>

<?php
if (isset($_POST['add-session'])) {
    $new_session   = $_POST['new_session'];
    // valiate session year
    $valis = "SELECT session_year FROM sessions WHERE session_year = ?";
    $valiStmt = $pdo->prepare($valis);
    $valiStmt->execute([$new_session]);
    $validate = $valiStmt->rowCount();
    if ($validate == TRUE) {
        $_SESSION['message'] = 'Session Year already exist.';
        $_SESSION['type'] = 'error';
        
    }else{

    $status         = 'inactive';
    $insert = "INSERT INTO sessions(session_year, status) VALUES(?, ?)";
    $insertpdo = $pdo->prepare($insert);
    $insertpdo->execute([$new_session, $status]);
        
        $_SESSION['message'] = 'Session Added Successfully.';
        $_SESSION['type'] = 'success';

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


}
?>
<style>
.suggestions {
  /*position: absolute;*/
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #ddd;
  border-radius: 5px;
  z-index: 9999;
  max-height: 200px;
  overflow-y: auto;
  display: none;
}
.suggestion-item {
  padding: 10px;
  cursor: pointer;
}
.suggestion-item:hover {
  background: #f5f5f5;
}
</style>


<?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>
  // Fomart Price input
document.getElementById('priceInput').addEventListener('input', function(e) {
    // Remove all non-numeric characters
    let value = e.target.value.replace(/[^0-9]/g, '');
    
    // Format with commas
    e.target.value = new Intl.NumberFormat().format(value);
});
</script>
<script>
function searchStudent(query) {
  let box = document.getElementById("suggestionsBox");

  if (query.length < 2) {
    box.style.display = "none";
    return;
  }

  let xhr = new XMLHttpRequest();
  xhr.open("POST", "searchStudent.php", true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.onload = function () {
    if (this.status == 200) {
      box.innerHTML = this.responseText;
      box.style.display = "block";
    }
  };
  xhr.send("query=" + encodeURIComponent(query));
}

function selectStudent(value) {
  document.getElementById("searchInput").value = value;
  document.getElementById("suggestionsBox").style.display = "none";
}
</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";
    }

   
</script>

<script>
    

    function handleDelete() {
        const selected = document.querySelector("input[name='sessionYear']:checked");
        if (!selected) {
            showCustomAlert("Please select a session year to activate.");
            return;
        }

        const selectedYear = selected.getAttribute("data-session");
        document.getElementById("sessionConfirmText").textContent = 
            `Are you sure you want to change the session year to ${selectedYear}?`;
        
        openModal('modal-delete');
    }

    // Custom alert modal (optional but better UX)
    function showCustomAlert(message) {
        const alertBox = document.createElement('div');
        alertBox.style.position = 'fixed';
        alertBox.style.top = '20px';
        alertBox.style.left = '50%';
        alertBox.style.transform = 'translateX(-50%)';
        alertBox.style.background = '#C74628';
        alertBox.style.color = '#fff';
        alertBox.style.padding = '15px 25px';
        alertBox.style.borderRadius = '5px';
        alertBox.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)';
        alertBox.style.zIndex = '10000';
        alertBox.textContent = message;

        document.body.appendChild(alertBox);
        setTimeout(() => {
            alertBox.remove();
        }, 3000);
    }
</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: 45px;
        border-radius: 7px;
        padding: 15px;
        text-align: left;
       /* height: 20px;*/
    }
    .my-input select{
        width: 100%;
        border:2px solid #ccc;
        outline: none;
        font-size: 16px;
        color: 888;
        height: 45px;
        border-radius: 7px;
        padding: 10px;
       /* height: 20px;*/
    }
</style>

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

