<?php
include 'db.php';
include 'layout.php';

// Bulk update logic BEFORE any output
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['purchase_ids'], $_POST['bulk_status']) && $_POST['bulk_status']) {
	$status = $conn->real_escape_string($_POST['bulk_status']);
	$ids = array_map('intval', $_POST['purchase_ids']);
	$idList = implode(',', $ids);
	$conn->query("UPDATE purchases SET status = '$status' WHERE id IN ($idList)");
	header("Location: purchase-list.php?bulk=done");
	exit;
}
?>

<body>
<div class="main-wrapper">
	<div class="page-wrapper">
		<div class="content">
			<div class="page-header">
				<div class="page-title">
					<h4>Purchase List</h4>
					<h6>Manage your purchases</h6>
				</div>
				<div class="page-btn">
					<a href="#" class="btn btn-added" data-bs-toggle="modal" data-bs-target="#addPurchaseModal">
						<i class="fa fa-plus me-2"></i>Add New Purchase
					</a>
				</div>
			</div>

			<div class="card">
				<div class="card-body">

					<!-- Filter Form -->
					<form method="get" class="mb-3">
						<div class="row g-2">
							<div class="col-md-3">
								<select name="status" class="form-control" onchange="this.form.submit()">
									<option value="">All Statuses</option>
									<option value="received" <?= (($_GET['status'] ?? '') === 'received') ? 'selected' : '' ?>>Received</option>
									<option value="pending" <?= (($_GET['status'] ?? '') === 'pending') ? 'selected' : '' ?>>Pending</option>
								</select>
							</div>
						</div>
					</form>

					<?php
					$statusFilter = $_GET['status'] ?? '';
					$whereClause = $statusFilter ? "WHERE p.status = '{$conn->real_escape_string($statusFilter)}'" : '';
					$sql = "SELECT p.*, v.name AS vendor FROM purchases p JOIN vendors v ON p.vendor_id = v.id $whereClause ORDER BY p.id DESC";
					$result = $conn->query($sql);
					?>

					<form method="post" id="bulkUpdateForm">
						<table class="table datatable table-bordered">
							<thead>
								<tr>
									<th><input type="checkbox" id="checkAll"></th>
									<th>Supplier</th>
									<th>Reference</th>
									<th>Date</th>
									<th>Total</th>
									<th>Net</th>
									<th>Status</th>
									<th>Action</th>
								</tr>
							</thead>
							<tbody>
								<?php while ($row = $result->fetch_assoc()): ?>
								<tr>
									<td><input type="checkbox" name="purchase_ids[]" value="<?= $row['id'] ?>"></td>
									<td><?= $row['vendor'] ?></td>
									<td><?= $row['purchase_number'] ?></td>
									<td><?= $row['purchase_date'] ?></td>
									<td><?= $row['total_amount'] ?></td>
									<td><?= $row['net_amount'] ?></td>
									<td>
										<select class="form-select form-select-sm inline-status" data-id="<?= $row['id'] ?>">
											<option value="received" <?= $row['status'] === 'received' ? 'selected' : '' ?>>Received</option>
											<option value="pending" <?= $row['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
										</select>
									</td>
									<td><a class='btn btn-sm btn-primary' href='#'>View</a></td>
								</tr>
								<?php endwhile; ?>
							</tbody>
						</table>

						<div class="mt-3">
							<select name="bulk_status" class="form-select w-auto d-inline">
								<option value="">Bulk Update Status</option>
								<option value="received">Mark as Received</option>
								<option value="pending">Mark as Pending</option>
							</select>
							<button type="submit" class="btn btn-secondary btn-sm">Update Selected</button>
						</div>
					</form>

				</div>
			</div>

			<?php include 'purchase-modal.php'; ?>
		</div>
	</div>
</div>

<?php if (isset($_GET['bulk']) && $_GET['bulk'] === 'done'): ?>
<script>
Swal.fire({
	title: 'Bulk Status Updated',
	text: 'Selected purchases have been updated successfully.',
	icon: 'success',
	timer: 2000,
	showConfirmButton: false
});
</script>
<?php endif; ?>

<script>
$(document).ready(function () {
	$('#checkAll').on('change', function () {
		$('input[name="purchase_ids[]"]').prop('checked', this.checked);
	});

	$('.inline-status').change(function () {
		const id = $(this).data('id');
		const status = $(this).val();
		$.post('update_status.php', { id, status }, function () {
			Swal.fire({
				title: 'Status Updated',
				text: 'Purchase has been marked as ' + status.toUpperCase(),
				icon: 'success',
				showConfirmButton: false,
				timer: 1500
			});
		});
	});
});
</script>
</body>
</html>
<?php if (isset($_GET['success']) && $_GET['success'] == 1): ?>
<script>
Swal.fire({
  title: 'Purchase Added',
  text: 'The purchase was saved successfully!',
  icon: 'success',
  timer: 2000,
  showConfirmButton: false
});
if (window.location.search.includes('success=1')) {
  history.replaceState({}, document.title, window.location.pathname);
}
</script>
<?php endif; ?>

