<?php 
session_start();
require_once('../connect.php');
// Set timezone to Manila
date_default_timezone_set('Asia/Manila');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve form inputs
    $id = $_POST['id'];
    $acctholder = $_POST['acctholder'];
    $postdate = $_POST['postdate'];
    $prev_reading = $_POST['prev_reading'];
    $newreading = $_POST['newreading'];
    $duedate = $_POST['duedate'];
    $disconnection = $_POST['disconnection'];
    $datetoday = date('Y-m-d h:i:s A');
    $reading_result = $_POST['reading_result'];
    // $reading_result_bill = $_POST['reading_result_bill'];
    if ($reading_result < 5) {
        $reading_result_bill = 200;  // Use = for assignment
    } else {
        $reading_result_bill = $_POST['reading_result_bill'];
    }
    
    // Update `tbl_user_account`
    $sql_update = "UPDATE tbl_user_account SET pres_reading = ? WHERE unique_id = ?";
    $stmt_update = $conn->prepare($sql_update);
    $stmt_update->bind_param('ss', $newreading, $id);
    if (!$stmt_update->execute()) {
        echo json_encode(['status' => 'error', 'message' => 'Failed to update user account: ' . $stmt_update->error]);
        exit;
    }
 

   
    // Insert into `tbl_members_report`
    $sql_insert = "INSERT INTO tbl_members_report (reading_date, account_no, account_name, prev_reading, pres_reading, total_reading, billing_amount, transaction_date, due_date, disconnection_date, completed) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)";
    $stmt_insert = $conn->prepare($sql_insert);
    $stmt_insert->bind_param(
        'ssssssssss',
        $postdate,
        $id,
        $acctholder,
        $prev_reading,
        $newreading,
        $reading_result,
        $reading_result_bill,
        $datetoday,
        $duedate,
        $disconnection
    );

    if ($stmt_insert->execute()) {
        echo json_encode(['status' => 'success', 'message' => 'Meter reading has been saved successfully.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to save meter reading: ' . $stmt_insert->error]);
    }
}
?>
