<?php
require_once '../config/db.php'; // Adjust path as needed

// Fetch all supplies with 'Owing' status for the dropdown
$sql = "SELECT id, supplier_id, total_cost, total_paid FROM supplies WHERE status = 'Owing'";
$stmt = $pdo->query($sql);
$supplies = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $supply_id = $_POST['supply_id'];
    $amount_paid = $_POST['amount_paid'];
    $payment_date = date('Y-m-d'); // Current date
    $added_by = 'admin'; // Replace with dynamic user information if required

    // Fetch the supply details
    $sql = "SELECT total_cost, total_paid FROM supplies WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$supply_id]);
    $supply = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$supply) {
        echo "<script>alert('Invalid supply selected.'); history.back();</script>";
        exit();
    }

    // Calculate the new total paid
    $new_total_paid = $supply['total_paid'] + $amount_paid;

    // Ensure payment does not exceed the total cost
    if ($new_total_paid > $supply['total_cost']) {
        echo "<script>alert('Payment exceeds the remaining balance.'); history.back();</script>";
        exit();
    }

    // Record payment in the supply_payments table
    $sql = "INSERT INTO supply_payments (supply_id, amount_paid, payment_date, added_by) VALUES (?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$supply_id, $amount_paid, $payment_date, $added_by]);

    // Update supply details in the supplies table
    $status = ($new_total_paid >= $supply['total_cost']) ? 'Balanced' : 'Owing';
    $sql = "UPDATE supplies SET total_paid = ?, status = ? WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$new_total_paid, $status, $supply_id]);

    // Display success message
    echo "<script>alert('Payment successfully recorded!'); window.location.href = 'view_supplies.php';</script>";
    exit();
}
?>

<!-- Payment Form -->
<div class="card shadow-sm mb-4">
    <div class="card-header bg-primary text-white">
        <h4 class="mb-0">Record Payment for Supply</h4>
    </div>
    <div class="card-body">
        <form action="" method="POST">
            <div class="form-group">
                <label for="supply_id">Select Supply</label>
                <select class="form-control" id="supply_id" name="supply_id" required>
                    <option value="" disabled selected>-- Select Supply --</option>
                    <?php foreach ($supplies as $supply): ?>
                        <option value="<?= $supply['id'] ?>">
                            Supplier ID: <?= htmlspecialchars($supply['supplier_id']) ?> | Total Cost: ₦<?= number_format($supply['total_cost'], 2) ?> | Paid: ₦<?= number_format($supply['total_paid'], 2) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label for="amount_paid">Amount Paid</label>
                <input type="number" class="form-control" id="amount_paid" name="amount_paid" step="0.01" min="0" placeholder="Enter payment amount" required>
            </div>
            <button type="submit" class="btn btn-success w-100">Submit Payment</button>
        </form>
    </div>
</div>
