<?php
require_once("../../autoloader.php");
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST, GET");
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'] === 'GET') {

    $id = 2;
    $number = 0;
    
    // Write page number to a file (optional)
    file_put_contents("anumber.txt", $number);

    // Retrieve user transactions
    $result = $controller->getUserTransaction($id);

    // Check if the result is an array and handle slicing based on page_num
    if (is_array($result) && count($result) > 0) {
        if ($number > 0) {
            $result = array_slice($result, 0, $number); // Limit results
        }

       // Iterate through transactions to modify as needed
        foreach ($result as &$transaction) {
            // Check for the specific service names and add corresponding fields
            if ($transaction['servicename'] === 'Exam Pin') {
                $apiResponseLog = json_decode($transaction['api_response_log'], true);
                if (isset($apiResponseLog['pins'])) {
                    // Extract pin, cleaning up the string
                    $transaction['pin'] = trim($apiResponseLog['pins']);
                }
            } elseif ($transaction['servicename'] === 'Electricity Bill') {
                $apiResponseLog = json_decode($transaction['api_response_log'], true);
                if (isset($apiResponseLog['data']['transaction']['meter_token'])) {
                    // Extract meter_token
                    $transaction['token'] = $apiResponseLog['data']['transaction']['meter_token'];
                }
                if (isset($apiResponseLog['data']['transaction']['meter_units'])) {
                    // Extract meter_units
                    $transaction['meter_units'] = $apiResponseLog['data']['transaction']['meter_units'];
                }
            }
        }

        $response["status"] = "success";
        $response["transactions"] = $result; // Set transactions to response

        // Return success response
        echo json_encode($response);
        exit();
    } else {
        // Handle case where no transactions are found
        $response["status"] = "error";
        $response["message"] = "No transactions found for the user.";
        echo json_encode($response);
        exit();
    }
}

// If the request method is not POST, return method not allowed
http_response_code(405); // Method Not Allowed
echo json_encode(["status" => "error", "message" => "Method not allowed."]);
exit();
?>
