<?php
session_start();
require_once('../connect.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['payAmount'])) {
    $referenceCode = $_POST['reference_code'];
    $amountPaid = $_POST['payAmount'];
    $riceType = $_POST['rice_type'];
    $uniqueId = $_POST['unique_id'];
    $quantity = $_POST['quantity_kilo'];
    $datePurchase = $_POST['date_purchase'];
    $paymentDue = $_POST['payment_due'];

    $stmt = $conn->prepare("INSERT INTO tbl_bigasrecord (unique_id, rice_type, transaction_type, quantity_kilo, date_purchase, payment_due, bigas_credit_amount, payment_option, date_encoded, reference_code) 
                            VALUES (?, ?, 'Paid', ?, ?, ?, ?, 'Cash', NOW(), ?)");
    $stmt->bind_param("ssissds", $uniqueId, $riceType, $quantity, $datePurchase, $paymentDue, $amountPaid, $referenceCode);

    $updateStmt = $conn->prepare("UPDATE tbl_bigasrecord SET payment_option = 'Cash' WHERE reference_code = ? AND transaction_type = 'Order'");
    $updateStmt->bind_param("s", $referenceCode);

    if ($stmt->execute() && $updateStmt->execute()) {
        echo json_encode(["status" => "success", "message" => "Payment Successful!", "reference_code" => $referenceCode]);
    } else {
        echo json_encode(["status" => "error", "message" => "Payment Failed! Please try again."]);
    }
}
?>
