<?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') {
    // Ensure the user ID is present in the request
    if (isset($_POST['user']) && !empty($_POST['user'])) {
        $id = $_POST['user'];

        // Call the setUserDeleted function and decode the JSON response
        $result = json_decode($controller->setUserDeleted($id), true);

        // Check the result status
        if ($result['status'] === 'fail') {
            // Return 400 status code for failure
            http_response_code(400);
            $response['status'] = 'fail';
            $response['msg'] = $result['message'];

            // Log failure to a file
            file_put_contents("airtime_fail_log.txt", json_encode($response));
            
            echo json_encode($response);
            exit();
        } else {
            // Success: Return the success message
            http_response_code(200);
            $response['status'] = 'success';
            $response['msg'] = $result['message'];

            // Return the response as JSON
            echo json_encode($response);
            exit();
        }
    } else {
        // Handle missing user ID
        http_response_code(400);
        $response = array('status' => 'fail', 'message' => 'User ID is required');
        file_put_contents("airtime_fail_log.txt", json_encode($response));
        echo json_encode($response);
        exit();
    }
} else {
    // Handle invalid request methods
    http_response_code(405); // 405 Method Not Allowed
    $response = array('status' => 'error', 'message' => 'Invalid request method');
    file_put_contents("airtime_fail_log.txt", json_encode($response));
    echo json_encode($response);
    exit();
}
?>
