<?php
declare(strict_types=1);

ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../../security/auth_guard.php';
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../core/Response.php';
require_once __DIR__ . '/../../../core/Validator.php';

$db = Database::getInstance();

/**
 * ==============================
 * METHOD CHECK
 * ==============================
 */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Invalid request method', 405);
}

/**
 * ==============================
 * INPUT
 * ==============================
 */
$input = json_decode(file_get_contents('php://input'), true);

if (!is_array($input)) {
    Response::error('Invalid JSON payload');
}

/**
 * ==============================
 * PRODUCT ID (ONLY REQUIRED)
 * ==============================
 */
if (empty($input['product_id'])) {
    Response::error('product_id is required');
}

$productId = (int)$input['product_id'];

/**
 * ==============================
 * OPTIONAL FIELDS
 * ==============================
 */
$sectionTitle  = trim($input['section_title'] ?? null);
$sectionKey    = trim($input['section_key'] ?? null);
$fileType      = $input['file_type'] ?? 'Image';
$previewType   = $input['preview_type'] ?? 'Both';
$filePath      = trim($input['file_path'] ?? null);
$thumbnailPath = trim($input['thumbnail_path'] ?? null);
$altText       = trim($input['alt_text'] ?? null);
$caption       = trim($input['caption'] ?? null);
$priority      = isset($input['priority']) ? (int)$input['priority'] : 0;
$isLazyLoad    = isset($input['is_lazy_load']) ? (int)$input['is_lazy_load'] : 1;

/**
 * ==============================
 * ENUM VALIDATION (ONLY IF PASSED)
 * ==============================
 */
if (!in_array($fileType, ['Image', 'Video'], true)) {
    Response::error('Invalid file_type');
}

if (!in_array($previewType, ['Desktop', 'Mobile', 'Both'], true)) {
    Response::error('Invalid preview_type');
}

/**
 * ==============================
 * PRODUCT EXISTS CHECK
 * ==============================
 */
$stmt = $db->prepare("SELECT id FROM retail_products WHERE id = :id");
$stmt->execute(['id' => $productId]);

if (!$stmt->fetch()) {
    Response::error('Invalid product_id');
}

/**
 * ==============================
 * DUPLICATE CHECK (ONLY IF section_key EXISTS)
 * ==============================
 */
if ($sectionKey !== null) {
    $dup = $db->prepare("
        SELECT id FROM retail_product_sections
        WHERE product_id = :product_id
          AND section_key = :section_key
          AND preview_type = :preview_type
          AND priority = :priority
        LIMIT 1
    ");
    $dup->execute([
        'product_id'   => $productId,
        'section_key'  => $sectionKey,
        'preview_type' => $previewType,
        'priority'     => $priority
    ]);

    if ($dup->fetch()) {
        Response::error('Section already exists for this product');
    }
}

/**
 * ==============================
 * INSERT
 * ==============================
 */
$insert = $db->prepare("
    INSERT INTO retail_product_sections (
        product_id,
        section_title,
        section_key,
        file_type,
        preview_type,
        file_path,
        thumbnail_path,
        alt_text,
        caption,
        priority,
        is_lazy_load,
        status,
        approval_status,
        created_by
    ) VALUES (
        :product_id,
        :section_title,
        :section_key,
        :file_type,
        :preview_type,
        :file_path,
        :thumbnail_path,
        :alt_text,
        :caption,
        :priority,
        :is_lazy_load,
        'Draft',
        'Pending',
        :created_by
    )
");

$insert->execute([
    'product_id'     => $productId,
    'section_title'  => $sectionTitle,
    'section_key'    => $sectionKey,
    'file_type'      => $fileType,
    'preview_type'   => $previewType,
    'file_path'      => $filePath,
    'thumbnail_path' => $thumbnailPath,
    'alt_text'       => $altText,
    'caption'        => $caption,
    'priority'       => $priority,
    'is_lazy_load'   => $isLazyLoad,
    'created_by'     => null // attach admin id later
]);

/**
 * ==============================
 * RESPONSE
 * ==============================
 */
Response::success('Product section created successfully', [
    'section_id' => $db->lastInsertId()
]);
