<?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') {
    $userId = $_POST['user_id'];
    
    // Get the Base64 image string from POST request
    $image = $_POST['image']; // Expecting 'image' key to contain Base64 string

    // Check if the image is provided
    if (empty($image)) {
        header('HTTP/1.0 400 Bad Request');
        $response['status'] = false;
        $response['msg'] = "No image provided";
        echo json_encode($response);
        exit();
    }

 // Check if the image is provided
    if (empty($userId)) {
        header('HTTP/1.0 400 Bad Request');
        $response['status'] = false;
        $response['msg'] = "No id provided";
        echo json_encode($response);
        exit();
    }

    // Process the Base64-encoded image
    $imageData = base64_decode($image);

    // Assuming you want to call 'setUserPics' with the user ID and image data
    $result = $controller->setUserPics($userId, $imageData);

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

    if ($result["status"] == "fail") {
        header('HTTP/1.0 400 Invalid Network Id');
        $response['status'] = false;
        $response['msg'] = "The Network id is invalid";
        echo json_encode($response);
        exit();
    } else {
        // Return a boolean status and the image name
        $response = array('status' => true, 'image_name' => $result['image_name']);
        file_put_contents("airtime_success_log.txt", json_encode($response));
        echo json_encode($response);
    }
} else {
    $response = array('status' => 'error', 'message' => 'Invalid request method');
    echo json_encode($response);
}
?>      
