<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");

/**
 * Функции возврата данных
 */

use App\Core\App;

require_once "vendor/autoload.php";

if (empty($_POST) || !$_POST['api_key'] || !$_POST['status']) {
    header('Location: /');
    exit;
}

$app = new App();
$app->init();

/**
 * Возвращает все записи
 * @return array|false
 */
function getAll($app)
{
    $sql = "select * from " . $_ENV['DB_NAME'] . ";";

    try {
        $stmt = $app->getDb()->query($sql);

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $app->getLogger()->error("Compressor: FETCH_ALL: " . $e->getMessage() . "\t>>>\t Query: " . $sql);
        return false;
    }
}

/**
 * Возвращает одну запись по ключу апи
 * @param $app
 * @param $apiKey
 * @return mixed|void
 */
function getOne($app, $apiKey, $status)
{
    $sql = "select * from";
    $sql .= " `" . $_ENV['DB_NAME'] . "`";
    $sql .= " where `api_key` = '" . $apiKey . "' ";
    $sql .= " and `status` = '" . $status . "';";

    try {
        return $app->getDb()->query($sql)->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $app->getLogger()->error("Compressor: FETCH: " . $e->getMessage() . "\t>>>\t Query: " . $sql);
        return false;
    }
}

function initApi($app)
{
    $apiKey = isset($_POST['api_key']) ? htmlspecialchars(trim($_POST['api_key'])) : null;
    $status = isset($_POST['status']) ? htmlspecialchars(trim($_POST['status'])) : null;
    $out = "";

    if ($apiKey && $apiKey !== '') {
        $data = getOne($app, $apiKey, $status);

        if ($data) {
            $out = $data['json_data'];
        } else {
            $out = json_encode(["error" => "No [$status] data for :: $apiKey"]);
        }
    } else {
        $out = json_encode(["error" => "empty data from POST", "POST" => $_POST]);
    }

    return $out;
}

//print_r($_POST);die();
//print_r(json_encode($_POST));die();

$data = initApi($app);
//print_r($data);die();
echo $data;
