<?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/Slug.php';

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

/**
 * ==============================
 * REQUIRED FIELDS
 * ==============================
 */
Validator::required($data, [
    'product_name',
    'category_id',
    'short_description',
    'full_description',
    'brochure_file',
    'variants'
]);

$productName = trim($data['product_name']);
$categoryId  = (int)$data['category_id'];
$shortDesc   = trim($data['short_description']);
$fullDesc    = trim($data['full_description']);
$brochure    = trim($data['brochure_file']);
$variants    = $data['variants'];

/**
 * ==============================
 * OPTIONAL FIELDS
 * ==============================
 */
$primarySleepId   = isset($data['primary_sleep_id']) ? (int)$data['primary_sleep_id'] : null;
$secondarySleepId = isset($data['secondary_sleep_id']) ? (int)$data['secondary_sleep_id'] : null;

$metaTitle       = isset($data['meta_title']) ? trim($data['meta_title']) : null;
$metaDescription = isset($data['meta_description']) ? trim($data['meta_description']) : null;
$metaKeywords    = isset($data['meta_keywords']) ? trim($data['meta_keywords']) : null;
$seoSchema       = isset($data['seo_schema']) ? trim($data['seo_schema']) : null;
$aiSeoContent    = isset($data['ai_seo_content']) ? trim($data['ai_seo_content']) : null;

/**
 * ==============================
 * BASIC VALIDATION
 * ==============================
 */
Validator::minLength($productName, 2, 'product_name');
Validator::minLength($shortDesc, 10, 'short_description');
Validator::minLength($fullDesc, 20, 'full_description');

if (!is_array($variants) || count($variants) < 1) {
    Response::error('At least one variant is required', 422);
}

/**
 * Prevent same sleep ID
 */
if ($primarySleepId && $secondarySleepId && $primarySleepId === $secondarySleepId) {
    Response::error('Primary and Secondary Sleep Type cannot be the same', 422);
}

/**
 * ==============================
 * VALIDATE CATEGORY
 * ==============================
 */
$stmt = $db->prepare("
    SELECT id FROM retail_categories
    WHERE id = :id AND status = 'Active'
");
$stmt->execute(['id' => $categoryId]);

if (!$stmt->fetch()) {
    Response::error('Invalid or inactive retail category', 422);
}

/**
 * ==============================
 * VALIDATE BROCHURE
 * ==============================
 */
if (!preg_match('/\.pdf$/i', $brochure)) {
    Response::error('Brochure must be a PDF file', 422);
}

/**
 * ==============================
 * GENERATE SLUG
 * ==============================
 */
$slug = Slug::unique($productName, 'retail_products');

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

try {

    /**
     * ==============================
     * INSERT PRODUCT
     * ==============================
     */
    $stmt = $db->prepare("
        INSERT INTO retail_products (
            product_name,
            slug,
            category_id,
            primary_sleep_id,
            secondary_sleep_id,
            short_description,
            full_description,
            brochure_file,
            meta_title,
            meta_description,
            meta_keywords,
            seo_schema,
            ai_seo_content,
            status,
            approval_status,
            created_by
        ) VALUES (
            :name,
            :slug,
            :category,
            :primary_sleep_id,
            :secondary_sleep_id,
            :short_desc,
            :full_desc,
            :brochure,
            :meta_title,
            :meta_description,
            :meta_keywords,
            :seo_schema,
            :ai_seo_content,
            'Draft',
            'Pending',
            :created_by
        )
    ");

    $stmt->execute([
        'name'               => $productName,
        'slug'               => $slug,
        'category'           => $categoryId,
        'primary_sleep_id'   => $primarySleepId,
        'secondary_sleep_id' => $secondarySleepId,
        'short_desc'         => $shortDesc,
        'full_desc'          => $fullDesc,
        'brochure'           => $brochure,
        'meta_title'         => $metaTitle,
        'meta_description'   => $metaDescription,
        'meta_keywords'      => $metaKeywords,
        'seo_schema'         => $seoSchema,
        'ai_seo_content'     => $aiSeoContent,
        'created_by'         => $_SESSION['employee_id']
    ]);

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

    /**
     * ==============================
     * INSERT VARIANTS
     * ==============================
     */
    $variantStmt = $db->prepare("
        INSERT INTO retail_product_variants (
            product_id,
            variant_name,
            sku,
            mrp,
            selling_price,
            size,
            firmness,
            thickness,
            specifications,
            status,
            sort_order
        ) VALUES (
            :product_id,
            :variant_name,
            :sku,
            :mrp,
            :selling_price,
            :size,
            :firmness,
            :thickness,
            :specs,
            'Active',
            :sort_order
        )
    ");

    $allowedSize = ['Single','Double','Queen','King','Custom'];
    $allowedFirm = ['Soft','Medium','Firm','Custom'];

    $order = 1;

    foreach ($variants as $variant) {

        Validator::required($variant, [
            'variant_name',
            'size',
            'firmness',
            'thickness',
            'mrp',
            'selling_price'
        ]);

        $variantName = trim($variant['variant_name']);
        $size        = $variant['size'];
        $firmness    = $variant['firmness'];
        $thickness   = trim($variant['thickness']);
        $mrp         = (float)$variant['mrp'];
        $sellPrice   = (float)$variant['selling_price'];

        if (!in_array($size, $allowedSize, true)) {
            Response::error("Invalid size for variant: {$variantName}", 422);
        }

        if (!in_array($firmness, $allowedFirm, true)) {
            Response::error("Invalid firmness for variant: {$variantName}", 422);
        }

        if ($mrp <= 0 || $sellPrice <= 0 || $sellPrice > $mrp) {
            Response::error("Invalid pricing for variant: {$variantName}", 422);
        }

        $variantStmt->execute([
            'product_id'    => $productId,
            'variant_name'  => $variantName,
            'sku'           => $variant['sku'] ?? null,
            'mrp'           => $mrp,
            'selling_price' => $sellPrice,
            'size'          => $size,
            'firmness'      => $firmness,
            'thickness'     => $thickness,
            'specs'         => isset($variant['specifications'])
                                ? json_encode($variant['specifications'], JSON_UNESCAPED_UNICODE)
                                : null,
            'sort_order'    => $order++
        ]);
    }

    $db->commit();

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

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