<?php
include 'includes/config.php'; 

error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $invoice_no = $_POST['invoice_no'];
    $user_id = $_POST['user_id'];
    $credit_account = $_POST['credit_account'];
    $amount = $_POST['amount'];
    $payment_status = $_POST['payment_status'];
    $sale_date = $_POST['sale_date'];
    $due_amount = $_POST['due_amount'];

    if ($due_amount == 0) {
        echo "<script>alert('Cannot submit payment as the due amount is zero.');</script>";
        exit;
    }

    if (!$invoice_no || !$user_id || !$credit_account || !$amount || !$payment_status || !$sale_date) {
        echo "<script>alert('All fields are required.');</script>";
        exit;
    }

    $status = 'customer';

    $sql = "INSERT INTO cash_deposit (invoice, bank_id, user_id, amount, status, payment_status, date_deposit) 
            VALUES (:invoice_no, :credit_account, :user_id, :amount, :status, :payment_status, :sale_date)";

    $stmt = $conn->prepare($sql);

    $stmt->bindParam(':invoice_no', $invoice_no);
    $stmt->bindParam(':credit_account', $credit_account);
    $stmt->bindParam(':user_id', $user_id);
    $stmt->bindParam(':amount', $amount);
    $stmt->bindParam(':status', $status);
    $stmt->bindParam(':payment_status', $payment_status);
    $stmt->bindParam(':sale_date', $sale_date);

    try {
        $stmt->execute();
        echo "<script>alert('Payment added successfully!'); window.location.href='list_pos.php';</script>";
    } catch (PDOException $e) {
        echo "<script>alert('Error: " . $e->getMessage() . "');</script>";
    }
} else {
    echo "<script>alert('Invalid request method.');</script>";
}
?>
