<?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");

$headers = apache_request_headers();
$response = array();
$controller = new SubscriberModel;

date_default_timezone_set('Africa/Lagos');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $id = $_POST['user_id'] ?? null;
    file_put_contents("airtimeusss.txt", json_encode($id));

    if (!$id) {
        $response['status'] = 'fail';
        $response['msg'] = 'User ID is required';
        echo json_encode($response);
        exit();
    }

    $money = $controller->generateKudaAccount($id);
    file_put_contents("kuda.txt", json_encode($money));

    $result = $controller->setUserApp($id);
    $unread = $controller->getUnread($id);
    $virtualAccount = $controller->getVirtualAccount($id);

    file_put_contents("anawalog.txt", json_encode($result));

   if ($result->status === "fail") {
        header('HTTP/1.0 400 Invalid Network Id');
        $response['status'] = "fail";
        $response['msg'] = "The Network id is invalid";
        file_put_contents("airtime_fail_log.txt", json_encode($response));
        echo json_encode($response);
        exit();
    } else {
        $response = [
            'status' => 'success',
            'data' => $result,
            'unread' => $unread,
            'virtual_account' => $virtualAccount,
        ];
        file_put_contents("airtime_fail_log.txt", json_encode($response, JSON_UNESCAPED_SLASHES));
        echo json_encode($response, JSON_UNESCAPED_SLASHES);
        exit();
    }

} else {
    $response = ['status' => 'error', 'message' => 'Invalid request method'];
    echo json_encode($response);
    exit();
}

function formatUserType($value)
{
    $value = (float) $value;
    if ($value == 1) return "Smart";
    if ($value == 2) return "API";
    return "Vendor";
}
?>