
<?php $__env->startSection('title', 'Purchase Orders'); ?>
<?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')); ?>">
<style>
    .select2-container--bootstrap-5{
    width: 100% !important;
}
</style>

<?php $__env->stopPush(); ?>
<?php $__env->startSection('content'); ?>
<div class="accordion mb-3" id="poFilterAccordion">
    <div class="accordion-item">
        <h2 class="accordion-header" id="poFilterHeading">
            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#poFilterCollapse" aria-expanded="false" aria-controls="poFilterCollapse">
                Filters
            </button>
        </h2>
        <div id="poFilterCollapse" class="accordion-collapse collapse" aria-labelledby="poFilterHeading" data-bs-parent="#poFilterAccordion">
            <div class="accordion-body">
                <div class="row g-3 align-items-end">
                    <div class="col-md-3">
                        <div class="mb-2">

                            <label class="form-label mb-0">Vendor</label>
                        </div>
                        <select id="filterVendor" class="form-select"></select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select id="filterStatus" class="form-select">
                            <option value="">All</option>
                            <option value="open">Open</option>
                            <option value="partial">Partial</option>
                            <option value="closed">Closed</option>
                            <!-- <option value="cancelled">Cancelled</option> -->
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Payment</label>
                        <select id="filterPayment" class="form-select">
                            <option value="">All</option>
                            <option value="unpaid">Unpaid</option>
                            <option value="partially_paid">Partially Paid</option>
                            <option value="paid">Paid</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Order 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
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="btnResetFilters">
                        <i class="fas fa-times me-2"></i>
                        Clear
                    </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">Purchase Orders</h6>
			<a href="<?php echo e(route('purchase-orders.create')); ?>" class="btn btn-primary">
				<i class="fas fa-plus me-2"></i>
				Add Purchase Order
			</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="purchase-orders-table" class="table table-hover">
				<thead class="table-light">
					<tr>
						<th>ID</th>
                        <th>PR #</th>
						<th>PO #</th>
						<th>Vendor</th>
						<th>Status</th>
						<th>Expected Date</th>
						<th>Created At</th>
						<th>Items</th>
						<th>Total</th>
						<th>Payment</th>
						<th>Actions</th>
					</tr>
				</thead>
			</table>
		</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 urlParams  = new URLSearchParams(window.location.search);
    const dateFilter = urlParams.get('date');
    const statusFilter = urlParams.get('status');

    const vendorSelect = $('#filterVendor');
    vendorSelect.select2({ theme: 'bootstrap-5', placeholder: 'Vendor', allowClear: true, ajax: {
        url: '<?php echo e(route('api.contacts.search')); ?>', dataType: 'json', delay: 250,
        // data: params => ({ q: params.term || '', t: "vendor" }),
		data: params => ({ q: params.term || '', type: "supplier" }),
        processResults: data => data, cache: true
    }});

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

    if (dateFilter === 'month') {
        const today   = new Date();
        const yyyy    = today.getFullYear();
        const mm      = String(today.getMonth() + 1).padStart(2, '0');
        const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate();

        fp.setDate([
            `${yyyy}-${mm}-01`,
            `${yyyy}-${mm}-${String(lastDay).padStart(2, '0')}`
        ]);
    }

    const table = new DataTable('#purchase-orders-table', {
        language: {
            processing: 'Loading...',
            zeroRecords: 'No matching records found',
            error: 'Error loading data. Please try again.'
        },
        processing: true,
        serverSide: true,
        ajax: {
            url: 'purchase-orders',
            data: function(d) {
                d.vendor_id      = vendorSelect.val() || '';
                d.status         = $('#filterStatus').val() || statusFilter || '';
                d.payment_status = $('#filterPayment').val() || '';

                // ✅ Read flatpickr value
                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: 'purchase_orders.id' },
            { data: 'pr_number',            name: 'purchase_requests.pr_number' },
            { data: 'po_number',            name: 'purchase_orders.po_number' },
            { data: 'vendor_name',          name: 'vendor.name', orderable: false, searchable: true },
            { data: 'status',               name: 'purchase_orders.status' },
            { data: 'formatted_expected_date', name: 'purchase_orders.expected_date', render: d => d || '-' },
            { data: 'formatted_created_at', name: 'purchase_orders.created_at',       render: d => d || '-' },
            { data: 'items_count',          name: 'items_count', searchable: false },
            { data: 'total_amount',         name: 'purchase_orders.total_amount' },
            { data: 'payment_status',       name: 'purchase_orders.payment_status' },
            { data: 'actions',              name: 'actions', orderable: false, searchable: false },
        ],
    });

    $('#btnApplyFilters').on('click', function() { table.draw(); });
    $('#btnResetFilters').on('click', function() {
        vendorSelect.val(null).trigger('change');
        $('#filterStatus').val('');
        $('#filterPayment').val('');
        fp.clear();
        table.draw();
    });

});
</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/purchase_orders/index.blade.php ENDPATH**/ ?>