

<?php $__env->startSection('title', 'Leases'); ?>

<?php $__env->startSection('content'); ?>

    <div class="card">

        <div class="card-header">

            <div class="d-flex justify-content-between">

                <h4 class="mb-0">
                    Lease List
                </h4>

                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('leases.create')): ?>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addLeaseModal">

                        <i class="bi bi-plus-circle"></i>
                        New Lease

                    </button>
                <?php endif; ?>

            </div>

        </div>

        <div class="card-body">

            <div class="table-responsive">

                <table class="table table-striped" id="leaseTable">

                    <thead>

                        <tr>

                            <th>Lease No</th>

                            <th>Device</th>

                            <th>Customer</th>

                            <th>Truck_No</th>

                            <th>Destination</th>

                            <th>Amount</th>

                            <th>Sales</th>

                            <th>Status</th>

                            <th>Created</th>

                            <th>Action</th>

                        </tr>

                    </thead>

                    <tbody>

                        <?php $__currentLoopData = $leases; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $lease): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <tr>

                                <td>
                                    <?php echo e($lease->lease_no); ?>

                                </td>

                                <td>
                                    <?php echo e($lease->device?->serial_number); ?>

                                </td>

                                <td>

                                    <?php if($lease->lease_type == 'cash'): ?>
                                        <?php echo e($lease->customer_name); ?>

                                    <?php else: ?>
                                        <?php echo e($lease->customer?->name); ?>

                                    <?php endif; ?>

                                </td>

                                <td>
                                    <?php echo e($lease->truck_no); ?>

                                </td>

                                <td>
                                    <?php echo e($lease->destination?->name); ?>

                                </td>

                                <td>
                                    <?php echo e(number_format($lease->amount)); ?>

                                </td>

                                <td>
                                    <?php echo e($lease->salesUser?->name); ?>

                                </td>

                                <td>

                                    <?php if($lease->status == 'active'): ?>
                                        <span class="badge bg-warning">
                                            ACTIVE
                                        </span>
                                    <?php elseif($lease->status == 'audited'): ?>
                                        <span class="badge bg-success">
                                            AUDITED
                                        </span>
                                    <?php elseif($lease->status == 'arrived_border'): ?>
                                        <span class="badge bg-info">
                                            ARRIVED BORDER
                                        </span>
                                    <?php elseif($lease->status == 'completed'): ?>
                                        <span class="badge bg-dark">
                                            COMPLETED
                                        </span>
                                    <?php endif; ?>

                                </td>

                                <td>

                                    <?php echo e($lease->created_at->format('d M Y H:i')); ?>


                                </td>

                                <td>

                                    <div class="d-flex gap-1">

                                        <button class="btn btn-info btn-sm view-lease" data-id="<?php echo e($lease->id); ?>"
                                            data-bs-toggle="modal" data-bs-target="#viewLeaseModal">


                                            View
                                        </button>


                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('leases.edit')): ?>
                                            <?php if($lease->status == 'active'): ?>
                                                <button class="btn btn-primary btn-sm edit-lease" data-id="<?php echo e($lease->id); ?>"
                                                    data-bs-toggle="modal" data-bs-target="#editLeaseModal">

                                                    <i class="bi bi-pencil"></i>

                                                </button>
                                            <?php endif; ?>
                                        <?php endif; ?>

                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('leases.audit')): ?>
                                            <?php if($lease->status == 'active'): ?>
                                                <button class="btn btn-success btn-sm audit-lease"
                                                    data-id="<?php echo e($lease->id); ?>" data-no="<?php echo e($lease->lease_no); ?>">

                                                    Audit

                                                </button>
                                            <?php endif; ?>
                                        <?php endif; ?>


                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('leases.edit')): ?>
                                            <?php if(in_array($lease->status, ['active', 'audited'])): ?>
                                                <button class="btn btn-warning btn-sm swap-device"
                                                    data-id="<?php echo e($lease->id); ?>" data-no="<?php echo e($lease->lease_no); ?>"
                                                    data-bs-toggle="modal" data-bs-target="#swapDeviceModal">

                                                    <i class="bi bi-arrow-left-right"></i>

                                                </button>
                                            <?php endif; ?>
                                        <?php endif; ?>


                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('leases.edit')): ?>
                                            <?php if($lease->status == 'active'): ?>
                                                <button class="btn btn-danger btn-sm cancel-lease"
                                                    data-id="<?php echo e($lease->id); ?>" data-no="<?php echo e($lease->lease_no); ?>">

                                                    
                                                    Cancel

                                                </button>
                                            <?php endif; ?>
                                        <?php endif; ?>

                                    </div>

                                </td>
                            </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                    </tbody>

                </table>

            </div>

        </div>

    </div>


    <div class="modal fade" id="viewLeaseModal">

        <div class="modal-dialog modal-lg">

            <div class="modal-content">

                <div class="modal-header">

                    <h5>
                        Lease Receipt
                    </h5>

                    <button type="button" class="btn-close" data-bs-dismiss="modal">
                    </button>

                </div>

                <div class="modal-body">

                    <div id="leaseReceipt">

                        <div class="text-center">

                            <h5>KIBZ</h5>

                            <h6 id="lease_no"></h6>

                            <small id="lease_date"></small>

                        </div>

                        <hr>

                        <table class="table table-borderless">

                            <tr>
                                <td><strong>Customer</strong></td>
                                <td id="customer"></td>
                            </tr>

                            <tr>
                                <td><strong>Device</strong></td>
                                <td id="device"></td>
                            </tr>

                            <tr>
                                <td><strong>Sub T1</strong></td>
                                <td id="sub_t1"></td>
                            </tr>

                            <tr>
                                <td><strong>Truck No</strong></td>
                                <td id="truck"></td>
                            </tr>

                            <tr>
                                <td><strong>Trailer No</strong></td>
                                <td id="trailer"></td>
                            </tr>

                            <tr>
                                <td><strong>Driver</strong></td>
                                <td id="driver"></td>
                            </tr>

                            <tr>
                                <td><strong>Phone</strong></td>
                                <td id="driver_phone"></td>
                            </tr>

                            <tr>
                                <td><strong>Passport/DL</strong></td>
                                <td id="passport"></td>
                            </tr>

                            <tr>
                                <td><strong>Cargo Type</strong></td>
                                <td id="cargo"></td>
                            </tr>

                            <tr>
                                <td><strong>Agent</strong></td>
                                <td id="agent"></td>
                            </tr>

                            <tr>
                                <td><strong>Destination</strong></td>
                                <td id="destination"></td>
                            </tr>

                            <tr>
                                <td><strong>Tag Point</strong></td>
                                <td id="tag_point"></td>
                            </tr>

                            <tr>
                                <td><strong>Sales User</strong></td>
                                <td id="sales"></td>
                            </tr>

                            <tr>
                                <td><strong>Amount</strong></td>
                                <td id="amount"></td>
                            </tr>

                            <tr>
                                <td><strong>Status</strong></td>
                                <td id="status"></td>
                            </tr>

                        </table>

                    </div>

                </div>

            </div>

        </div>

    </div>



    <div class="modal fade" id="swapDeviceModal" tabindex="-1">

        <div class="modal-dialog">

            <div class="modal-content">

                <form id="swapDeviceForm">

                    <?php echo csrf_field(); ?>

                    <div class="modal-header">

                        <h5 class="modal-title">

                            Swap Lease Device

                        </h5>

                        <button type="button" class="btn-close" data-bs-dismiss="modal">
                        </button>

                    </div>

                    <div class="modal-body">

                        <input type="hidden" id="swap_lease_id">

                        <div class="mb-3">

                            <label class="form-label">

                                Lease No

                            </label>

                            <input type="text" id="swap_lease_no" class="form-control" readonly>

                        </div>

                        <div class="mb-3">

                            <label class="form-label">

                                New Device

                            </label>

                            <select id="swap_device_id" name="device_id" class="form-select select2" required>

                            </select>

                        </div>

                        <div class="mb-3">

                            <label class="form-label">

                                Reason

                            </label>

                            <textarea id="swap_reason" name="reason" class="form-control" rows="3" placeholder="Reason for swapping device"></textarea>

                        </div>

                    </div>

                    <div class="modal-footer">

                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">

                            Close

                        </button>

                        <button type="submit" class="btn btn-warning">

                            <i class="bi bi-arrow-left-right"></i>

                            Swap Device

                        </button>

                    </div>

                </form>

            </div>

        </div>

    </div>



    <?php echo $__env->make('leases.partials.add-lease-modal', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    <?php echo $__env->make('leases.partials.edit-lease-modal', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
    <script>
        $(document).ready(function() {

            $('#leaseTable').DataTable({
                order: [
                    [1, 'desc']
                ],

                pageLength: 25,

                responsive: true,

                dom: 'Bfrtip',

                buttons: [

                    'copy',
                    'excel',
                    'csv',
                    'print'

                ]
            });

        });



        $('#lease_type').on('change', function() {

            let type = $(this).val();

            if (type === 'bill') {

                $('#bill_customer_wrapper').show();
                $('#cash_customer_wrapper').hide();

            } else {

                $('#bill_customer_wrapper').hide();
                $('#cash_customer_wrapper').show();

            }

        });



        $(document).on(
            'click',
            '.view-lease',
            function() {

                let id = $(this).data('id');

                $.get(
                    '/leases/' + id + '/details',
                    function(lease) {

                        let customer =
                            lease.lease_type === 'cash' ?
                            lease.customer_name :
                            (lease.customer?.name ?? '');

                        $('#lease_no').text(
                            lease.lease_no
                        );

                        $('#lease_date').text(
                            lease.leased_at ?? ''
                        );

                        $('#customer').text(
                            customer
                        );

                        $('#device').text(
                            lease.device?.serial_number ?? ''
                        );

                        $('#sub_t1').text(
                            lease.sub_t1_no ?? ''
                        );

                        $('#truck').text(
                            lease.truck_no ?? ''
                        );

                        $('#trailer').text(
                            lease.trailer_no ?? ''
                        );

                        $('#driver').text(
                            lease.driver_name ?? ''
                        );

                        $('#driver_phone').text(
                            lease.driver_phone ?? ''
                        );

                        $('#passport').text(
                            lease.passport_or_license ?? ''
                        );

                        $('#cargo').text(
                            lease.cargo_type ?? ''
                        );

                        $('#agent').text(
                            lease.agent_name ?? ''
                        );

                        $('#destination').text(
                            lease.destination?.name ?? ''
                        );
                        $('#tag_point').text(
                            lease.tag_point?.name ?? ''
                        );

                        $('#sales').text(
                            lease.sales_user?.name ?? ''
                        );

                        $('#amount').text(
                            Number(lease.amount).toLocaleString() + ' TZS'
                        );

                        $('#status').text(
                            lease.status ?? ''
                        );

                    }
                );

            }
        );


        $(document).on(
            'click',
            '.edit-lease',
            function() {
                let id = $(this).data('id');

                $('#editLeaseForm').attr(
                    'action',
                    '/leases/' + id
                );

                $.get(
                    '/leases/' + id + '/edit-details',
                    function(response) {

                        let lease = response.lease;

                        // Add current leased device if missing
                        if (
                            $('#edit_device_id option[value="' + lease.device_id + '"]').length === 0
                        ) {

                            $('#edit_device_id').append(
                                new Option(
                                    response.current_device.serial_number,
                                    response.current_device.id,
                                    true,
                                    true
                                )
                            );
                        }

                        $('#edit_device_id')
                            .val(lease.device_id)
                            .trigger('change');

                        $('#edit_lease_type').val(
                            lease.lease_type
                        );

                        $('#edit_device_id').val(
                            lease.device_id
                        ).trigger('change');

                        $('#edit_sub_t1_no').val(
                            lease.sub_t1_no
                        );

                        $('#edit_customer_name').val(
                            lease.customer_name
                        );

                        $('#edit_customer_id').val(
                            lease.customer_id
                        );

                        $('#edit_truck_no').val(
                            lease.truck_no
                        );

                        $('#edit_trailer_no').val(
                            lease.trailer_no
                        );

                        $('#edit_driver_name').val(
                            lease.driver_name
                        );

                        $('#edit_driver_phone').val(
                            lease.driver_phone
                        );

                        $('#edit_passport_or_license').val(
                            lease.passport_or_license
                        );

                        $('#edit_cargo_type').val(
                            lease.cargo_type
                        );

                        $('#edit_agent_name').val(
                            lease.agent_name
                        );

                        $('#edit_destination_border_id').val(
                            lease.destination_border_id
                        );

                        $('#edit_tag_point_id').val(
                            lease.tag_point_id
                        );

                        if (
                            lease.lease_type == 'bill'
                        ) {

                            $('#bill_customer_wrapper').show();
                            $('#cash_customer_wrapper').hide();

                        } else {

                            $('#bill_customer_wrapper').hide();
                            $('#cash_customer_wrapper').show();
                        }
                    }
                );
            }

        );



        $(document).on(
            'click',
            '.audit-lease',
            function() {

                let id = $(this).data('id');
                let leaseNo = $(this).data('no');

                Swal.fire({

                    title: 'Audit Lease?',

                    text: 'Confirm audit for ' + leaseNo + ' ?',

                    icon: 'question',

                    showCancelButton: true,

                    confirmButtonText: 'Yes, Audit'

                }).then((result) => {

                    if (result.isConfirmed) {

                        $.ajax({

                            url: '/leases/' + id + '/audit',

                            type: 'POST',

                            data: {
                                _token: '<?php echo e(csrf_token()); ?>'
                            },

                            success: function() {

                                toastr.success(
                                    'Lease audited successfully.'
                                );

                                location.reload();
                            }

                        });
                    }
                });
            }
        );





        $(document).on(
            'click',
            '.cancel-lease',
            function() {

                let id = $(this).data('id');
                let leaseNo = $(this).data('no');

                Swal.fire({

                    title: 'Cancel Lease',

                    text: 'Enter cancellation reason',

                    input: 'textarea',

                    inputPlaceholder: 'Cancellation remarks...',

                    icon: 'warning',

                    showCancelButton: true,

                    confirmButtonText: 'Cancel Lease',

                    inputValidator: (value) => {

                        if (!value) {

                            return 'Cancellation remarks are required';
                        }
                    }

                }).then((result) => {

                    if (result.isConfirmed) {

                        $.ajax({

                            url: '/leases/' + id + '/cancel',

                            type: 'POST',

                            data: {

                                _token: '<?php echo e(csrf_token()); ?>',

                                cancel_remarks: result.value
                            },

                            success: function() {

                                toastr.success(
                                    'Lease cancelled successfully'
                                );

                                location.reload();
                            }

                        });

                    }

                });

            }
        );


        $(document).on(
            'click',
            '.swap-device',
            function() {

                let leaseId = $(this).data('id');
                let leaseNo = $(this).data('no');

                $('#swap_lease_id').val(
                    leaseId
                );

                $('#swap_lease_no').val(
                    leaseNo
                );

                $('#swap_device_id').empty();

                $.get(
                    '/leases/' + leaseId + '/swap-form',
                    function(response) {

                        response.devices.forEach(function(device) {

                            $('#swap_device_id').append(

                                `<option value="${device.id}">
                            ${device.serial_number}
                        </option>`

                            );

                        });

                        $('#swap_device_id').trigger('change');

                    }

                );

            }
        );



        $('#swapDeviceForm').submit(function(e) {

            e.preventDefault();

            let leaseId = $('#swap_lease_id').val();

            $.ajax({

                url: '/leases/' +
                    leaseId +
                    '/swap-device',

                type: 'POST',

                data: {

                    _token: '<?php echo e(csrf_token()); ?>',

                    device_id: $('#swap_device_id').val(),

                    reason: $('#swap_reason').val()

                },

                success: function(response) {

                    toastr.success(
                        response.message
                    );

                    $('#swapDeviceModal').modal(
                        'hide'
                    );

                    location.reload();

                },

                error: function(xhr) {

                    toastr.error(
                        xhr.responseJSON.message
                    );

                }

            });

        });



        $('#swapDeviceModal').on(
            'shown.bs.modal',
            function() {

                $('#swap_device_id').select2({

                    dropdownParent: $('#swapDeviceModal'),

                    width: '100%'

                });

            }
        );




$(document).on(
    'click',
    '.cancel-lease',
    function () {

        let id = $(this).data('id');
        let leaseNo = $(this).data('no');

        Swal.fire({

            title: 'Cancel Lease',

            html:
                '<b>' + leaseNo + '</b><br><br>' +
                'Please provide the reason for cancellation.',

            icon: 'warning',

            input: 'textarea',

            inputPlaceholder:
                'Enter cancellation reason...',

            inputAttributes: {

                rows: 4

            },

            showCancelButton: true,

            confirmButtonColor: '#dc3545',

            confirmButtonText: 'Cancel Lease',

            cancelButtonText: 'Close',

            inputValidator: (value) => {

                if (!value) {

                    return 'Cancellation reason is required';

                }

            }

        }).then((result) => {

            if (!result.isConfirmed) {

                return;

            }

            $.ajax({

                url:
                    '/leases/' +
                    id +
                    '/cancel',

                type: 'POST',

                data: {

                    _token:
                        '<?php echo e(csrf_token()); ?>',

                    cancel_reason:
                        result.value

                },

                success: function (response) {

                    toastr.success(
                        response.message
                    );

                    setTimeout(function () {

                        location.reload();

                    }, 600);

                },

                error: function (xhr) {

                    toastr.error(

                        xhr.responseJSON?.message ??
                        'Unable to cancel lease.'

                    );

                }

            });

        });

    }
);




    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.master', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\Projects\lms-ects\resources\views/leases/index.blade.php ENDPATH**/ ?>