<?php
// mark_payment.php

// Include necessary files and configurations
include 'services/session.php';

include 'includes/dbconn.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $invoice_number = $_POST["invoice_number"];
    $payment_amount = $_POST["paymentAmount"];
    $payment_mode = $_POST["paymentMode"];
    $payment_reference = $_POST["paymentReference"];
    $balance = $_POST["balance"];

    // Retrieve the invoice details
    $invoice_query = "SELECT * FROM invoices WHERE invoice_number = '$invoice_number'";
    $invoice_result = mysqli_query($conn, $invoice_query);

    if ($invoice_result && mysqli_num_rows($invoice_result) > 0) {
        $invoice_row = mysqli_fetch_assoc($invoice_result);
        $total_amount = $invoice_row['total_amount'];
        $balance_amount = $invoice_row['balance'];

        // Check if payment amount is less than or equal to the balance
        if ($payment_amount <= $balance_amount) {
            // Deduct payment amount from the balance
            $new_balance = $balance_amount - $payment_amount;

            // Update the balance in the invoices table
            $update_balance_query = "UPDATE invoices SET balance = $new_balance WHERE invoice_number = '$invoice_number'";
            mysqli_query($conn, $update_balance_query);

            // Insert into payments table
            $insert_payment_query = "INSERT INTO payments (invoice_id, payment_amount, payment_date, payment_mode, payment_reference) 
                                     VALUES ('{$invoice_row['invoice_id']}', '$payment_amount', CURDATE(), '$payment_mode', '$payment_reference')";
            mysqli_query($conn, $insert_payment_query);

            // Return success response to the AJAX call
            echo json_encode(['success' => true]);
        } else {
            // Return failure response to the AJAX call
            echo json_encode(['success' => false, 'message' => 'Payment amount exceeds the balance.']);
        }
    } else {
        // Return failure response to the AJAX call
        echo json_encode(['success' => false, 'message' => 'Invoice not found.']);
    }

    mysqli_close($conn);
}
?>
