<?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);

$payment_method = $_POST['payment_method'] ?? 'cash';
$account_id = !empty($_POST['bank_account_id']) ? intval($_POST['bank_account_id']) : null;

$invoice_payments = array_filter($invoice_payments, fn($v) => floatval($v) > 0);
$has_manual = count($invoice_payments) > 0;

$conn->begin_transaction();

try {
	$total_logged = 0;

	if ($has_manual) {
		foreach ($invoice_payments as $sale_id => $paid) {
			$paid = floatval($paid);
			if ($paid <= 0) continue;

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

			$os = $conn->query("SELECT amount FROM cus_outstanding WHERE sale_id = $sale_id")->fetch_assoc();
			$new_balance = $os['amount'] - $paid;
			$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_logged += $paid;
		}
	} else {
		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;
			$total_logged += $paying_now;
		}
	}

	// Log to account_transactions if not credit
	if ($payment_method !== 'credit' && $total_logged > 0) {
		$desc = ucfirst($payment_method) . " payment from customer ID $customer_id";
		$insert = $conn->prepare("INSERT INTO account_transactions (sale_id, account_type, account_id, amount, description) VALUES (NULL, ?, ?, ?, ?)");
		$insert->bind_param("sids", $payment_method, $account_id, $total_logged, $desc);
		$insert->execute();
		$insert->close();
	}

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

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