<?php
include 'db.php';

$vendor_id = intval($_POST['vendor_id']);
$remarks = $conn->real_escape_string($_POST['remarks'] ?? '');
$purchase_ids = $_POST['purchase_ids'] ?? [];
$purchase_amounts = $_POST['purchase_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;

// Filter out empty manual entries
$invoice_payments = array_filter($invoice_payments, fn($v) => floatval($v) > 0);
$has_manual = count($invoice_payments) > 0;

$conn->begin_transaction();

try {
    $logged_total = 0;
    $reference_purchase_id = 0;

    if ($has_manual) {
        // Manual payments per purchase
        foreach ($invoice_payments as $purchase_id => $paid) {
            $paid = floatval($paid);
            if ($paid <= 0) continue;

            // Insert payment
            $conn->query("INSERT INTO sup_payments (vendor_id, purchase_id, amount_paid, remarks) 
                VALUES ($vendor_id, $purchase_id, $paid, '$remarks')");

            // Fetch outstanding amount
            $os = $conn->query("SELECT amount FROM sup_outstanding WHERE purchase_id = $purchase_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 sup_outstanding SET amount = $new_amount, status = '$status' WHERE purchase_id = $purchase_id");

            $logged_total += $paid;
            if ($reference_purchase_id == 0) {
                $reference_purchase_id = $purchase_id;
            }
        }
    } else {
        // Distribute total amount
        foreach ($purchase_ids as $purchase_id) {
            if ($total_paid <= 0) break;

            $purchase_id = intval($purchase_id);
            $due = floatval($purchase_amounts[$purchase_id]);

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

            $conn->query("INSERT INTO sup_payments (vendor_id, purchase_id, amount_paid, remarks) 
                VALUES ($vendor_id, $purchase_id, $paying_now, '$remarks')");

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

            $total_paid -= $paying_now;
            $logged_total += $paying_now;
            if ($reference_purchase_id == 0) {
                $reference_purchase_id = $purchase_id;
            }
        }
    }

    // ✅ Log into account_transactions
    if ($logged_total > 0 && $reference_purchase_id > 0) {
        $desc = "Supplier payment for Vendor ID $vendor_id";

        $log_stmt = $conn->prepare("INSERT INTO account_transactions 
            (sale_id, account_type, account_id, amount, description)
            VALUES (?, ?, ?, ?, ?)");
        $log_stmt->bind_param("isids", $reference_purchase_id, $payment_method, $account_id, $logged_total, $desc);
        $log_stmt->execute();
        $log_stmt->close();
    }

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

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