<?php

require './router.php';
require './simplepay/start.php';
require './simplepay/back.php';
require './simplepay/ipn.php';

$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Útvonalak regisztrálása
$routes = [
    ['GET', '/', 'productListHandler'],
    ['GET', '/termekek/{slug}', 'singleProductHandler'],
    ['POST', '/order-product/{id}', 'createOrderHandler'],
    ['GET', '/back/{orderId}', 'backHandler'],
    ['POST', '/ipn', 'ipnHandler'],
];

// Útvonalválasztó inicializálása
$dispatch = registerRoutes($routes);
$matchedRoute = $dispatch($method, $path);
$handlerFunction = $matchedRoute['handler'];
$handlerFunction($matchedRoute['vars']);

function singleProductHandler($vars)
{
    $pdo = getConnection();
    $stmt = $pdo->prepare("SELECT * FROM products WHERE slug = ?");
    $stmt->execute([$vars['slug']]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("SELECT * FROM orders WHERE userId = 1 AND productId = ? AND (status = 'INITIALIZED' OR status = 'STARTED')");
    $stmt->execute([$product['id']]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);


    echo render("wrapper.phtml", [
        'title' => $product['name'],
        'description' => $product['description'],
        'content' => render('product.phtml', [
            'product' => $product,
            'url' => siteUrl() . "/termekek/" . $product['slug'],
            'paymentUrl' => $order ? getPaymentUrl($order, $product) : "",
            'status' => $_GET['status'] ?? '',
            'transactionId' => $_GET['transactionId'] ?? '',
        ]),
    ]);
}

function createOrderHandler($vars)
{
    $pdo = getConnection();
    $stmt = $pdo->prepare("INSERT INTO `orders` (`userId`, `productId`, `ref`, `status`) VALUES (?, ?, ?, ?);");
    $stmt->execute([1, $vars['id'], uniqid(), "INITIALIZED"]);

    header('Location: ' . $_SERVER['HTTP_REFERER']);
}

function backHandler($vars)
{
    back($vars['orderId']);
}

function ipnHandler()
{
    ipn();
}

function productListHandler()
{
    $pdo = getConnection();
    $stmt = $pdo->prepare("SELECT * FROM products");
    $stmt->execute([]);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo render("wrapper.phtml", [
        'title' => "Termékek",
        'description' => "Termék lista",
        'content' => render('product-list.phtml', [
            'products' => $products,
        ]),
    ]);
}

function notFoundHandler()
{
    echo "Útvonal nem található";
}

function render($path, $params = [])
{
    ob_start();
    require __DIR__ . '/views/' . $path;
    return ob_get_clean();
}

function getConnection()
{
    return new PDO(
        'mysql:host=' . $_SERVER['DB_HOST'] . ';dbname=' . $_SERVER['DB_NAME'],
        $_SERVER['DB_USER'],
        $_SERVER['DB_PASSWORD']
    );
}

function siteUrl()
{
    return (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
}
