<?php
require '../config/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $owing_id = $_POST['owing_id'];
    $payment_amount = $_POST['payment_amount'];

    // Fetch current amount and amount_paid from the owings table
    $sql = "SELECT amount, amount_paid FROM owings WHERE id = :owing_id";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['owing_id' => $owing_id]);
    $result = $stmt->fetch();

    if ($result) {
        $current_amount = $result['amount'];
        $current_amount_paid = $result['amount_paid'];

        // Check if payment amount is less than or equal to the current owed amount
        if ($payment_amount <= ($current_amount)) {
            // Calculate the new total amount paid
            $new_amount_paid = $current_amount_paid + $payment_amount;

            // Calculate the new amount left to pay by subtracting the payment amount
            $new_amount = $current_amount - $payment_amount;

            // Update the owings table with the new amount and new amount paid
            $sql = "UPDATE owings SET amount = :new_amount, amount_paid = :new_amount_paid WHERE id = :owing_id";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(['new_amount' => $new_amount, 'new_amount_paid' => $new_amount_paid, 'owing_id' => $owing_id]);

            // Update the status if the amount is fully paid
            if ($new_amount <= 0) {
                $sql = "UPDATE owings SET status = 'Paid' WHERE id = :owing_id";
                $stmt = $pdo->prepare($sql);
                $stmt->execute(['owing_id' => $owing_id]);
            }

            // Insert payment details into the payments table
            $sql = "INSERT INTO payments (owing_id, amount_paid, payment_date) 
                    VALUES (:owing_id, :payment_amount, NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                'owing_id' => $owing_id,
                'payment_amount' => $payment_amount
            ]);

            // Redirect or return success message
            header('Location: owing_management.php');
            exit();
        } else {
            // Handle error: payment amount exceeds owed balance
            echo "Error: Payment amount is greater than the amount owed.";
        }
    } else {
        // Handle error: no owing record found
        echo "Error: No such owing record found.";
    }
}
?>
