<?php
declare(strict_types=1);

/* ================= AUTH & CORE ================= */
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/Slug.php';

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

/* ================= VALIDATION ================= */
Validator::required($data, ['title']);

$title = trim($data['title']);
$slug  = Slug::make($title);

/* ================= SLUG UNIQUE ================= */
$stmt = $db->prepare("
    SELECT id FROM hospitality_products WHERE slug = :slug
");
$stmt->execute(['slug' => $slug]);

if ($stmt->fetch()) {
    Response::error('Hospitality product already exists', 409);
}

/* ================= TRANSACTION ================= */
$db->beginTransaction();

try {

    /* ================= INSERT PRODUCT ================= */
    $stmt = $db->prepare("
        INSERT INTO hospitality_products (
            title,
            slug,
            short_description,
            description,
            product_type,
            usage_category,
            meta_title,
            meta_description,
            canonical_url,
            schema_json,
            priority,
            status,
            approval_status,
            created_by,
            created_at
        ) VALUES (
            :title,
            :slug,
            :short_description,
            :description,
            :product_type,
            :usage_category,
            :meta_title,
            :meta_description,
            :canonical_url,
            :schema_json,
            :priority,
            'Draft',
            'Pending',
            :created_by,
            NOW()
        )
    ");

    $stmt->execute([
        'title'             => $title,
        'slug'              => $slug,
        'short_description' => $data['short_description'] ?? null,
        'description'       => $data['description'] ?? null,
        'product_type'      => $data['product_type'] ?? 'Hotel',
        'usage_category'    => $data['usage_category'] ?? null,
        'meta_title'        => $data['meta_title'] ?? null,
        'meta_description'  => $data['meta_description'] ?? null,
        'canonical_url'     => $data['canonical_url'] ?? null,
        'schema_json'       => $data['schema_json'] ?? null,
        'priority'          => (int) ($data['priority'] ?? 0),
        'created_by'        => $_SESSION['employee_id']
    ]);

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

    /* ================= INSERT SECTIONS ================= */
    if (!empty($data['sections']) && is_array($data['sections'])) {

        $stmt = $db->prepare("
            INSERT INTO retail_product_sections (
                product_id,
                section_title,
                section_key,
                file_type,
                preview_type,
                file_path,
                thumbnail_path,
                priority,
                status,
                approval_status,
                created_by,
                created_at
            ) VALUES (
                :product_id,
                :section_title,
                :section_key,
                :file_type,
                :preview_type,
                :file_path,
                :thumbnail_path,
                :priority,
                'Draft',
                'Pending',
                :created_by,
                NOW()
            )
        ");

        foreach ($data['sections'] as $section) {

            Validator::required($section, [
                'file_type',
                'preview_type',
                'file_path'
            ]);

            $stmt->execute([
                'product_id'     => $productId,
                'section_title'  => $section['section_title'] ?? null,
                'section_key'    => $section['section_key'] ?? null,
                'file_type'      => $section['file_type'],
                'preview_type'   => $section['preview_type'],
                'file_path'      => $section['file_path'],
                'thumbnail_path' => $section['thumbnail_path'] ?? null,
                'priority'       => (int) ($section['priority'] ?? 0),
                'created_by'     => $_SESSION['employee_id']
            ]);
        }
    }

    $db->commit();

} catch (Throwable $e) {
    $db->rollBack();
    Response::error('Failed to create hospitality product', 500);
}

/* ================= RESPONSE ================= */
Response::success('Hospitality product created successfully', [
    'product_id' => $productId,
    'slug'       => $slug
]);
