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

date_default_timezone_set('Africa/Lagos');

$response = [];
$controller = new SubscriberModel;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id       = $_POST['user_id'] ?? null;
    $phone    = $_POST['phoneNumber'] ?? null;
    $network  = $_POST['network'] ?? null;
    $name     = $_POST['disconame'] ?? null;
    $meterno  = $_POST['meterNumber'] ?? null;

    // Validate required fields (optional but recommended)
    if (!$id || !$phone || !$network || !$name || !$meterno) {
        $response = ['status' => 'fail', 'msg' => 'Missing required fields'];
        http_response_code(400);
        echo json_encode($response);
        exit();
    }

    // Call the model method
    $result = $controller->saveBeneficiaryElectricity($id, $network, $phone, $name, $meterno);

    // If result is already an array, no need to decode
    $ress = is_array($result) ? $result : json_decode($result, true);

    file_put_contents("airtime_fail_log.txt", json_encode($ress, JSON_UNESCAPED_SLASHES));

    if ($ress['status'] === "fail") {
        http_response_code(400);
        $response = [
            'status' => 'fail',
            'msg' => $ress['msg']
        ];
        echo json_encode($response);
        exit();
    } else {
        http_response_code(200);
        echo json_encode(['status' => 'success'], JSON_UNESCAPED_SLASHES);
        exit();
    }

} else {
    http_response_code(405); // Method not allowed
    $response = ['status' => 'error', 'message' => 'Invalid request method'];
    file_put_contents("airtime_fail_log.txt", json_encode($response));
    echo json_encode($response);
}
