<?php
include 'core/autoload.php';
include 'core/app/model/StoreProductData.php';

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

$page    = isset($_GET['page'])     ? (int) $_GET['page']     : 1;
$perPage = isset($_GET['per_page']) ? (int) $_GET['per_page'] : 12;

$page    = max(1, $page);
$perPage = max(1, min(60, $perPage));
$offset  = ($page - 1) * $perPage;

define('NOVEDADES_LIMIT', 60);

function nov_text_raw($value)
{
    return html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
}

function nov_img($image)
{
    $default = 'assets/images/error/01.png';
    if (!is_string($image) || $image === '') {
        return $default;
    }

    $image = trim($image);
    if (preg_match('/^https?:\/\//i', $image)) {
        return $image;
    }

    if (strpos($image, '/') !== false) {
        $cleanPath = ltrim($image, '/');
        if (file_exists(__DIR__ . '/' . $cleanPath)) {
            return $cleanPath;
        }
    }

    $filename  = basename($image);
    $extension = strtolower((string) pathinfo($filename, PATHINFO_EXTENSION));
    if (!in_array($extension, array('jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'), true)) {
        return $default;
    }

    $path = 'assets/images/products/' . $filename;
    if (file_exists(__DIR__ . '/' . $path)) {
        return $path;
    }

    return $default;
}

$items   = StoreProductData::getRecentProductsPaged($perPage, $offset, NOVEDADES_LIMIT);
$total   = min(StoreProductData::getPublicProductsCount('', ''), NOVEDADES_LIMIT);
$hasMore = ($offset + count($items)) < $total;

$out = array();
foreach ($items as $p) {
    $rawPrice   = isset($p['price']) ? (float) $p['price'] : 0;
    $priceFinal = (int) ceil($rawPrice * 0.87 * 1.4);

    $out[] = array(
        'id'           => (int) $p['id'],
        'name'         => nov_text_raw(isset($p['name'])  ? $p['name']  : ''),
        'brand'        => nov_text_raw(isset($p['brand']) ? $p['brand'] : ''),
        'code'         => nov_text_raw(isset($p['code'])  ? $p['code']  : ''),
        'price'        => $rawPrice,
        'price_final'  => $priceFinal,
        'stock_lapaz'  => isset($p['stock_lapaz'])   ? (int) $p['stock_lapaz']   : 0,
        'stock_interior' => isset($p['stock_interior']) ? (int) $p['stock_interior'] : 0,
        'image'        => nov_img(isset($p['image']) ? $p['image'] : ''),
    );
}

echo json_encode(array(
    'items'    => $out,
    'total'    => $total,
    'page'     => $page,
    'per_page' => $perPage,
    'has_more' => $hasMore,
));
