<?php
require_once("../../autoloader.php");
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST");
header("Allow: POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Origin");

$response = array();
$controller = new SubscriberModel;
date_default_timezone_set('Africa/Lagos');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieving posted form data
    $fname = $_POST['fname'] ?? '';
     $id = $_POST['id'] ?? '';
    $lname = $_POST['lname'] ?? '';
    $address = $_POST['address'] ?? '';
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? ''; // using 'email' instead of 'id'

    // Validating input (optional but recommended)
    if (empty($id)) {
        $response['status'] = 'fail';
        $response['message'] = 'ID is required';
        echo json_encode($response);
        exit();
    }
        file_put_contents("airtime_fail_log.txt", json_encode($fname));
    // Attempt to update user bio
    $result = $controller->setUserBio($id, $fname, $lname);
    
    // Handling the result
    if ($result["status"] == "fail") {
        header('HTTP/1.0 400 Invalid Network Id');
        $response['status'] = "fail";
        $response['message'] = "The Network ID is invalid";

        echo json_encode($response);
        exit();
    } else {
        // Construct success response
        $data = array(
            "id" => $result["Id"] ?? null,
            "username" => $result["username"] ?? $username,
            "fname" => $result["fname"] ?? $fname,
            "lname" => $result["lname"] ?? $lname,
            "email" => $result["email"] ?? $email,
            "image_name" => $result["image"] ?? "default_image_url",
            "phone" => $result["phone"] ?? '',
            "age" => $result["age"] ?? '',
            "sex" => $result["sex"] ?? 'Male',
            "address" => $result["address"] ?? $address,
            "date_created" => $result["date"] ?? date('Y-m-d H:i:s'),
            "isbank_verify" => $result["isbank_verify"] ?? false,
            "pin" => $result["pin"] ?? '',
            "pin_set" => $result["pin_set"] ?? false,
            "status" => "success"
        );
        
   
        echo json_encode($data);
        exit();
    }
} else {
    $response = array('status' => 'error', 'message' => 'Invalid request method');
 
    echo json_encode($response);
}
?>
