
<?php $__env->startSection('title', 'Gate Passes'); ?>
<?php $__env->startPush('plugin-styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/flatpickr/flatpickr.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/sweetalert2/sweetalert2.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/select2/select2.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/select2-bootstrap-5-theme/select2-bootstrap-5-theme.min.css')); ?>">

<style>
.change-status-btn {
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
}
.select2-container {
    width:100% !important;
}
/* Select2 Bootstrap 5 Theme Fixes */
.select2-container--bootstrap-5 .select2-selection {
    min-height: 45px;
    padding: 0.375rem 0.75rem;
    font-size: 1rem;
    border: 1px solid #dee2e6;
    border-radius: 4px;
}

.select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
    padding: 0;
    line-height: 1.5;
}

.select2-container--bootstrap-5 .select2-selection--single .select2-selection__placeholder {
    color: #6c757d;
}

.select2-container--bootstrap-5 .select2-dropdown {
    border-color: #dee2e6;
    border-radius: 0.25rem;
}

.select2-container--bootstrap-5 .select2-search__field {
    padding: 0.375rem 0.75rem;
    border: 1px solid #dee2e6;
    border-radius: 0.25rem;
}

.select2-container--bootstrap-5 .select2-results__option--highlighted[aria-selected] {
    background-color: #0d6efd;
}

.select2-container--bootstrap-5.select2-container--focus .select2-selection,
.select2-container--bootstrap-5.select2-container--open .select2-selection {
    border-color: #86b7fe;
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}
/* Light blue hover for Select2 options */
.select2-container--bootstrap-5 .select2-results__option--highlighted {
    background-color: #5898ecff !important;  /* Light blue */
    color: #000 !important;                /* Black text for contrast */
}

/* Optional: smooth transition */
.select2-container--bootstrap-5 .select2-results__option--highlighted {
    transition: background-color 0.2s ease;
}

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

<?php $__env->startSection('content'); ?>
<div class="accordion mb-3" id="gpFilterAccordion">
    <div class="accordion-item">
        <h2 class="accordion-header" id="gpFilterHeading">
            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#gpFilterCollapse" aria-expanded="false" aria-controls="gpFilterCollapse">
                Filters
            </button>
        </h2>
        <div id="gpFilterCollapse" class="accordion-collapse collapse" aria-labelledby="gpFilterHeading" data-bs-parent="#gpFilterAccordion">
            <div class="accordion-body">
                <div class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <div class="mb-2">
                            <label class="form-label mb-0">PO Number</label>
                        </div>
                        <select id="filterPO" class="form-select"></select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Status</label>
                        <select id="filterStatus" class="form-select">
                            <option value="">All</option>
                            <option value="open">Open</option>
                            <option value="closed">Closed</option>
                            <!-- <option value="cancelled">Cancelled</option> -->
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Created Date Range</label>
                        <input id="filterDateRange" class="form-control" placeholder="YYYY-MM-DD to YYYY-MM-DD">
                    </div>
                </div>
                <div class="mt-3 d-flex gap-2">
                    <button id="btnApplyFilters" class="btn btn-primary" type="button">Apply</button>
                    <button id="btnResetFilters" class="btn btn-secondary" type="button">Reset</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="card-title mb-0">Gate Passes</h6>
            <a href="<?php echo e(route('gatepasses.create')); ?>" class="btn btn-primary">
                <i class="fas fa-plus me-2"></i>
                Add Gate Pass
            </a>
        </div>

        <?php if(session('success')): ?>
            <div class="alert alert-success"><?php echo e(session('success')); ?></div>
        <?php endif; ?>
        <?php if($errors->any()): ?>
            <div class="alert alert-danger"><?php echo e($errors->first()); ?></div>
        <?php endif; ?>

        <div class="table-responsive">
            <table id="gate-passes-table" class="table table-hover">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>GP #</th>
                        <th>PO #</th>
                        <th>Vehicle No</th>
                        <th>Driver Name</th>
                        <th>Status</th>
                        <th>Created At</th>
                        <th>Actions</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>

<!-- Status Change Modal -->
<div class="modal fade" id="statusChangeModal" tabindex="-1" aria-labelledby="statusChangeModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="statusChangeModalLabel">Change Gate Pass Status</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="statusChangeForm">
                <div class="modal-body">
                    <input type="hidden" id="gpId" name="gp_id">
                    <input type="hidden" name="_token" value="<?php echo e(csrf_token()); ?>">

                    <div class="mb-3">
                        <label for="newStatus" class="form-label">New Status</label>
                        <select class="form-select" id="newStatus" name="status" required>
                            <option value="">Select Status</option>
                            <option value="completed">Completed</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="statusNote" class="form-label">Note</label>
                        <textarea class="form-control" id="statusNote" name="note" rows="3" placeholder="Enter any notes or comments..."></textarea>
                        <div class="form-text" id="noteHelp">Note is required for cancellation.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" style="display: none;"></span>
                        Update Status
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('plugin-scripts'); ?>
<script src="<?php echo e(asset('theme/vendors/jquery/jquery.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/datatables.net/dataTables.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/select2/select2.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/flatpickr/flatpickr.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/sweetalert2/sweetalert2.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/moment/moment.min.js')); ?>"></script>

<script>
window.SKIP_ERROR_HANDLING = true;
document.addEventListener('DOMContentLoaded', function () {
    const poSelect = $('#filterPO');
    poSelect.select2({
        theme: 'bootstrap-5',
        placeholder: 'Select PO',
        allowClear: true,
        ajax: {
            url: '<?php echo e(route("purchase-orders.search")); ?>',
            dataType: 'json',
            data: function(params) {
                return {
                    search: params.term || '',
                    status: ''
                    
                };
            },
            processResults: function(data) {
                return {
                    results: data.map(po => ({
                        id: po.id,
                        text: po.text 
                    }))
                };
            },
            cache: true
        }
    });

    const fp = flatpickr('#filterDateRange', { mode: 'range', dateFormat: 'Y-m-d' });

    const table = new DataTable('#gate-passes-table', {
        processing: true,
        serverSide: true,
        ajax: {
            url: '<?php echo e(route("gatepasses.index")); ?>',
            data: function(d) {
                d.po_id = poSelect.val() || '';
                d.status = $('#filterStatus').val() || '';
                const dr = document.getElementById('filterDateRange').value;
                if (dr && dr.includes(' to ')) {
                    const parts = dr.split(' to ');
                    d.date_from = parts[0];
                    d.date_to = parts[1];
                }
            },
            error: function(xhr, error, thrown) {
                console.error('DataTables error:', error, thrown);
            }
        },
        order: [[0, 'desc']],
        columns: [
            { data: 'id', name: 'id' },
            { data: 'gate_pass_number', name: 'gate_pass_number' },
            { data: 'po_number', name: 'purchaseOrder.po_number' },
            { data: 'vehicle_no', name: 'vehicle_no' },
            { data: 'driver_name', name: 'driver_name' },
            { data: 'status', name: 'status' },
            {
                data: 'created_at',
                name: 'created_at',
                render: function(data) {
                    return moment(data).format('MM/DD/YYYY h:mm A');
                }
            },
            { data: 'actions', name: 'actions', orderable: false, searchable: false }
        ]
    });

    $('#btnApplyFilters, #filterStatus').on('click change', function() {
        table.draw();
    });
    poSelect.on('change', function() {
        table.draw();
    });
    $('#btnResetFilters').on('click', function() {
        poSelect.val(null).trigger('change');
        $('#filterStatus').val('');
        document.getElementById('filterDateRange').value = '';
        table.draw();
    });

    // Handle Change Status button clicks
    $(document).on('click', '.change-status-btn', function() {
        const button = $(this);
        const gpId = button.data('id');
        const currentStatus = button.data('current-status');

        $('#gpId').val(gpId);
        $('#statusNote').val('');
        updateStatusOptions(currentStatus);
        $('#statusChangeModal').modal('show');
    });

    // Handle status change form submission
    $('#statusChangeForm').on('submit', function(e) {
        e.preventDefault();

        const form = $(this);
        const submitBtn = form.find('button[type="submit"]');
        const spinner = submitBtn.find('.spinner-border');
        const gpId = $('#gpId').val();
        const newStatus = $('#newStatus').val();
        const note = $('#statusNote').val();

        if (newStatus === 'cancelled' && !note.trim()) {
            Swal.fire({
                icon: 'warning',
                title: 'Note Required',
                text: 'Please provide a note for cancellation.'
            });
            return;
        }

        submitBtn.prop('disabled', true);
        spinner.show();

        $.ajax({
            url: `<?php echo e(route('gatepasses.update-status', ':id')); ?>`.replace(':id', gpId),
            method: 'PATCH',
            data: {
                status: newStatus,
                note: note,
                _token: '<?php echo e(csrf_token()); ?>'
            },
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: response.message,
                        timer: 2000,
                        showConfirmButton: false
                    });
                    $('#statusChangeModal').modal('hide');
                    table.draw();
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: response.message
                    });
                }
            },
            error: function(xhr) {
                let errorMessage = 'Failed to update status';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                }
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: errorMessage
                });
            },
            complete: function() {
                submitBtn.prop('disabled', false);
                spinner.hide();
            }
        });
    });

    // Update note help text based on selected status
    $(document).on('change', '#newStatus', function() {
        const status = $(this).val();
        const noteHelp = $('#noteHelp');

        if (status === 'cancelled') {
            noteHelp.text('Note is required for cancellation. Please provide reason.');
            noteHelp.removeClass('text-muted').addClass('text-warning');
        } else {
            noteHelp.text('Note is optional for completion.');
            noteHelp.removeClass('text-warning').addClass('text-muted');
        }
    });

    // Reset form when modal is hidden
    $('#statusChangeModal').on('hidden.bs.modal', function() {
        $('#statusChangeForm')[0].reset();
        $('#gpId').val('');
        $('#noteHelp').text('Note is required for cancellation.').removeClass('text-warning').addClass('text-muted');
    });
});
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\habibcables-ERP\resources\views\gate_passes\index.blade.php ENDPATH**/ ?>