<?php

/**
 * Product Normalizer / Presenter (Minimal Helper)
 */

function product_normalize(array $product): array
{
    // Canonical fields (Source of truth)
    $title       = (string)($product['title'] ?? $product['name'] ?? '');
    $description = (string)($product['description'] ?? $product['short_description'] ?? '');
    $currency    = (string)($product['currency'] ?? 'DZD');

    // Prices (keep original values but ensure availability)
    $price      = $product['price'] ?? null;
    $sale_price = $product['sale_price'] ?? null;
    $old_price  = $product['old_price'] ?? null; // legacy/optional

    // Images:
    // - featured_image is a web path (/uploads/products/...)
    // - images is JSON-decoded array in ProductModel::decodeJsonFields()
    $images = [];
    if (isset($product['images']) && is_array($product['images'])) {
        $images = $product['images'];
    } elseif (!empty($product['gallery']) && is_array($product['gallery'])) {
        $images = $product['gallery'];
    }

    $featured_image = (string)($product['featured_image'] ?? $product['image'] ?? '');
    if ($featured_image === '' && !empty($images[0]) && is_string($images[0])) {
        $featured_image = $images[0];
    }

    // Canonical output
    $normalized = $product;

    // Canonical keys (preferred for all sections going forward)
    $normalized['title']        = $title;
    $normalized['description']  = $description;
    $normalized['currency']     = $currency;

    $normalized['price']        = $price;
    $normalized['sale_price']   = $sale_price;

    // Provide a single "old_price" key commonly used by landing templates
    // Priority: explicit old_price > price when sale_price exists
    if ($old_price !== null) {
        $normalized['old_price'] = $old_price;
    } elseif ($sale_price !== null && $price !== null) {
        $normalized['old_price'] = $price;
    } else {
        $normalized['old_price'] = $old_price; // keep as-is (null)
    }

    $normalized['image']         = $featured_image; // canonical "image"
    $normalized['featured_image']= $featured_image; // keep source field consistent
    $normalized['gallery']       = $images;         // canonical "gallery"
    $normalized['images']        = $images;         // keep source field consistent

    // Backward-compatible aliases to stop Undefined array key in legacy sections
    // (حتى ننقل الأقسام تدريجيًا لمفاتيح canonical بدون تكسير)
    $normalized['name'] = $normalized['title'];

    return $normalized;
}
