<?php
header('Content-Type: application/json');
session_start();
require_once('../connect.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate required fields
    $fields = ['id', 'rice_type', 'quantity_kilo', 'date_purchase', 'payment_due', 'bigas_credit_amount'];
    foreach ($fields as $field) {
        if (empty($_POST[$field])) {
            echo json_encode(['statusCode' => 400, 'message' => "Missing required field: $field"]);
            exit;
        }
    }

    // Assign variables
    $id = trim($_POST['id']);
    $rice_type = trim($_POST['rice_type']);
    $quantity_kilo = trim($_POST['quantity_kilo']);
    $date_purchase = trim($_POST['date_purchase']);
    $payment_due = trim($_POST['payment_due']);
    $bigas_credit_amount = trim($_POST['bigas_credit_amount']);

    // Additional values
    $date_encoded = date('Y-m-d');
    $reference_code = strtoupper(substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 10, 10));

    // Insert into database
    $sql = "INSERT INTO tbl_bigasrecord (date_encoded, unique_id, transaction_type, rice_type, quantity_kilo, date_purchase, payment_due, bigas_credit_amount, reference_code) 
            VALUES ('$date_encoded', '$id', 'order', '$rice_type', '$quantity_kilo', '$date_purchase', '$payment_due', '$bigas_credit_amount', '$reference_code')";

    if (mysqli_query($conn, $sql)) {
        echo json_encode(['statusCode' => 200, 'message' => 'Encoding successful.']);
    } else {
        echo json_encode(['statusCode' => 500, 'message' => 'Database error: ' . mysqli_error($conn)]);
    }

    mysqli_close($conn);
} else {
    echo json_encode(['statusCode' => 405, 'message' => 'Invalid request method.']);
}
