<?php
declare(strict_types=1);

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';
require_once __DIR__ . '/../../core/Logger.php';

$db = Database::getInstance();
$data = json_decode(file_get_contents('php://input'), true);

Validator::required($data, [
    'product_id',
    'section_key',
    'file_type',
    'file_path'
]);

/**
 * Validate enums
 */
if (!in_array($data['file_type'], ['Image', 'Video'], true)) {
    Response::error('Invalid file type', 422);
}

$previewType = $data['preview_type'] ?? 'Both';
if (!in_array($previewType, ['Desktop','Mobile','Both'], true)) {
    Response::error('Invalid preview type', 422);
}

try {
    $stmt = $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,
            created_at
        ) 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,
            NOW()
        )
    ");

    $stmt->execute([
        'product_id'      => $data['product_id'],
        'section_title'   => $data['section_title'] ?? null,
        'section_key'     => $data['section_key'],
        'file_type'       => $data['file_type'],
        'preview_type'    => $previewType,
        'file_path'       => $data['file_path'],
        'thumbnail_path'  => $data['thumbnail_path'] ?? null,
        'alt_text'        => $data['alt_text'] ?? null,
        'caption'         => $data['caption'] ?? null,
        'priority'        => (int) ($data['priority'] ?? 0),
        'is_lazy_load'    => (int) ($data['is_lazy_load'] ?? 1),
        'created_by'      => $_SESSION['employee_id']
    ]);

    $id = (int) $db->lastInsertId();

} catch (Throwable $e) {
    Logger::error('Section create failed', ['error' => $e->getMessage()]);
    Response::error('Failed to create section', 500);
}

Response::success('Section created successfully', [
    'section_id' => $id
]);
