<?php
require_once "../config/db.php";

$invoice_id   = (int) $_POST['invoice_id'];
$amount       = (float) $_POST['amount'];
$date         = $_POST['payment_date'];
$method       = $_POST['method'];

// validation
if($amount <= 0){
    die("Invalid amount");
}

// check pending
$total = $conn->query("SELECT total FROM invoices WHERE id=$invoice_id")->fetch_assoc()['total'];

$paid = $conn->query("
SELECT SUM(amount) as paid FROM payments WHERE invoice_id=$invoice_id
")->fetch_assoc()['paid'] ?? 0;

$pending = $total - $paid;

if($amount > $pending){
    die("Amount exceeds pending");
}

// insert payment
$stmt = $conn->prepare("
INSERT INTO payments (invoice_id, amount, payment_date, method)
VALUES (?,?,?,?)
");

$stmt->bind_param("idss", $invoice_id, $amount, $date, $method);
$stmt->execute();

// OPTIONAL: update status
$newPaid = $paid + $amount;

$status = ($newPaid >= $total) ? 'paid' : 'partial';

$conn->query("UPDATE invoices SET payment_status='$status' WHERE id=$invoice_id");

header("Location: ../pages/invoices.php");
exit;