<?php

require './router.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);

    echo render("wrapper.phtml", [
        'title' => $product['name'],
        'description' => $product['description'],
        'content' => render('product.phtml', [
            'product' => $product,
            'url' => siteUrl() . "/termekek/" . $product['slug'],
        ]),
    ]);
}

function createOrderHandler($vars)
{
    
}

function backHandler($vars)
{
}

function ipnHandler()
{
}

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'];
}
