<?php
ini_set('session.gc_maxlifetime', 360000);
session_set_cookie_params(360000);
session_start();

require_once('../connect.php');
require_once('sql_required.php');

// Ensure no extra output
if (ob_get_length()) { ob_end_clean(); }

// Always JSON
header('Content-Type: application/json; charset=utf-8');

function respond($arr, $code = 200) {
    http_response_code($code);
    echo json_encode($arr);
    exit;
}

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        respond(['status' => 'error', 'message' => 'Invalid method.'], 405);
    }

    if (!isset($_POST['type']) || $_POST['type'] !== '1') {
        respond(['status' => 'error', 'message' => 'Invalid request type.'], 400);
    }

    $required = ['acctnumber','accntholder','fname','lname','address','branch'];
    foreach ($required as $key) {
        if (empty($_POST[$key])) {
            respond(['status' => 'error', 'message' => "Missing field: $key"], 400);
        }
    }

    // Sanitize
    $acctnumber      = mysqli_real_escape_string($conn, $_POST['acctnumber']);
    $accntholder     = mysqli_real_escape_string($conn, $_POST['accntholder']);
    $fname           = mysqli_real_escape_string($conn, $_POST['fname']);
    $lname           = mysqli_real_escape_string($conn, $_POST['lname']);
    $address         = mysqli_real_escape_string($conn, $_POST['address']);
    $branch          = mysqli_real_escape_string($conn, $_POST['branch']);
    $pres_reading    = 0;
    $date_registered = isset($thedatetoday) ? $thedatetoday : date('Y-m-d H:i:s');
    $line_status     = 1;

    $sql = "INSERT INTO tbl_user_account 
                (unique_id, acct_holder, firstname, lastname, home_address, branch, pres_reading, date_registered, line_status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = mysqli_prepare($conn, $sql);
    if (!$stmt) {
        respond(['status' => 'error', 'message' => 'Prepare failed: ' . mysqli_error($conn)], 500);
    }

    mysqli_stmt_bind_param(
        $stmt,
        "ssssssisi",
        $acctnumber,
        $accntholder,
        $fname,
        $lname,
        $address,
        $branch,
        $pres_reading,
        $date_registered,
        $line_status
    );

    if (!mysqli_stmt_execute($stmt)) {
        $err = mysqli_stmt_error($stmt);
        mysqli_stmt_close($stmt);
        respond(['status' => 'error', 'message' => 'Failed to save: ' . $err], 500);
    }

    mysqli_stmt_close($stmt);
    respond(['status' => 'success', 'message' => 'Member has been saved successfully.']);

} catch (Throwable $e) {
    respond(['status' => 'error', 'message' => 'Unexpected error: ' . $e->getMessage()], 500);
}
