<?php
$ROOT_DIR = $_SERVER['DOCUMENT_ROOT'];

require_once $ROOT_DIR . '/config.php';
require_once $ROOT_DIR . '/libraries/medoo/medoo.php';

$mdb = new medoo( [
    'database_type' => 'mysql',
    'database_name' => $database[ 'name' ],
    'server'        => $database[ 'host' ],
    'username'      => $database[ 'user' ],
    'password'      => $database[ 'password' ],
    'charset'       => 'utf8'
] );

header('Content-Type: application/json; charset=utf-8');

$sku = isset($_GET['sku']) ? $_GET['sku'] : null;
$productId = isset($_GET['id']) ? $_GET['id'] : null;

if ($sku) {
    $product = $mdb->get('pp_shop_products', '*', ['sku' => $sku]);

    if ($product) {
        $image = $mdb->get('pp_shop_products_images', '*', ['product_id' => $product['id']]);
        $productDescription = $mdb->get('pp_shop_products_langs', '*', ['product_id' => $product['id'], 'lang_id' => 'pl']);

        $productArr = [
            'id' => $product['id'],
            'name' => $productDescription ? $productDescription['name'] : '',
            'img' => $image ? ($settings['ssl'] ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $image['src'] : '',
            'price_netto' => $product['price_netto'],
            'price_brutto' => $product['price_brutto'],
            'sku' => $product['sku'],
            'ean' => $product['ean'],
            'date_added' => $product['date_add'],
        ];

        echo json_encode($productArr, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Product not found'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
} elseif ($productId) {
    $product = $mdb->get('pp_shop_products', '*', ['id' => $productId]);

    if ($product) {
        $image = $mdb->get('pp_shop_products_images', '*', ['product_id' => $product['id']]);
        $productDescription = $mdb->get('pp_shop_products_langs', '*', ['product_id' => $product['id'], 'lang_id' => 'pl']);

        $productArr = [
            'id' => $product['id'],
            'name' => $productDescription ? $productDescription['name'] : '',
            'img' => $image ? ($settings['ssl'] ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $image['src'] : '',
            'price_netto' => $product['price_netto'],
            'price_brutto' => $product['price_brutto'],
            'sku' => $product['sku'],
            'ean' => $product['ean'],
            'date_added' => $product['date_add'],
        ];

        echo json_encode($productArr, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Product not found'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
} else {
    http_response_code(400);
    echo json_encode(['error' => 'SKU or ID is missing'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}