<?php
declare(strict_types=1);

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

$db = Database::getInstance();

/**
 * ==============================
 * INPUT
 * ==============================
 */
$slug    = $_GET['slug'] ?? null;
$preview = $_GET['preview'] ?? null;

if (!$slug) {
    Response::error('Product slug is required', 422);
}

$allowedPreview = ['Desktop', 'Mobile'];

if ($preview && !in_array($preview, $allowedPreview, true)) {
    Response::error('Invalid preview type', 422);
}

/**
 * ==============================
 * FETCH PRODUCT (PUBLIC SAFE)
 * ==============================
 */
$productStmt = $db->prepare("
    SELECT id, product_name, slug
    FROM retail_products
    WHERE slug = :slug
      AND status = 'Active'
      AND approval_status = 'Approved'
");

$productStmt->execute(['slug' => $slug]);
$product = $productStmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    Response::error('Product not found', 404);
}

/**
 * ==============================
 * FETCH SECTIONS (PUBLIC SAFE)
 * ==============================
 */
$sql = "
    SELECT
        id,
        section_title,
        file_type,
        preview_type,
        file_path,
        thumbnail_path,
        alt_text,
        caption,
        priority
    FROM retail_product_sections
    WHERE product_id = :product_id
      AND status = 'Active'
      AND approval_status = 'Approved'
";

$params = ['product_id' => $product['id']];

if ($preview) {
    $sql .= " AND preview_type IN ('Both', :preview)";
    $params['preview'] = $preview;
}

$sql .= " ORDER BY priority ASC";

$stmt = $db->prepare($sql);
$stmt->execute($params);

$sections = [];

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $sections[] = [
        'id'        => (int)$row['id'],
        'title'     => $row['section_title'],
        'type'      => $row['file_type'],
        'preview'   => $row['preview_type'],
        'file'      => $row['file_path'],
        'thumbnail' => $row['thumbnail_path'],
        'alt'       => $row['alt_text'],
        'caption'   => $row['caption'],
        'priority'  => (int)$row['priority']
    ];
}

/**
 * ==============================
 * RESPONSE
 * ==============================
 */
Response::success('Sections fetched successfully', [
    'product' => [
        'id'   => (int)$product['id'],
        'name' => $product['product_name'],
        'slug' => $product['slug']
    ],
    'sections' => $sections
]);
