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

$userType = isset($_SESSION['type']) ? $_SESSION['type'] : 'Guest'; // Default to 'Guest' or any other value

?>

<!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 id="shopname"></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/css/buttons.bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.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
        ***********************************-->
        

<div class="nk-sidebar">           
    <?php require 'navbar.php'; ?>
</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">My Pending Bills</h4>
                <div class="active-member">
                    <div class="table-responsive">
                        <table class="table table-xs mb-0 " id="pending-bills-table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Seller Name</th>
                                    <th>Total</th>
                                    <th>Paid Amount</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody></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">My Bills Today</h4>
                <div class="active-member">
                    <div class="table-responsive">
                        <table class="table table-xs mb-0 zero-configuration" id="today-bills-table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Seller Name</th>
                                    <th>Total</th>
                                    <th>Paid Amount</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>                        
    </div>
</div>

                
                <!-- Payment Modal -->
                
               <div class="modal fade" id="editmodal" tabindex="-1" aria-labelledby="editmodalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <form id="payment_update">
                <div class="modal-header">
                    <h5 class="modal-title">Update Payment Details</h5>
                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                </div>
                <div class="modal-body">
                    <div class="basic-form">
                        <label>Reference ID</label>
                        <input type="text" id="loanid" name="loanid" class="form-control input-rounded">
                    </div>
                    <div class="basic-form">
                        <label>Payment Amount</label>
                        <input type="number" min="0" id="payamount" name="payamount" class="form-control input-rounded">
                    </div>
                    <div class="basic-form">
                        <label>Payment Mode</label>
                        <select class="custom-select input-rounded" id="paymethod" name="paymethod" required onchange="showHideBookingIdInput()">
                            <option value="">Please select</option>
                            <option value="cash">Cash</option>
                            <option value="till">Till</option>
                            <option value="merchant">Merchant</option>
                            <option value="rooms">Rooms</option>
                        </select>
                    </div>
                    <div class="basic-form" id="bookingIdContainer" style="display: none;">
                        <label>Booking Id</label>
                        <input type="text" id="booking_id" name="booking_id" class="form-control input-rounded">
                    </div>
                    <div class="basic-form">
                        <label>
                            <input type="checkbox" id="addSecondPaymentCheckbox" onchange="showHideSecondPayment()"> Add Second Payment Method
                        </label>
                    </div>
                    <div id="secondPaymentContainer" style="display: none;">
                        <div class="basic-form">
                            <label>Second Payment Amount</label>
                            <input type="number" min="0" id="payamount2" name="payamount2" class="form-control input-rounded">
                        </div>
                        <div class="basic-form">
                            <label>Second Payment Mode</label>
                            <select class="custom-select input-rounded" id="paymethod2" name="paymethod2">
                                <option value="">Please select</option>
                                <option value="cash">Cash</option>
                                <option value="till">Till</option>
                                <option value="merchant">Merchant</option>
                                <option value="rooms">Rooms</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>   
.

<!-- View Items Modal -->
<div class="modal fade" id="viewItemsModal" tabindex="-1" role="dialog" aria-labelledby="viewItemsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="viewItemsModalLabel">Transaction Details</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Transaction ID:</strong> <span id="viewTransId"></span>
                    </div>
                    <div class="col-md-6">
                        <strong>Seller:</strong> <span id="viewSellerName"></span>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Date:</strong> <span id="viewTransDate"></span>
                    </div>
                    <div class="col-md-6">
                        <strong>Status:</strong> <span id="viewTransStatus"></span>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-bordered table-striped table-hover">
                        <thead class="thead-dark">
                            <tr>
                                <th>#</th>
                                <th>Product ID</th>
                                <th>Product Name</th>
                                <th>Category</th>
                                <th>Qty</th>
                                <th>Unit Price</th>
                                <th>Subtotal</th>
                            </tr>
                        </thead>
                        <tbody id="itemsTableBody">
                            <!-- Items will be loaded here by JavaScript -->
                        </tbody>
                        <tfoot>
                            <tr class="table-active">
                                <td colspan="5"></td>
                                <td><strong>Total:</strong></td>
                                <td id="viewTransTotal"></td>
                            </tr>
                            <tr class="table-active">
                                <td colspan="5"></td>
                                <td><strong>Amount Paid:</strong></td>
                                <td id="viewAmountPaid"></td>
                            </tr>
                            <tr class="table-active">
                                <td colspan="5"></td>
                                <td><strong>Balance:</strong></td>
                                <td id="viewBalance"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary print-btn" onclick="printTransaction()">
                    <i class="fa fa-print"></i> Print
                </button>
            </div>
        </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.6.0/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>
    
    <!-- SweetAlert CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.print.min.js"></script>


   
<script>
    function showHideBookingIdInput() {
        var paymethodSelect = document.getElementById("paymethod");
        var bookingIdContainer = document.getElementById("bookingIdContainer");
        var selectedOption = paymethodSelect.options[paymethodSelect.selectedIndex].value;

        if (selectedOption === "rooms") {
            bookingIdContainer.style.display = "block";
        } else {
            bookingIdContainer.style.display = "none";
        }
    }
</script>
 <div class="modal fade" id="editmodal" tabindex="-1" aria-labelledby="editmodalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <form id="payment_update">
                <div class="modal-header">
                    <h5 class="modal-title">Update Payment Details</h5>
                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                </div>
                <div class="modal-body">
                    <div class="basic-form">
                        <label>Reference ID</label>
                        <input type="text" id="loanid" name="loanid" class="form-control input-rounded">
                    </div>
                    <div class="basic-form">
                        <label>Payment Amount</label>
                        <input type="number" min="0" id="payamount" name="payamount" class="form-control input-rounded">
                    </div>
                    <div class="basic-form">
                        <label>Payment Mode</label>
                        <select class="custom-select input-rounded" id="paymethod" name="paymethod" required onchange="showHideBookingIdInput()">
                            <option value="">Please select</option>
                            <option value="cash">Cash</option>
                            <option value="till">Till</option>
                            <option value="merchant">Merchant</option>
                            <option value="rooms">Rooms</option>
                        </select>
                    </div>
                    <div class="basic-form" id="bookingIdContainer" style="display: none;">
                        <label>Booking Id</label>
                        <input type="text" id="booking_id" name="booking_id" class="form-control input-rounded">
                    </div>
                    <div class="basic-form">
                        <label>
                            <input type="checkbox" id="addSecondPaymentCheckbox" onchange="showHideSecondPayment()"> Add Second Payment Method
                        </label>
                    </div>
                    <div id="secondPaymentContainer" style="display: none;">
                        <div class="basic-form">
                            <label>Second Payment Amount</label>
                            <input type="number" min="0" id="payamount2" name="payamount2" class="form-control input-rounded">
                        </div>
                        <div class="basic-form">
                            <label>Second Payment Mode</label>
                            <select class="custom-select input-rounded" id="paymethod2" name="paymethod2">
                                <option value="">Please select</option>
                                <option value="cash">Cash</option>
                                <option value="till">Till</option>
                                <option value="merchant">Merchant</option>
                                <option value="rooms">Rooms</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function showHideBookingIdInput() {
        const paymethod = document.getElementById('paymethod').value;
        const bookingIdContainer = document.getElementById('bookingIdContainer');
        bookingIdContainer.style.display = (paymethod === 'rooms') ? 'block' : 'none';
    }

    function showHideSecondPayment() {
        const secondPaymentContainer = document.getElementById('secondPaymentContainer');
        const addSecondPaymentCheckbox = document.getElementById('addSecondPaymentCheckbox');
        secondPaymentContainer.style.display = addSecondPaymentCheckbox.checked ? 'block' : 'none';
    }

    $(document).ready(function() {
        $('#payment_update').on('submit', function(event) {
            event.preventDefault();

            var formData = $(this).serialize();
            $.ajax({
                url: './database/payment.kts.php',
                type: 'POST',
                data: formData,
                success: function(response) {
                    var jsonResponse = JSON.parse(response);
                    if (jsonResponse.status === 'success') {
                        Swal.fire({
                            title: 'Success!',
                            text: jsonResponse.message,
                            icon: 'success',
                            confirmButtonText: 'OK'
                        }).then(function() {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Error!',
                            text: jsonResponse.message,
                            icon: 'error',
                            confirmButtonText: 'OK'
                        });
                    }
                    $('#payment_update')[0].reset();
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                }
            });
        });
    });
</script>
<script>
$(document).ready(function() {
    var table, todayTable;

    // Initialize DataTables only once
    if (!$.fn.DataTable.isDataTable('#pending-bills-table')) {
        table = $('#pending-bills-table').DataTable({
            paging: true,
            searching: true,
            ordering: true
        });
    } else {
        table = $('#pending-bills-table').DataTable();
    }

    if (!$.fn.DataTable.isDataTable('#today-bills-table')) {
        todayTable = $('#today-bills-table').DataTable({
            paging: true,
            searching: true,
            ordering: true
        });
    } else {
        todayTable = $('#today-bills-table').DataTable();
    }

    // Fetch bills
    fetchPendingBills();
    fetchTodayBills();

    // Event delegation for edit button
    $(document).on('click', '.editbtn', function() {
        var transId = $(this).data('id');
        $('#loanid').val(transId);
        $('#editmodal').modal('show');
    });

    // Event delegation for view button
    $(document).on('click', '.viewbtn', function() {
        var transId = $(this).data('id');
        fetchTransactionItems(transId);
    });

    function fetchPendingBills() {
        $.ajax({
            url: './database/fetch_bills.kts.php',
            type: 'GET',
            data: { type: 'pending' },
            dataType: 'json',
            success: function(data) {
                table.clear();

                data.forEach(function(row) {
                    var buttons = '';
                    var viewButton = '<button class="btn btn-outline-info btn-sm viewbtn mr-1" type="button" data-id="' + row.trans_id + '"><i class="fa fa-eye"></i></button>';
                    
                    <?php if ($userType == 'Manager') { ?>
                        var editButton = '<button class="btn btn-outline-primary btn-sm editbtn" type="button" data-id="' + row.trans_id + '"><i class="fa fa-edit"></i></button>';
                        buttons = viewButton + editButton;
                    <?php } else { ?>
                        buttons = viewButton;
                    <?php } ?>

                    table.row.add([
                        row.trans_id,
                        row.seller_name,
                        row.total,
                        row.amount_received,
                        getStatusBadge(row.amount_received, row.total),
                        row.seller_date,
                        buttons
                    ]);
                });

                table.draw();
            },
            error: function(xhr) {
                console.log('Error fetching pending bills:', xhr.responseText);
            }
        });
    }

    function fetchTodayBills() {
        $.ajax({
            url: './database/fetch_bills.kts.php',
            type: 'GET',
            data: { type: 'today' },
            dataType: 'json',
            success: function(data) {
                todayTable.clear();

                data.forEach(function(row) {
                    var buttons = '';
                    var viewButton = '<button class="btn btn-outline-info btn-sm viewbtn mr-1" type="button" data-id="' + row.trans_id + '"><i class="fa fa-eye"></i></button>';
                    
                <?php if ($userType == 'Manager' || $userType == 'Cashier') { ?>
                        var editButton = '<button class="btn btn-outline-primary btn-sm editbtn" type="button" data-id="' + row.trans_id + '"><i class="fa fa-edit"></i></button>';
                        buttons = viewButton + editButton;
                    <?php } else { ?>
                        buttons = viewButton;
                    <?php } ?>

                    todayTable.row.add([
                        row.trans_id,
                        row.seller_name,
                        row.total,
                        row.amount_received,
                        getStatusBadge(row.amount_received, row.total),
                        row.seller_date,
                        buttons
                    ]);
                });

                todayTable.draw();
            },
            error: function(xhr) {
                console.log('Error fetching today\'s bills:', xhr.responseText);
            }
        });
    }

  function fetchTransactionItems(transId) {
    $.ajax({
        url: './gearbox/fetch_transaction_items.kts.php',
        type: 'GET',
        data: { trans_id: transId },
        dataType: 'json',
        success: function(data) {
            // Check if data is empty or invalid
            if (!data || data.length === 0) {
                console.log('No items found for this transaction');
                alert('No items found for this transaction');
                return;
            }
            
            // Get the first item to show transaction header info
            var firstItem = data[0];
            
            // Update modal header information
            $('#viewTransId').text(firstItem.trans_id);
            
            // Clear and populate items table
            var itemsTable = $('#itemsTableBody');
            itemsTable.empty();
            
            // Calculate totals
            var totalQuantity = 0;
            var totalAmount = 0;
            
            data.forEach(function(item, index) {
                itemsTable.append(
                    '<tr>' +
                    '<td>' + (index + 1) + '</td>' +  // Row number
                    '<td>' + (item.product_id || 'N/A') + '</td>' +
                    '<td>' + (item.product_name || 'N/A') + '</td>' +
                    '<td>' + (item.category || 'N/A') + '</td>' +
                    '<td>' + (item.quantity || '0') + '</td>' +
                    '<td>' + (item.selling_price ? parseFloat(item.selling_price).toFixed(2) : '0.00') + '</td>' +
                    '<td>' + (item.subtotal ? parseFloat(item.subtotal).toFixed(2) : '0.00') + '</td>' +
                    '</tr>'
                );
                
                // Calculate totals
                totalQuantity += parseFloat(item.quantity) || 0;
                totalAmount += parseFloat(item.subtotal) || 0;
            });
            
            // Update footer with totals
            $('#totalQuantity').text(totalQuantity.toFixed(2));
            $('#totalAmount').text(totalAmount.toFixed(2));
            
            // Show the modal
            $('#viewItemsModal').modal('show');
        },
        error: function(xhr) {
            console.log('Error fetching transaction items:', xhr.responseText);
            alert('Error loading transaction items. Please check console for details.');
        }
    });
}
    function getStatusBadge(amount_received, total) {
        if (amount_received >= total) {
            if (amount_received > total) {
                const overpaidAmount = (amount_received - total).toFixed(2);
                return `<span class="badge badge-info" title="Overpaid by ${overpaidAmount}">Overpaid</span>`;
            }
            return '<span class="badge badge-success">Paid</span>';
        }
        const remainingAmount = (total - amount_received).toFixed(2);
        return `<span class="badge badge-warning" title="Remaining: ${remainingAmount}">Pending</span>`;
    }
});
</script>



	
</body>

</html>