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

<body>
<div class="main-wrapper">
	<div class="page-wrapper">
		<div class="content">
			<div class="page-header">
				<div class="page-title">
					<h4>Supplier Payments</h4>
					<h6>Pay against purchase or total outstanding</h6>
				</div>
			</div>

			<form method="GET" class="row mb-3">
				<div class="col-md-6">
					<select name="vendor_id" class="form-control select2" required>
						<option value="">-- Select Supplier --</option>
						<?php
						$vendors = $conn->query("SELECT id, name FROM vendors ORDER BY name ASC");
						while ($v = $vendors->fetch_assoc()) {
							$selected = ($_GET['vendor_id'] ?? '') == $v['id'] ? 'selected' : '';
							echo "<option value='{$v['id']}' $selected>{$v['name']}</option>";
						}
						?>
					</select>
				</div>
				<div class="col-md-2">
					<button type="submit" class="btn btn-primary">Search</button>
				</div>
			</form>

			<?php if (!empty($_GET['vendor_id'])): ?>
			<?php
			$vid = intval($_GET['vendor_id']);
			$vendor = $conn->query("SELECT * FROM vendors WHERE id = $vid")->fetch_assoc();
			$outstanding = $conn->query("SELECT * FROM sup_outstanding WHERE vendor_id = $vid AND status != 'paid' ORDER BY purchase_id ASC");

			$rows = [];
			$total_outstanding = 0;
			while ($row = $outstanding->fetch_assoc()) {
				$rows[] = $row;
				$total_outstanding += $row['amount'];
			}
			?>

			<div class="card">
				<div class="card-header">
					<h5>Outstanding for: <?php echo $vendor['name']; ?></h5>
					<p>Total Outstanding: <strong>Rs <?php echo number_format($total_outstanding, 2); ?></strong></p>
				</div>
				<div class="card-body">
					<?php if (count($rows)): ?>
					<form method="POST" action="make_supplier_payment.php">
						<input type="hidden" name="vendor_id" value="<?php echo $vid; ?>">

						<table class="table table-bordered">
							<thead>
								<tr>
									<th>Purchase #</th>
									<th>Outstanding</th>
									<th>Status</th>
									<th>Enter Payment</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($rows as $row): ?>
								<tr>
									<td>#<?php echo $row['purchase_id']; ?></td>
									<td>Rs <?php echo number_format($row['amount'], 2); ?></td>
									<td><?php echo ucfirst($row['status']); ?></td>
									<td>
										<input type="hidden" name="purchase_ids[]" value="<?php echo $row['purchase_id']; ?>">
										<input type="hidden" name="purchase_amounts[<?php echo $row['purchase_id']; ?>]" value="<?php echo $row['amount']; ?>">
										<input type="number" step="0.01" name="invoice_payments[<?php echo $row['purchase_id']; ?>]" class="form-control" placeholder="Rs">
									</td>
								</tr>
								<?php endforeach; ?>
							</tbody>
						</table>

						<div class="row">
							<div class="col-md-4 mb-3">
								<label>Total Amount (Optional)</label>
								<input type="number" step="0.01" name="amount_paid" class="form-control" placeholder="If not entered above">
							</div>
							<div class="col-md-8 mb-3">
								<label>Remarks</label>
								<input type="text" name="remarks" class="form-control" placeholder="Payment remarks">
							</div>
						</div>

						<div class="col-md-4 mb-3">
    <label>Payment Method</label>
    <select name="payment_method" class="form-select" onchange="toggleBank(this.value)">
        <option value="cash">Cash</option>
        <option value="bank">Bank</option>
        <option value="card">Card</option>
        <option value="upi">UPI</option>
        <option value="credit">Credit</option>
    </select>
</div>

<div class="col-md-4 mb-3 d-none" id="bank-account-wrapper">
    <label>Bank Account</label>
    <select name="bank_account_id" class="form-select">
        <option value="">-- Select Bank --</option>
        <?php
        $banks = $conn->query("SELECT id, bank_name FROM bank_accounts WHERE is_active = 1");
        while ($b = $banks->fetch_assoc()) {
            echo "<option value='{$b['id']}'>" . htmlspecialchars($b['bank_name']) . "</option>";
        }
        ?>
    </select>
</div>

<script>
function toggleBank(method) {
    const show = ['bank', 'card', 'upi'].includes(method);
    document.getElementById('bank-account-wrapper').classList.toggle('d-none', !show);
}
</script>

<button type="submit" class="btn btn-success">Submit Payment</button>

					</form>
					<?php else: ?>
						<p>No outstanding dues for this supplier.</p>
					<?php endif; ?>
				</div>
			</div>
			<?php endif; ?>
		</div>
	</div>
</div>

<?php if (isset($_GET['success'])): ?>
<script>
Swal.fire({
	title: 'Payment Successful',
	text: 'Supplier payment recorded.',
	icon: 'success',
	timer: 2500,
	showConfirmButton: false
});
</script>
<?php endif; ?>

<script>
$(document).ready(function () {
	$('.select2').select2();
});
</script>
</body>
</html>
