<?php
include 'db.php';

$customer_id = intval($_POST['customer_id']);
$remarks = $conn->real_escape_string($_POST['remarks'] ?? '');
$sale_ids = $_POST['sale_ids'] ?? [];
$sale_amounts = $_POST['sale_amounts'] ?? [];
$invoice_payments = $_POST['invoice_payments'] ?? [];
$total_paid = floatval($_POST['amount_paid'] ?? 0);

// Normalize invoice-specific entries
$invoice_payments = array_filter($invoice_payments, fn($v) => floatval($v) > 0);
$has_manual = count($invoice_payments) > 0;

$conn->begin_transaction();

try {
	if ($has_manual) {
		// Use manual values
		foreach ($invoice_payments as $sale_id => $paid) {
			$paid = floatval($paid);
			if ($paid <= 0) continue;

			// Insert payment
			$conn->query("INSERT INTO cus_payments (customer_id, sale_id, amount_paid, remarks) 
				VALUES ($customer_id, $sale_id, $paid, '$remarks')");

			// Get outstanding
			$os = $conn->query("SELECT amount FROM cus_outstanding WHERE sale_id = $sale_id")->fetch_assoc();
			$new_balance = $os['amount'] - $paid;

			// Update status
			$status = $new_balance <= 0 ? 'paid' : 'partial';
			$new_amount = max(0, $new_balance);
			$conn->query("UPDATE cus_outstanding SET amount = $new_amount, status = '$status' WHERE sale_id = $sale_id");
		}
	} else {
		// Auto distribute total
		foreach ($sale_ids as $sale_id) {
			if ($total_paid <= 0) break;

			$sale_id = intval($sale_id);
			$due = floatval($sale_amounts[$sale_id]);

			$paying_now = min($total_paid, $due);

			$conn->query("INSERT INTO cus_payments (customer_id, sale_id, amount_paid, remarks) 
				VALUES ($customer_id, $sale_id, $paying_now, '$remarks')");

			$new_balance = $due - $paying_now;
			$status = $new_balance <= 0 ? 'paid' : 'partial';
			$new_amount = max(0, $new_balance);
			$conn->query("UPDATE cus_outstanding SET amount = $new_amount, status = '$status' WHERE sale_id = $sale_id");

			$total_paid -= $paying_now;
		}
	}

	$conn->commit();
header("Location: customer_payments.php?customer_id=$customer_id&success=1");
exit;


} catch (Exception $e) {
	$conn->rollback();
	die("Error: " . $e->getMessage());
}
?>
