<?php
declare(strict_types=1);

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

$productId = (int)($_GET['id'] ?? 0);
if ($productId <= 0) {
    Response::error('Invalid product id', 422);
}

/**
 * PRODUCT CORE
 */
$stmt = $db->prepare("
    SELECT
        id,
        product_name,
        slug,
        category_id,
        primary_sleep_id,
        secondary_sleep_id,
        short_description,
        full_description,
        brochure_file
    FROM retail_products
    WHERE id = :id
");
$stmt->execute(['id' => $productId]);

$product = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$product) {
    Response::error('Product not found', 404);
}

/**
 * SEO DATA
 */
$seoStmt = $db->prepare("
    SELECT
        meta_title,
        meta_description,
        meta_keywords,
        seo_schema,
        ai_seo_content
    FROM retail_products
    WHERE id = :id
");
$seoStmt->execute(['id' => $productId]);
$seo = $seoStmt->fetch(PDO::FETCH_ASSOC);

/**
 * VARIANTS
 */
$vStmt = $db->prepare("
    SELECT
        id,
        variant_name,
        sku,
        mrp,
        selling_price,
        size,
        firmness,
        thickness,
        specifications,
        status,
        sort_order
    FROM retail_product_variants
    WHERE product_id = :pid
    ORDER BY sort_order ASC
");
$vStmt->execute(['pid' => $productId]);

$variants = $vStmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($variants as &$v) {
    $v['specifications'] = $v['specifications']
        ? json_decode($v['specifications'], true)
        : null;
}

/**
 * IMAGES
 */
$iStmt = $db->prepare("
    SELECT
        id,
        image_path,
        alt_text,
        caption,
        is_featured,
        status
    FROM retail_product_images
    WHERE product_id = :pid
      AND status = 'Active'
    ORDER BY is_featured DESC, sort_order ASC
");
$iStmt->execute(['pid' => $productId]);

$images = $iStmt->fetchAll(PDO::FETCH_ASSOC);

/**
 * SECTIONS (BACKEND)
 */
$sStmt = $db->prepare("
    SELECT
        id,
        section_title,
        section_key,
        file_type,
        preview_type,
        file_path,
        thumbnail_path,
        alt_text,
        caption,
        priority,
        status,
        approval_status
    FROM retail_product_sections
    WHERE product_id = :pid
    ORDER BY priority ASC
");
$sStmt->execute(['pid' => $productId]);

$sections = $sStmt->fetchAll(PDO::FETCH_ASSOC);

/**
 * FINAL RESPONSE
 */
Response::success('Retail product fetched successfully', [
    'product'  => $product,
    'seo'      => $seo,
    'variants' => $variants,
    'images'   => $images,
    'sections' => $sections
]);
