<?php
    // Load page from template
    require_once "dashboard.php";
?>

<!-- Start the custom CSS for this page -->
<?= startSection('css') ?> 
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="<?=$baseURL?>/assets/css/dataTables.bootstrap4.css">

<?= endSection() ?> 

<!-- Start the content for this page -->
<?= startSection('content') ?> 
    <div class="container-fluid">

        <?= yieldSection('dashboard') ?> 

        <div class="row justify-content-center mb-4">
            <div class="col-11">
                <div class="row">
                    <div class="col-12 col-lg-12 col-xl-12">
                        <div class="card shadow mb-4 mt-4">
                            <div class="card-body mx-4 my-4">
                                <div class="row toolbar">
                                    <div class="col-md-6">
                                        <h2 class="h3 page-title">List of request for approval</h2>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-row float-right"> 
                                        </div>
                                    </div>
                                </div>
                                <hr>
                                <div class="row toolbar">
                                    <div class="col-12 mt-3">
                                        <div class="form-row float-right "> 
                                            <div class="form-group mr-3">
                                                <select id="status" class="form-control" required>
                                                    <option value="" selected>Select All Status</option>
                                                    <option value="Pending">For Verification</option>
                                                    <option value="Verified">For Approval</option>
                                                </select>
                                            </div>
                                            <div class="form-group mr-3">
                                                <select id="donation_type" class="form-control" required>
                                                    <option value="" selected>Select All Donation</option>
                                                    <option value="Monetary">Monetary</option>
                                                    <option value="Material">Material</option>
                                                </select>
                                            </div>
                                            <div class="form-group mr-3">
                                                <select id="location" class="form-control" required>
                                                    <!-- Options will be populated here -->
                                                </select>
                                            </div> 
                                            <div class="form-group">
                                                <button class="btn btn-primary fe fe-search fe-16" id="filterData"> Filter</button>
                                            </div> 
                                        </div>
                                    </div>
                                </div>
                                <hr>
                                <table class="table datatables table-hover" id="tblData">
                                    <thead class="bg-light font-weight-bold">
                                        <tr>
                                            <th><strong>No.</strong></th>
                                            <th><strong>Member</strong></th>
                                            <th><strong>Donation</strong></th>
                                            <th><strong>Location</strong></th>
                                            <th><strong>Purpose</strong></th>
                                            <th><strong>Status</strong></th>
                                            <th><strong>Action</strong></th>
                                        </tr>
                                    </thead>
                                    <tbody id="donation-request-body">
                                        <!-- Data rows will be populated here dynamically -->
                                    </tbody>
                                </table>
                            </div> 
                        </div> 
                    </div>
                </div>

            </div>
        </div>
    </div>
<?= endSection() ?> 

<!-- Start the java scripts for this page -->
<?= startSection('scripts') ?> 
<script src='<?=$baseURL?>/assets/js/jquery.dataTables.min.js'></script>
<script src='<?=$baseURL?>/assets/js/dataTables.bootstrap4.min.js'></script>
<script >
    $(document).ready(function(){   
       
        var tblData = $('#tblData').DataTable();

        getLocationList();
        getDonationRequest();
 
        $("#filterData").on('click', function(e){ 
            getDonationRequest();
        });

        function getDonationRequest(){
            showLoader();
            var status   	        = $("#status").val();
            var donation_type   	= $("#donation_type").val();
            var location   	        = $("#location").val();
            tblData.clear().draw();
            $.ajax({
				url: '<?=$baseURL?>/controller/ctrl-request.php',
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({ 
                    trans               : "getDonationRequest",
                    status              : status,
                    donation_type       : donation_type,
                    location            : location
                }), 
                success: function(response) {
                    closeLoader();
                    if (response.response_code === "0") {
                        response.results.forEach(function(item, index) {
                            var htmlData;
                            switch (item.donation_type) {
                            case "Material":
                                htmlData = `<div>
                                                <span><strong>${item.donation_type}</strong></span><br>
                                                <span><strong>Item: </strong>${item.item_id}</span><br>
                                                <span><strong>Quantity: </strong>${item.item_quantity}</span>
                                            </div>`; 
                                break;
                            case "Monetary":
                                htmlData = `<div>
                                                <span><strong>${item.donation_type}</strong></span><br>
                                                <span><strong>Amount: </strong>${item.amount}</span><br>
                                            </div>`; 
                                break;
                            }

                            var htmlBtn;
                            switch (item.status) {
                            case "Pending":
                                htmlBtn = `<div>
                                                <button type="button" class="btn mb-2 mr-2 btn-primary btn-sm handleStatus" status="Verified" item_id="${item.id}">Verify</button>
                                                <button type="button" class="btn mb-2 btn-danger btn-sm handleStatus" status="Denied" item_id="${item.id}">Deny</button>
                                            </div>`; 
                                break;
                            case "Verified":
                                htmlBtn = `<div>
                                                <button type="button" class="btn mb-2 mr-2 btn-success btn-sm handleStatus" status="Approved" item_id="${item.id}">Approve</button>
                                                <button type="button" class="btn mb-2 btn-danger btn-sm handleStatus" status="Denied" item_id="${item.id}">Deny</button>
                                            </div>`; 
                                break;
                            }
                            
                            tblData.row.add([
                                index + 1,
                                `<div>
                                    <strong>${item.member_name}</strong><br>
                                    <span><i class="fe fe-home"></i> ${item.member_address}</span><br>
                                    <span><i class="fe fe-mail"></i> ${item.member_email}</span>, 
                                    <span><i class="fe fe-phone"></i> ${item.member_phone}</span>
                                </div>`,
                                htmlData,
                                item.location,
                                item.purpose,
                                item.status,
                                htmlBtn,
                            ]).draw();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: response.title,
                            text: response.description,
                            confirmButtonText: 'OK',
                            didOpen: () => {
                                Swal.hideLoading();
                            },  
                        });
                    }
                },
                error: function(xhr, status, error) { 
                    Swal.fire({
                        icon: 'error',
                        title: 'Failed',
                        text: 'An error occurred while submitting the event!',
                        confirmButtonText: 'OK',
                        didOpen: () => {
                            Swal.hideLoading();
                        },  
                    });
                }
            });
        }


        function getLocationList(){
            $.ajax({
				url: '<?=$baseURL?>/controller/ctrl-global.php',
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(
                    { 
                        trans: "getLocations" 
                    }
                ), 
                success: function(response) {
                    if (response.response_code === "0") {
                        var items = response.items;
                        var dropdown = $('#location');

                        // Clear existing options
                        dropdown.empty();     
                        dropdown.append('<option value="" selected>Select All Location</option>');

                        // Populate the dropdown with items
                        $.each(items, function(index, item) {
                            dropdown.append('<option value="' + item.location_description + '">' + item.location_description + '</option>');
                        });
                    }
                }
            });
        }

        $(document).on('click', '.handleStatus', function(e){ 
            
            var status = $(this).attr('status'); 
            var item_id = $(this).attr('item_id'); 
            handleStatus(status,item_id);
            
        });

        function handleStatus(status,item_id){
            var data;
            if(status=='Verified'){
                data = {
                    trans: "updateRequestStatus",
                    id: item_id,
                    status: "Verified",
                    verified_date: new Date(),
                    verified_by: "<?=$_SESSION['userid']?>",
                };
            } else if(status=='Approved'){
                data = {
                    trans: "updateRequestStatus",
                    id: item_id,
                    status: "Approved",
                    approved_date: new Date(),
                    approved_by: "<?=$_SESSION['userid']?>",
                };
            } else if(status=='Denied'){
                data = {
                    trans: "updateRequestStatus",
                    id: item_id,
                    status: "Denied",
                    denied_date: new Date(),
                    denied_by: "<?=$_SESSION['userid']?>",
                };
            }

            Swal.fire({
                title: 'Are you sure?',
                text: `Do you want to ${status} this request?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes',
                cancelButtonText: 'Cancel',
                didOpen: () => {
                    Swal.hideLoading();
                },  
            }).then((result) => {
                if (result.isConfirmed) {
                    showLoader();
                    // Create the data object to send in the API request
                    $.ajax({
						url: '<?=$baseURL?>/controller/ctrl-request.php',
                        type: "POST",
                        contentType: "application/json",
                        data: JSON.stringify(data), 
                        success: function(response) {
                            if (response.response_code === "0") {
                                if (response.response_code === "0") {
                                    Swal.fire({
                                        icon: 'success',
                                        title: response.title,
                                        text: response.description,
                                        confirmButtonText: 'OK'
                                    }).then((result) => {
                                        window.location.reload(); 
                                    });
                                } else {
                                    Swal.fire({
                                        icon: 'error',
                                        title: response.title,
                                        text: response.description,
                                        confirmButtonText: 'OK',
                                        didOpen: () => {
                                            Swal.hideLoading();
                                        },  
                                    });
                                }
                            }
                        }
                    });
                }
            });
        }
    });
</script> 
<?= endSection() ?> 