<?php

header("Content-Type: application/json");

// Force background error logs off to maintain pristine JSON parser metrics
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

require_once '../config/database.php';

$db = getDB();

$categoryId = intval($_GET['category_id'] ?? 0);

if ($categoryId <= 0) {
    echo json_encode([
        "success" => false,
        "message" => "Invalid Category"
    ]);
    exit;
}

// Ensure BASE_URL is declared locally if absent from primary configuration dependencies
if (!defined('BASE_URL')) {
    define('BASE_URL', 'https://globinvest.online/api/');
}

$products = [];

$query = $db->query("
    SELECT *
    FROM products
    WHERE category_id = $categoryId
    AND is_active = 1
    ORDER BY id DESC
");

if ($query) {
    while ($row = $query->fetch_assoc()) {
        $fullImages = [];

        // =====================
        // IMAGES & GALLERY FALLBACK EXTRACTION (FIXED)
        // =====================
        if (!empty($row['images'])) {
            $images = json_decode($row['images'], true);

            if (is_array($images)) {
                // Scenario A: Stored as a valid string array -> ["burger.jpg"]
                foreach ($images as $img) {
                    $cleanImg = str_replace('uploads/products/', '', $img);
                    $fullImages[] = BASE_URL . "uploads/products/" . $cleanImg;
                }
            } else {
                // Scenario B: Stored as a raw plain string filename -> burger.jpg
                $cleanImg = str_replace('uploads/products/', '', $row['images']);
                $fullImages[] = BASE_URL . "uploads/products/" . $cleanImg;
            }
        }

        // =====================
        // PACKAGE PRODUCT MAP DATA ENTRIES
        // =====================
        $products[] = [
            "id"             => intval($row['id']),
            "category_id"    => intval($row['category_id']),
            "name_en"        => $row['name_en'] ?? '',
            "name_bn"        => $row['name_bn'] ?? '',
            "description_en" => $row['description_en'] ?? '',
            "description_bn" => $row['description_bn'] ?? '',
            "price"          => floatval($row['price'] ?? 0),
            "old_price"      => !empty($row['old_price']) ? floatval($row['old_price']) : null,
            "stock"          => intval($row['stock'] ?? 0),
            "avg_rating"     => floatval($row['avg_rating'] ?? 4.9),
            "review_count"   => intval($row['review_count'] ?? 0),
            "is_featured"    => intval($row['is_featured'] ?? 0),
            "is_new"         => intval($row['is_new'] ?? 0),
            "total_sales"    => intval($row['total_sales'] ?? 0),
            "created_at"     => $row['created_at'] ?? '',
            "images"         => $fullImages,
            // CRITICAL: Mapped explicitly as a single string to fix your card component display pipeline
            "image"          => (count($fullImages) > 0) ? $fullImages[0] : "", 
        ];
    }
}

// =====================
// OUTPUT CLEAN VALID PAYLOAD
// =====================
echo json_encode([
    "success" => true,
    "data" => [
        "products" => $products
    ]
]);