<?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'];
    $number = (int)$_POST['page_num'];
    $serviceName = $_POST['servicename'];
    $startDate = $_POST['start_date'];
    $endDate = $_POST['end_date'];
    $startDateFormatted = DateTime::createFromFormat('d/m/Y', $startDate)->format('Y-m-d');
    $endDateFormatted = DateTime::createFromFormat('d/m/Y', $endDate)->format('Y-m-d');
    $result = $controller->getUserTransactionFilter($id,$serviceName, $startDateFormatted, $endDateFormatted);

    file_put_contents("eyeyeyel_log.txt", json_encode($serviceName));

    foreach ($result as &$transaction) {
        if ($transaction['servicename'] === 'Exam Pin') {
            $apiResponseLog = json_decode($transaction['api_response_log'], true);
            if (isset($apiResponseLog['pins'])) {
                $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'])) {
                $transaction['token'] = $apiResponseLog['data']['transaction']['meter_token'];
            }
        }
    }

    $response["status"] = "success";

    if ($number > 0) {
        $result = array_slice($result, 0, $number);
    }

    $response["transactions"] = $result;
    $modifiedJsonString = json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    echo $modifiedJsonString;
    exit();
}
?>
