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


?>
<?php 
include 'database/shikanisha.kts.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>THE FARM</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">
    <!-- 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 rel="stylesheet" href="./quixlab/plugins/toastr/css/toastr.min.css" >


</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 class="input-group icons">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-transparent border-0 pr-2 pr-sm-3" id="basic-addon1"><i class="mdi mdi-magnify"></i></span>
                        </div>
                        <input type="search" class="form-control" placeholder="Search Dashboard" aria-label="Search Dashboard">
                        <div class="drop-down animated flipInX d-md-none">
                            <form action="#">
                                <input type="text" class="form-control" placeholder="Search">
                            </form>
                        </div>
                    </div>
                </div>
                <div class="header-right">
                    <ul class="clearfix">
                      
                    </ul>
                </div>
            </div>
        </div>
        <!--**********************************
            Header end ti-comment-alt
        ***********************************-->

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


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

$cashierLinks = array(
    "orders.php", 
    "reg-customer.php", 
    "sales.php"
);

$receptionistLinks = array(
    "orders.php", 
    "reg-customer.php", 
    "payments.php", 
    "sales.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">

            <div class="container-fluid mt-3">
              
                  <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Client Pending Bills</h4>
                                <div class="active-member">
                                    <div class="table-responsive">
                                        <table id="accountTable"  class="table table-xs mb-0 table-bordered">
                                           <thead>
                                                <tr>
                                                    <th>Acc Number</th>
                                                    <th>Client Name</th>
                                                    <th>Phone Number</th>
                                                    <th>Total Debt</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody id="accountTableBody"></tbody>
                                          </table>
                                    </div>
                                </div>
                            </div>
                        </div>                        
                    </div>
                </div>
                   
                   
              <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Clients List</h4>
                                <div class="active-member">
                                    <div class="table-responsive">
                                        <table id="clientsTable"  class="table table-xs mb-0 table-bordered">
                                           <thead>
                                                <tr>
                                                    <th>Reg Code</th>
                                                    <th>Client Name</th>
                                                    <th>Phone Number</th>
                                                    <th>Location</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody id="clientsTableBody"></tbody>
                                          </table>
                                    </div>
                                </div>
                            </div>
                        </div>                        
                    </div>
                </div>
             
                <!-- Payment Modal -->
                
             <div class="modal" id="paymentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Payment Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
             <form id="payments">
            <div class="modal-body">
               
                    <div class="form-group">
                        <label for="modalAccId">Account ID</label>
                        <input type="text" class="form-control" id="modalAccId" name="modalAccId" readonly>
                    </div>
                    <div class="form-group">
                        <label for="paymethod">Payment Method</label>
                        <select class="custom-select browser-default input-rounded" id="paymethod" name="paymethod" required>
                            <option value="">Please select</option>
                            <option value="cash">Cash</option>
                            <option value="till">Till</option>
                            <option value="merchant">Merchant</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="amount">Amount</label>
                        <input type="text" class="form-control" id="amount" name="amount" required>
                    </div>
               
            </div>
             <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Update Payment</button>
            </div>
             </form>
           
        </div>
    </div>
</div>
                
                <!-- end of payment modal -->

            </div>
            <!-- #/ container -->
        </div>
        <!--**********************************
            Content body end
        ***********************************-->
        
        
        <!--**********************************
            Footer start
        ***********************************-->
        <div class="footer">
            <div class="copyright">
                <p>Copyright &copy; Designed & Developed by <a href="https://kakashitech.com">Kakashi Tech</a> 2023</p>
            </div>
        </div>
        <!--**********************************
            Footer end
        ***********************************-->
    </div>
    <!--**********************************
        Main wrapper end
    ***********************************-->

    <!--**********************************
        Scripts
    ***********************************-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.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>

    <!-- 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/plugins/toastr/js/toastr.init.js"></script>
    <script src="./quixlab/plugins/toastr/js/toastr.min.js"></script>


 <script>
  $(document).ready(function() {
  $('#bootstrap-data-table-export').on('click', '.editbtn', function() {
    $('#editmodal').modal('show');

    var $tr = $(this).closest('tr');
    var data = $tr.children("td").map(function() {
      return $(this).text();
    }).get();

    console.log(data);

    $('#loanid').val(data[0]);
  });
});


   </script>
   <script>
$(document).ready(function() {
    $('#doublePaymentBtn').click(function() {
        // Simply toggle the visibility
        if ($('.double-payment-section').is(":visible")) {
            $('.double-payment-section').hide();
        } else {
            $('.double-payment-section').show();
        }
    });

   
});
</script>
   
 <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
<script>
$(document).ready(function() {
    $('#payment_update').submit(function(e) {
        e.preventDefault(); // Prevent the form from submitting the traditional way

        $.ajax({
            type: 'POST',
            url: './database/payment.kts.php', // Replace with the path to your PHP script
            data: $(this).serialize(),
            dataType: 'json', // Expect a JSON response from the server
            success: function(response) {
                if(response.status === 'success') {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: response.message,
                        confirmButtonText: 'OK'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // Optionally redirect or perform another action
                            window.location.reload(); // As an example, reload the page
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message,
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function(xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: 'AJAX Error',
                    text: 'There was an error processing your request: ' + error,
                    confirmButtonText: 'OK'
                });
            }
        });
    });
});
</script>
  
<script>
    // Function to determine the status badge
    function getStatusBadge(amountOwed) {
        if (amountOwed == 0) {
            return '<span class="badge badge-success">Paid</span>';
        } else if (amountOwed > 0) {
            return '<span class="badge badge-warning">Pending</span>';
        } else if (amountOwed < 0) {
            return '<span class="badge badge-danger">Overpayment</span>';
        }
    }

    // Function to display the modal
    function displayModal(accId) {
        // Set the acc_id in the modal input (disabled)
        $('#modalAccId').val(accId);

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

    // Call the fetchData function when the page loads
    $(document).ready(function () {
        // Initialize DataTable with buttons
        var table = $('#accountTable').DataTable({
            dom: 'Bfrtip',
            buttons: ['copyHtml5', 'excelHtml5', 'pdfHtml5'],
            ajax: {
                url: './database/clientdebts.kts.php', // Replace with the actual path to your PHP script
                dataSrc: ''
            },
            columns: [
                { data: 'acc_id' },
                { data: 'full_name' },
                { data: 'phone_number' },
                { data: 'amount_owed' },
                {
                    data: null,
                    render: function (data, type, row) {
                        return getStatusBadge(row.amount_owed);
                    }
                },
                {
                    data: 'acc_id',
                    render: function (data, type, row) {
                        return '<i class="fa fa-money text-success make-payment" data-acc-id="' + row.acc_id + '" style="cursor: pointer;"></i>';
                    }
                }
            ]
        });

        // Handle the click event for the "fa-money" icon
        $('#accountTable').on('click', '.fa-money', function () {
            var accId = $(this).data('acc-id');
            displayModal(accId);
        });
    });
</script>
<script>
    $(document).ready(function () {
        // Function to fetch and display data
        function fetchData() {
            $.ajax({
                url: 'database/fetch_customers.kts.php', // Replace with the actual path to your PHP script
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    // Initialize DataTable with export buttons
                    $('#clientsTable').DataTable({
                        data: data,
                        columns: [
                            { data: 'customer_id' },
                            { data: 'full_name' },
                            { data: 'phone_number' },
                            { data: 'location' },
                            {
                            data: 'customer_id',
                            render: function (data, type, row) {
                                return '<i class="fa fa-trash text-danger delete-client" data-client-id="' + row.customer_id + '" style="cursor: pointer;"></i>';
                            }
                        } // Add action buttons here if needed
                        ],
                        dom: 'Bfrtip',
                        buttons: ['copyHtml5', 'excelHtml5', 'pdfHtml5']
                    });
                },
                error: function (xhr, status, error) {
                    console.error(xhr);
                }
            });
        }

        // Call the fetchData function when the page loads
        fetchData();
      
      
    });
</script>

<script>
    $(document).ready(function () {
        // Function to handle client deletion
        function deleteClient(clientId) {
            $.ajax({
                url: 'database/delete_client.kts.php', // Replace with the actual path to your PHP script
                method: 'POST',
                data: { client_id: clientId },
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        // Success notification using Toastr
                        toastr.success(response.message);
                    } else {
                        // Error notification using Toastr
                        toastr.error(response.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error(xhr);
                }
            });
        }

        // Event listener for delete client button
        $(document).on('click', '.delete-client', function () {
            var clientId = $(this).data('client-id');

            // Show SweetAlert confirmation
            Swal.fire({
                title: 'Are you sure?',
                text: 'All data will be lost, and the process is irreversible!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    // User confirmed, proceed with deletion
                    deleteClient(clientId);
                }
            });
        });
    });
</script>
<script>
$(document).ready(function () {
    // Event listener for form submission
    $('#payments').submit(function (e) {
        e.preventDefault();

        // Get form data
        var formData = $(this).serialize();

        // Make AJAX request to submit form data
        $.ajax({
            url: 'database/submit_payment.kts.php', // Replace with the actual path to your PHP script
            method: 'POST',
            data: formData,
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    // Success notification using Toastr
                    toastr.success(response.message);

                    // Reload the page
                    location.reload();
                } else {
                    // Error notification using Toastr
                    toastr.error(response.message);
                }
            },
            error: function (xhr, status, error) {
                console.error(xhr);
            }
        });
    });
});
  </script>
	
</body>

</html>