<?php
     session_start();
      include 'database/shikanisha.kts.php';
        if(!($_SESSION['type'] == 'Manager' || $_SESSION['type'] == 'Cashier' || $_SESSION['type'] == 'Receptionist' || $_SESSION['type'] == 'Waiter')){
            header("location:logout.php");
}


?>

<!DOCTYPE html>
<html  lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Jacyjoka</title>
    <!-- Favicon icon -->
    <link rel="icon" type="./quixlab/image/png" sizes="16x16" href="./quixlab/images/favicon.png">
    <!-- Pignose Calender -->
    <link href="./quixlab/plugins/pg-calendar/css/pignose.calendar.min.css" rel="stylesheet">
    <!-- Chartist -->
    <link rel="stylesheet" href="./quixlab/plugins/chartist/css/chartist.min.css">
    <link rel="stylesheet" href="./quixlab/plugins/chartist-plugin-tooltips/css/chartist-plugin-tooltip.css">
    <!-- Custom Stylesheet -->
    <link href="./quixlab/css/design.css" rel="stylesheet">
    <link href="./quixlab/plugins/toastr/css/toastr.min.css" rel="stylesheet">
    <!-- DataTables with Buttons -->
    <link rel="stylesheet" href="./quixlab/plugins/tables/css/datatable/dataTables.bootstrap4.min.css">
    <link href="./quixlab/plugins/tables/css/datatable/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="./quixlab/css/buttons.bootstrap.min.css" rel="stylesheet" />

</head>

<body>

    <!--*******************
        Preloader start
    ********************-->
    <div id="preloader">
        <div class="loader">
            <svg class="circular" viewBox="25 25 50 50">
                <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="3" stroke-miterlimit="10" />
            </svg>
        </div>
    </div>
    <!--*******************
        Preloader end
    ********************-->

    
    <!--**********************************
        Main wrapper start
    ***********************************-->
    <div id="main-wrapper">

        <!--**********************************
            Nav header start
        ***********************************-->
        <div class="nav-header">
            <div class="brand-logo" style="background-image: url('./quixlab/images/room.png');">
                
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header start
        ***********************************-->
        <div class="header">    
            <div class="header-content clearfix">
                
                <div class="nav-control">
                    <div class="hamburger">
                        <span class="toggle-icon"><i class="icon-menu"></i></span>
                    </div>
                </div>
                <div class="header-left">
                   
                </div>
                <div class="header-right">
                    <ul class="clearfix">
                        
                        <li class="icons dropdown d-none d-md-flex"><a href="javascript:void(0)" id="storecart">
                                <i class="fa fa-money">+</i>
                               
                            </a>
                        </li>
                        
                    </ul>
                </div>
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header start
        ***********************************-->
    <?php


// Define arrays for each user role and the corresponding allowed links
$managerLinks = array(
    "orders.php", 
    "payments.php", 
    "reports.php", 
    "purchases.php", 
    "expense.php", 
    "employee.php", 
    "inventory.php"
);

$cashierLinks = array(
    "orders.php", 
    "swimming.php", 
    "payments.php"
);

$receptionistLinks = array(
    "orders.php", 
    "payments.php", 
    "swimming.php", 
    "reg-customer.php"
);

// Check if user is logged in and their role is set in the session
if(isset($_SESSION['type'])) {
    $role = $_SESSION['type'];
    
    // Assign the corresponding links based on the user role
    switch($role) {
        case "Manager":
            $links = $managerLinks;
            break;
        case "Cashier":
            $links = $cashierLinks;
            break;
        case "Receptionist":
            $links = $receptionistLinks;
            break;
        default:
            $links = array();
            break;
    }
} else {
    // Redirect user to login page if they are not logged in
    header("Location: login.php");
    exit();
}

?>

<div class="nk-sidebar">           
    <div class="nk-nav-scroll">
        <ul class="metismenu" id="menu">
            <li class="nav-label">Dashboard</li>
            <li>
                <a class="has-arrow" href="javascript:void()" aria-expanded="false">
                    <i class="icon-speedometer menu-icon"></i><span class="nav-text">Dashboard</span>
                </a>
                <ul aria-expanded="false">
                    <li><a href="index.php">Dashboard</a></li>
                    <!-- <li><a href="./index-2.html">Home 2</a></li> -->
                </ul>
            </li>
            <?php 
               foreach($links as $link) {
    $linkText = ucfirst(str_replace(".php", "", $link)); // remove .php extension and capitalize first letter
    echo '<li><a href="' . $link . '"><i class="icon-menu menu-icon"></i><span class="nav-text">' . $linkText . '</span></a></li>';
}

            ?>
            <li>
                <a href="logout.php" aria-expanded="false">
                    <i class="icon-lock menu-icon"></i><span class="nav-text">LogOut</span>
                </a>
            </li>
        </ul>
    </div>
</div> 
        <!--**********************************
            Sidebar end
        ***********************************-->

        <!--**********************************
            Content body start
        ***********************************-->
        <div class="content-body">

            
            <!-- row -->
            <div class="modal fade" id="bookSession">
                  <div class="modal-dialog" role="document">
                    <div class="modal-content">
                      <div class="card">
                       <div class="card-body pb-0 d-flex justify-content-between">
                            <form id="booksess" onsubmit="submitFormz(event)">
                                <div class="form-group">
                                    <label for="age_status">Age Group:</label>
                                    <select class="form-control" name="age_status" onchange="fetchCost()" required>
                                        <option selected disabled>Select Age group</option>
                                        <option>Adults</option>
                                        <option>Teenagers</option>
                                        <option>Kids</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label for="amount">Cost Amount:</label>
                                    <input type="number" class="form-control" name="amount" placeholder="Enter Cost Amount" required readonly/>
                                </div>

                                <div class="form-group">
                                    <label for="amount">Number of Persons:</label>
                                    <input type="number" class="form-control" name="count" placeholder="Enter Number of Persons" required oninput="calculateTotalCost()"/>
                                </div>

                                <div class="form-group">
                                    <label for="amount">Total Cost Amount:</label>
                                    <input type="number" class="form-control" name="totamount" placeholder="Total Cost Amount" required readonly/>
                                </div>

                                <button class="btn btn-info" type="submit">Start Session</button>
                                &nbsp;
                            </form>
                           </div>
                          </div>
                        </div>
                      </div>
                  </div>
                  
                   <div class="modal fade" id="createSession">
                  <div class="modal-dialog" role="document">
                    <div class="modal-content">
                      <div class="card">
                       <div class="card-body pb-0 d-flex justify-content-between">
                               <form id="swimsession">
                                  <div class="form-group">
                                      <select class="form-control" name="age_group" required>
                                          <option selected disabled>Select Age group</option>
                                          <option>Adults</option>
                                          <option>Teenagers</option>
                                          <option>Kids</option>
                                      </select>
                                  </div>

                                  <div class="form-group">
                                      <input type="number" class="form-control" name="cost" placeholder="Session Cost" required/>
                                  </div>

                                  <button class="btn btn-info" type="button" onclick="submitForm()">Create Session</button>
                                  &nbsp;
                              </form>
                           </div>
                          </div>
                        </div>
                      </div>
                  </div>
                  
                  
           <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-6 col-sm-6">
                      <div class="card gradient-2" 
                       data-toggle="modal" data-target="#bookSession">
                        <div class="card-body">
                          <h3 class="card-title text-white"></h3>
                          <div class="d-inline-block">
                            <h2 class="text-white">Book Swimming Session</h2>
                            <p class="text-white mb-0"></p>
                          </div>
                          <span class="float-right display-5 opacity-5"><i class="fa fa-shopping-cart"></i></span>
                        </div>
                      </div>
                    </div>
                  <div class="col-lg-6 col-sm-6">
                      <div class="card gradient-1" 
                       data-toggle="modal" data-target="#createSession">
                        <div class="card-body">
                          <h3 class="card-title text-white"></h3>
                          <div class="d-inline-block">
                            <h2 class="text-white">Create Swimming Session</h2>
                            <p class="text-white mb-0"></p>
                          </div>
                          <span class="float-right display-5 opacity-5"><i class="fa fa-shopping-cart"></i></span>
                        </div>
                      </div>
                    </div>

                   
                  
                 <!-- end of row -->
                  </div>
               
                <div class="row">
               
                    <div class="col-12">
                        <div class="card">
                          <div class="card-body pb-0 d-flex justify-content-between">
                                       
                                        <div>
                                            <h4 class="card-title">Swimming Session Report</h4>
                                           
                                        </div>
                                        
                                    </div>
                          
                            <div class="card-body">
                               
                               
                               <div class="table-responsive">
                                 <table id="swimming_report" class="table table-striped table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Session Id</th>
                                            <th>Age Group</th>
                                            <th>Cost</th>
                                            <th>No Of Persons</th>
                                            <th>Total Cost</th>
                                            <th>Date</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>

                                </div>
                             </div>
                        </div>
                    </div>
                </div>
                
                   <div class="row">
               
                    <div class="col-12">
                        <div class="card">
                          <div class="card-body pb-0 d-flex justify-content-between">
                                       
                                        <div>
                                            <h4 class="card-title">Swimming Session Report</h4>
                                           
                                        </div>
                                        
                                    </div>
                          
                            <div class="card-body">
                               
                               
                               <div class="table-responsive">
                                 <table id="swimming_sessions" class="table table-striped table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Session Id</th>
                                            <th>Age Group</th>
                                            <th>Cost</th>
                                           
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>

                                </div>
                             </div>
                        </div>
                    </div>
                </div>
                
                
                  <div class="row">
    <div class="col-lg-12 col-sm-12">
        <div class="card">
          <div class="card-body">
        <h4 class="card-title">Swimming Detailed Report</h4>
        <!-- Items Report Form -->
        <form id="expenseReportForm">
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="start_date">Start Date:</label>
                        <input type="datetime-local" class="form-control" id="start_date" name="start_date" required>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="end_date">End Date:</label>
                        <input type="datetime-local" class="form-control" id="end_date" name="end_date" required>
                    </div>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <button type="button" class="btn btn-primary" onclick="generateReport()">Generate Report</button>
                </div>
            </div>
        </form>

        <!-- Items Report Table -->
        <div class="active-member">
            <div class="table-responsive">
                <table id="expenseTable" class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>Expense ID</th>
                            <th>Name</th>
                            <th>Date</th>
                            <th>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be inserted here by AJAX -->
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3"></td>
                            <td><b><i>Total Amount: Ksh<span id="totalExpense">0.00</span></i></b></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
          </div>
                 </div>
          </div>
       </div>
<!-- Add this modal at the end of your HTML body -->
<div class="modal" id="updateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Session Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- Form for updating the cost -->
                <form id="updateForm">
                    <div class="form-group">
                        <label for="updateCost">Updated Cost:</label>
                        <input type="number" class="form-control" id="updateCost" name="updateCost" required/>
                    </div>
                    <button type="submit" class="btn btn-primary">Update Cost</button>
                </form>
            </div>
        </div>
    </div>
</div>

    <!-- Modal -->
          <div class="modal fade" id="addExpenseTypeModal" tabindex="-1" role="dialog" aria-labelledby="addExpenseTypeModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
             <div class="container"></div>
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="addExpenseTypeModalLabel">Add Expense Type</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>
                <div class="modal-body">
                  <form id="addExpenseTypeForm">
                    <div class="form-group">
                      <label for="name">Name:</label>
                      <input type="text" class="form-control" id="name" name="name" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                  </form>
                </div>
              </div>
            </div>
          </div>

   <!-- Modal -->
            <!-- #/ container -->
        </div>
        <!--**********************************
            Content body end
        ***********************************-->
        
  </div>
        <!--**********************************
            Footer start
        ***********************************-->
        <div class="footer">
            <div class="copyright">
                <p>Copyright &copy; Designed & Developed by <a href="https://themeforest.net/user/quixlab">Quixlab</a> 2018</p>
            </div>
        </div>
        <!--**********************************
            Footer end
        ***********************************-->

    
   
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="./quixlab/plugins/common/common.min.js"></script>
    <script src="./quixlab/js/custom.min.js"></script>
    <script src="./quixlab/js/settings.js"></script>
    <script src="./quixlab/js/gleek.js"></script>
    <script src="./quixlab/js/styleSwitcher.js"></script>
    <script src="./quixlab/plugins/toastr/js/toastr.min.js"></script>
    <script src="./quixlab/plugins/toastr/js/toastr.init.js"></script>
    <!-- Chartjs -->
    <script src="./quixlab/plugins/chart.js/Chart.bundle.min.js"></script>
    <!-- Circle progress -->
    <script src="./quixlab/plugins/circle-progress/circle-progress.min.js"></script>
    <!-- Datamap -->
    <script src="./quixlab/plugins/d3v3/index.js"></script>
    <script src="./quixlab/plugins/topojson/topojson.min.js"></script>
    <script src="./quixlab/plugins/datamaps/datamaps.world.min.js"></script>
    <!-- Morrisjs -->
    <script src="./quixlab/plugins/raphael/raphael.min.js"></script>
    <script src="./quixlab/plugins/morris/morris.min.js"></script>
    <!-- Pignose Calender -->
    <script src="./quixlab/plugins/moment/moment.min.js"></script>
    <script src="./quixlab/plugins/pg-calendar/js/pignose.calendar.min.js"></script>
    <!-- ChartistJS -->
    <script src="./quixlab/plugins/chartist/js/chartist.min.js"></script>
    <script src="./quixlab/plugins/chartist-plugin-tooltips/js/chartist-plugin-tooltip.min.js"></script>
    <script src="./quixlab/js/dashboard/dashboard-1.js"></script>
    <!-- Datatables -->
    <script src="./js/dashboard/dashboard-1.js"></script>
    <script src="./quixlab/plugins/tables/js/jquery.dataTables.min.js"></script>
    <script src="./quixlab/plugins/tables/js/datatable/dataTables.bootstrap4.min.js"></script>
    <script src="./quixlab/plugins/tables/js/datatable-init/datatable-basic.min.js"></script>
    
    <script src="./quixlab/js/data-table/dataTables.buttons.min.js"></script>
    <script src="./quixlab/js/data-table/buttons.flash.min.js"></script>
    <script src="./quixlab/js/data-table/jszip.min.js"></script>
    <script src="./quixlab/js/data-table/pdfmake.min.js"></script>
    <script src="./quixlab/js/data-table/vfs_fonts.js"></script>
    <script src="./quixlab/js/data-table/buttons.html5.min.js"></script>
    <script src="./quixlab/js/data-table/buttons.print.min.js"></script>
    <script src="./quixlab/js/data-table/datatables-init.js"></script>
    <script src="./quixlab/js/swimming.js"></script>
    
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>

   <script>
    $(document).ready(function () {
        // Initialize DataTable
        var table = $('#swimming_sessions').DataTable({
            "ajax": {
                "url": "database/fetch_swimming_sessions.kts.php", // PHP script to fetch data from the server
                "dataSrc": ""
            },
            "columns": [
                { "data": "swimid" },
                { "data": "age_group" },
                { "data": "cost" },
               
                {
                "data": "swimid",
                "render": function (data, type, row) {
                    return '<button class="btn btn-primary" onclick="openUpdateModal(' + data + ')">Change Price</button>';
                }
                }
            ]
        });
    });
     function openUpdateModal(sessionId) {
    // Make an AJAX request to fetch session details based on the session ID
    $.ajax({
        url: 'database/fetch_swimo_details.kts.php',
        type: 'POST',
        data: { session_id: sessionId },
        success: function (response) {
            if (response.success) {
                // Update the modal content with fetched details
                $('#updateCost').val(response.cost);

                // Show the modal
                $('#updateModal').modal('show');

                // Handle form submission for updating cost
                $('#updateForm').on('submit', function (event) {
                    event.preventDefault();
                    updateCost(sessionId);
                });
            } else {
                alert('Error fetching session details');
            }
        },
        error: function (xhr, status, error) {
            console.error(xhr.responseText);
            alert('Error fetching session details');
        }
    });
}

function updateCost(sessionId) {
    var updatedCost = $('#updateCost').val();

    // Make an AJAX request to update the cost
    $.ajax({
        url: 'database/update_cost.kts.php',
        type: 'POST',
        data: { session_id: sessionId, updated_cost: updatedCost },
        success: function (response) {
            if (response.success) {
                // Close the modal after successful update
                $('#updateModal').modal('hide');

                // Reload the DataTable after successful update
                location.reload();
            } else {
                alert('Error updating cost');
            }
        },
        error: function (xhr, status, error) {
            console.error(xhr.responseText);
            alert('Error updating cost');
        }
    });
}
  </script>
<script>
    $(document).ready(function () {
        // Initialize DataTable
        var table = $('#swimming_report').DataTable({
            "ajax": {
                "url": "database/fetch_swimming_data.kts.php", // PHP script to fetch data from the server
                "dataSrc": ""
            },
            "columns": [
                { "data": "swimo_id" },
                { "data": "age_group" },
                { "data": "cost" },
                { "data": "no_persons" },
                { "data": "total_cost" },
                { "data": "date_column" },
                {
                    "data": "swimo_id",
                    "render": function (data, type, row) {
                        return '<button class="btn btn-danger" onclick="deleteSession(' + data + ')">Delete</button>';
                    }
                }
            ]
        });
    });

    // Function to delete a session
function deleteSession(sessionId) {
    Swal.fire({
        title: 'Are you sure?',
        text: 'You are about to delete this session!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            // Make AJAX request to delete session
            $.ajax({
                url: 'database/delete_session.kts.php',
                type: 'POST',
                data: { session_id: sessionId },
                                dataType: 'json', // Expect JSON response

                success: function (response) {
                    // Check if the response is a success
                    if (response && response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Session Deleted Successfully!',
                            showConfirmButton: false,
                            timer: 1500
                        }).then(() => {
                            // Reload the DataTable after successful deletion
                            $('#swimming_report').DataTable().ajax.reload();
                        });
                    } else {
                        // Display the server response message in case of failure
                        Swal.fire({
                            icon: 'error',
                            title: 'Oops...',
                            text: response.message || 'Error deleting session!',
                        });
                    }
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseText);
                    // Display a generic error message for AJAX failure
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'Error deleting session!',
                    });
                }
            });
        }
    });
}




</script>


   <script>
  function submitForm() {
    // Fetch form data
    var form = document.getElementById("swimsession");
    var formData = new FormData(form);

    // Make AJAX request to submit form data
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "database/submit_form.kts.php", true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            // Handle the response
            handleResponse(xhr.responseText);
        }
    };
    xhr.send(formData);
}

function handleResponse(response) {
    // Parse the JSON response
    var result = JSON.parse(response);

    // Display SweetAlert based on the response
    if (result.success) {
        Swal.fire({
            icon: 'success',
            title: 'Session Created Successfully!',
            showConfirmButton: false,
            timer: 1500
        });
        location.reload();
    } else {
        Swal.fire({
            icon: 'error',
            title: 'Oops...',
            text: result.message || 'Something went wrong!',  // Display the server's error message, if available
        });
    }
}
</script>
<!-- Add this script block to your HTML file -->

<script>
    function fetchCost() {
        var ageStatusSelect = document.querySelector("[name='age_status']");
        var amountInput = document.querySelector("[name='amount']");
        var selectedAgeGroup = ageStatusSelect.value;

        // Make AJAX request to fetch cost based on selected age group
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "database/fetch_cost.kts.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // Handle the response
                var result = JSON.parse(xhr.responseText);
                if (result.success) {
                    // Populate the amount input field with the fetched cost
                    amountInput.value = result.cost;
                } else {
                    // Handle error or set a default value
                    amountInput.value = ""; // You can set a default value or handle errors accordingly
                }
            }
        };
        xhr.send("age_group=" + selectedAgeGroup);
    }
</script>


<script>
    function calculateTotalCost() {
        var countInput = document.querySelector("[name='count']");
        var amountInput = document.querySelector("[name='amount']");
        var totamountInput = document.querySelector("[name='totamount']");

        var count = parseFloat(countInput.value) || 0;
        var costAmount = parseFloat(amountInput.value) || 0;

        var totalCost = count * costAmount;

        totamountInput.value = totalCost.toFixed(2);
    }
</script>
    <!--**********************************
        Scripts
    ***********************************-->
<script>
    function submitFormz(event) {
        event.preventDefault(); // Prevent the form from submitting in the traditional way

        var form = document.getElementById("booksess");
        var formData = new FormData(form);

        // Make AJAX request to submit form data
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "database/swim.kts.php", true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // Handle the response
                handleResponse(xhr.responseText);
            }
        };
        xhr.send(formData);
    }

    function handleResponse(response) {
        var result = JSON.parse(response);

        // Display SweetAlert based on the server's response
        if (result.success) {
            Swal.fire({
                icon: 'success',
                title: 'Session Started Successfully!',
                showConfirmButton: false,
                timer: 1500
            });
            // Optionally, you can redirect or perform other actions upon success
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: 'Something went wrong!',
            });
        }
    }
</script>

<script>
   $('#storecart').click(function(){
    $('#shopite').modal();
  })    
 </script>
</body>
</html>