@extends('layouts.app')
@section('title', 'Gatepasses')
@push('plugin-styles')
<link rel="stylesheet" href="{{ asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.css') }}">
<link rel="stylesheet" href="{{ asset('theme/vendors/flatpickr/flatpickr.min.css') }}">
<link rel="stylesheet" href="{{ asset('theme/vendors/sweetalert2/sweetalert2.min.css') }}">
@endpush
@section('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-3">
						<label class="form-label">Vendor</label>
						<select id="filterVendor" class="form-select">
							<option value="">All Vendors</option>
						</select>
					</div>
					<div class="col-md-3">
						<label class="form-label">Type</label>
						<select id="filterType" class="form-select">
							<option value="">All Types</option>
							<option value="inbound">Inbound</option>
							<option value="outbound">Outbound</option>
						</select>
					</div>
					<div class="col-md-3">
						<label class="form-label">Status</label>
						<select id="filterStatus" class="form-select">
							<option value="">All Statuses</option>
							<option value="pending">Pending</option>
							<option value="approved">Approved</option>
							<option value="completed">Completed</option>
							<option value="cancelled">Cancelled</option>
						</select>
					</div>
					<div class="col-md-3">
						<label class="form-label">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 type="button" class="btn btn-primary" id="btnApplyFilters">
						<i class="fas fa-search me-2"></i>
						Apply Filters
					</button>
					<button type="button" class="btn btn-outline-secondary" id="btnResetFilters">
						<i class="fas fa-times me-2"></i>
						Clear Filters
					</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">Gatepasses</h6>
			<a href="{{ route('gatepasses.create') }}" class="btn btn-primary">
				<i class="fas fa-plus me-2"></i>
				Add Gatepass
			</a>
		</div>
		@if(session('success'))
			<div class="alert alert-success">{{ session('success') }}</div>
		@endif
		@if($errors->any())
			<div class="alert alert-danger">{{ $errors->first() }}</div>
		@endif
		<div class="table-responsive">
			<table id="gp-table" class="table table-hover">
				<thead class="table-light">
					<tr>
						<th>ID</th>
						<th>Gate Pass #</th>
						<th>Vendor</th>
						<th>Created</th>
						<th>Type</th>
						<th>Status</th>
						<th>Actions</th>
					</tr>
				</thead>
			</table>
		</div>
	</div>
</div>
@endsection

@push('plugin-scripts')
<script src="{{ asset('theme/vendors/jquery/jquery.min.js') }}"></script>
<script src="{{ asset('theme/vendors/datatables.net/dataTables.js') }}"></script>
<script src="{{ asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.js') }}"></script>
<script src="{{ asset('theme/vendors/select2/select2.min.js') }}"></script>
<script src="{{ asset('theme/vendors/flatpickr/flatpickr.min.js') }}"></script>
<script src="{{ asset('theme/vendors/sweetalert2/sweetalert2.min.js') }}"></script>
<script>
	document.addEventListener('DOMContentLoaded', function(){
		// Initialize vendor filter with Select2
		const vendorSelect = $('#filterVendor');
		vendorSelect.select2({
			theme: 'bootstrap-5',
			placeholder: 'Select Vendor',
			allowClear: true,
			ajax: {
				url: '{{ route('contacts.search') }}',
				dataType: 'json',
				delay: 250,
				data: params => ({
					q: params.term || '',
					t: "vendor"
				}),
				processResults: data => data,
				cache: true
			}
		});

		// Initialize date range picker
		flatpickr('#filterDateRange', { mode: 'range', dateFormat: 'Y-m-d' });

		const table = new DataTable('#gp-table', {
			processing: true,
			serverSide: true,
			ajax: {
				url: 'gatepasses',
				data: function(d) {
					d.vendor_id = vendorSelect.val() || '';
					d.type = $('#filterType').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];
					}
				}
			},
			order: [[0, 'desc']], // Latest records on top
			columns: [
				{ data: 'id', name: 'id' },
				{ data: 'gate_pass_number', name: 'gate_pass_number' },
				{ data: 'vendor_name', name: 'vendor.name', orderable: false },
				{ data: 'created_at', name: 'created_at' },
				{ data: 'type', name: 'type' },
				{ data: 'status', name: 'status' },
				{ data: 'actions', name: 'actions', orderable: false, searchable: false }
			],
		});

		// Filter event handlers
		$('#btnApplyFilters, #filterType, #filterStatus').on('click change', function(){
			table.draw();
		});

		vendorSelect.on('change', function(){
			table.draw();
		});

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

		// Handle status select changes
		$(document).on('change', '.status-select', function() {
			const select = $(this);
			const url = select.data('url');
			const value = select.val();
			const originalValue = select.find('option[selected]').val();

			$.ajax({
				url: url,
				method: 'PATCH',
				data: {
					status: value,
					_token: '{{ csrf_token() }}'
				},
				success: function(response) {
					if (response.success) {
						// Show success message
						Swal.fire({
							icon: 'success',
							title: 'Success!',
							text: 'Gatepass status updated successfully',
							timer: 2000,
							showConfirmButton: false
						});
						// Reload the table
						table.draw();
					} else {
						Swal.fire({
							icon: 'error',
							title: 'Error!',
							text: 'Failed to update status: ' + response.message
						});
						// Revert to original value
						select.val(originalValue);
					}
				},
				error: function() {
					Swal.fire({
						icon: 'error',
						title: 'Error!',
						text: 'Failed to update status'
					});
					// Revert to original value
					select.val(originalValue);
				}
			});
		});
	});
</script>
@endpush
