<?php
header('Content-Type: application/json');
session_start();
require_once('../connect.php');
// Set timezone to Manila
date_default_timezone_set('Asia/Manila');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate required fields
    $fields = ['id', 'waterbill_amount', 'payment_date', 'modeofpay', 'select_readingdate', 'payment_ref'];
    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']);
    $waterbill_amount = trim($_POST['waterbill_amount']);
    $payment_date = trim($_POST['payment_date']);
    $modeofpay = trim($_POST['modeofpay']);
    $select_readingdate = trim($_POST['select_readingdate']);
    $payment_ref = trim($_POST['payment_ref']);
    
    // Additional values
 $date_encoded = date('Y-m-d h:i:s A');
    $upload_image = 'N/A';

    // Insert into database
    $sql = "INSERT INTO tbl_payments 
            (referrence_code, unique_id, payment_type, amount, payment_date, reading_date, receipt_url, payment_option, date_encoded) 
            VALUES 
            ('$payment_ref', '$id', 'WB', '$waterbill_amount', '$payment_date', '$select_readingdate', '$upload_image', '$modeofpay', '$date_encoded')";

    if (mysqli_query($conn, $sql)) {
        echo json_encode(['statusCode' => 200, 'message' => 'Payment added successfully!']);
    } 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.']);
}
