<?php
session_start();

require_once '../includes/auth.php';
require_once 'functions.php';

if (!function_exists('redirect_to')) {
    function redirect_to($url) {
        header("Location: " . $url);
        exit;
    }
}

if (!function_exists('slugify_text')) {
    function slugify_text($text) {
        $text = trim((string)$text);
        $text = preg_replace('/\s+/u', '-', $text);
        $text = preg_replace('/[^\p{Arabic}\p{L}\p{N}\-_]+/u', '-', $text);
        $text = preg_replace('/-+/u', '-', $text);
        $text = trim($text, '-');
        return mb_strtolower($text, 'UTF-8');
    }
}

if (!function_exists('clean_text')) {
    function clean_text($value) {
        return trim((string)$value);
    }
}


if (!function_exists('prd_product_image_slugify')) {
    function prd_product_image_slugify($text) {
        $text = trim((string)$text);
        $text = preg_replace('/\s+/u', '-', $text);
        $text = preg_replace('/[^\p{Arabic}\p{L}\p{N}\-_]+/u', '-', $text);
        $text = preg_replace('/-+/u', '-', $text);
        $text = trim($text, '-');
        $text = mb_strtolower($text, 'UTF-8');
        return $text !== '' ? $text : 'general';
    }
}

if (!function_exists('prd_validate_existing_product_image')) {
    function prd_validate_existing_product_image($value) {
        $value = trim((string)$value);
        if ($value === '') return '';
        $value = str_replace('\\', '/', $value);
        $value = ltrim($value, '/');
        if (strpos($value, '..') !== false) return '';
        if (!preg_match('/^[\p{Arabic}\p{L}\p{N}\-_\/\. ]+$/u', $value)) return '';
        $ext = strtolower(pathinfo($value, PATHINFO_EXTENSION));
        if (!in_array($ext, ['jpg','jpeg','png','webp'], true)) return '';
        $base = realpath(dirname(__DIR__) . '/uploads/products');
        if (!$base) return '';
        $full = realpath($base . DIRECTORY_SEPARATOR . $value);
        if (!$full || strpos($full, $base) !== 0 || !is_file($full)) return '';
        return $value;
    }
}

if (!function_exists('upload_product_image')) {
    function upload_product_image($file, $prefix = 'prd_', $brandPart = '') {
        if (
            !isset($file['name'], $file['tmp_name'], $file['error']) ||
            $file['error'] === UPLOAD_ERR_NO_FILE ||
            empty($file['name'])
        ) {
            return null;
        }

        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('صار خطأ أثناء رفع الصورة: ' . $file['name']);
        }

        $allowed = [
            'image/jpeg' => 'jpg',
            'image/png'  => 'png',
            'image/webp' => 'webp',
            'image/jpg'  => 'jpg',
        ];

        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime  = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);

        if (!isset($allowed[$mime])) {
            throw new Exception('نوع الصورة غير مدعوم: ' . $file['name']);
        }

        $ext = $allowed[$mime];

        $brandSlug = prd_product_image_slugify($brandPart);
        $uploadDirFs  = dirname(__DIR__) . '/uploads/products/' . $brandSlug . '/';

        if (!is_dir($uploadDirFs)) {
            if (!mkdir($uploadDirFs, 0775, true) && !is_dir($uploadDirFs)) {
                throw new Exception('تعذر إنشاء مجلد رفع الصور.');
            }
        }

        $newName   = $prefix . uniqid('', true) . '.' . $ext;
        $targetFs  = $uploadDirFs . $newName;

        if (!move_uploaded_file($file['tmp_name'], $targetFs)) {
            throw new Exception('فشل نقل الصورة المرفوعة: ' . $file['name']);
        }

        return $brandSlug . '/' . $newName;
    }
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect_to('create.php');
}

$errors = [];

$categoryId         = (int)($_POST['category_id'] ?? 0);
$brandPart          = clean_text($_POST['brand_part'] ?? '');
$productPart        = clean_text($_POST['product_part'] ?? '');
$name               = clean_text($_POST['name'] ?? '');
$slug               = clean_text($_POST['slug'] ?? '');
$barcode            = clean_text($_POST['barcode'] ?? ($_POST['sku'] ?? ''));
$sku                = $barcode;
$shortDescription   = clean_text($_POST['short_description'] ?? '');
$hasVariants        = isset($_POST['has_variants']) ? 1 : 0;
$variantsSamePrice  = isset($_POST['variants_same_price']) ? 1 : 0;
$status             = isset($_POST['status']) ? (int)$_POST['status'] : 1;
$sortOrder          = (int)($_POST['sort_order'] ?? 0);

$price              = (float)($_POST['price'] ?? 0);
$stockQty           = (int)($_POST['stock_qty'] ?? 0);
$lowStockAlert      = (int)($_POST['low_stock_alert'] ?? 0);
$allowPreorder     = isset($_POST['allow_preorder']) ? 1 : 0;
$accessMode         = prd_normalize_access_mode((string)($_POST['access_mode'] ?? 'all'));
$accessScope        = prd_normalize_access_scope((string)($_POST['access_scope'] ?? 'always'));
$accessMinSubtotal  = max(0.0, (float)($_POST['access_min_subtotal'] ?? 0));
$lowStockGateEnabled = ((int)($_POST['low_stock_gate_enabled'] ?? 0) === 1) ? 1 : 0;
$lowStockGateQty    = max(0, (int)($_POST['low_stock_gate_qty'] ?? 0));
$accessTierIds      = array_values(array_unique(array_filter(array_map('intval', (array)($_POST['access_tier_ids'] ?? [])))));

$sharedVariantPrice = (float)($_POST['price_variants_shared'] ?? 0);

$productTypeIds     = $_POST['product_type_ids'] ?? [];
$variantsInput      = $_POST['variants'] ?? [];

if ($categoryId <= 0) {
    $errors[] = 'يرجى اختيار التصنيف.';
}

if ($brandPart === '') {
    $errors[] = 'يرجى اختيار البراند.';
}

if ($productPart === '') {
    $errors[] = 'يرجى إدخال اسم المنتج.';
}

if ($name === '') {
    $name = trim($brandPart . ' - ' . $productPart, ' -');
}

if ($slug === '') {
    $slug = slugify_text($name);
}

if ($barcode === '') {
    $barcode = slugify_text($name);
}
if ($sku === '') {
    $sku = $barcode;
}

if ($name === '') {
    $errors[] = 'اسم المنتج النهائي فارغ.';
}

if ($slug === '') {
    $errors[] = 'تعذر توليد الـ slug.';
}

if ($sku === '') {
    $errors[] = 'تعذر توليد الباركود.';
}

if (!$hasVariants) {
    $variantsSamePrice = 1;

    if ($price < 0) {
        $errors[] = 'سعر المنتج لا يمكن أن يكون أقل من صفر.';
    }

    if ($stockQty < 0) {
        $errors[] = 'كمية المنتج لا يمكن أن تكون أقل من صفر.';
    }

    if ($lowStockAlert < 0) {
        $errors[] = 'تنبيه انخفاض المخزون لا يمكن أن يكون أقل من صفر.';
    }
} else {
    if (!is_array($variantsInput) || count($variantsInput) === 0) {
        $errors[] = 'أضف Variant واحد على الأقل.';
    }
}

$normalizedProductTypeIds = [];
if (is_array($productTypeIds)) {
    foreach ($productTypeIds as $typeId) {
        $typeId = (int)$typeId;
        if ($typeId > 0) {
            $normalizedProductTypeIds[] = $typeId;
        }
    }
    $normalizedProductTypeIds = array_values(array_unique($normalizedProductTypeIds));
}

$preparedVariants = [];

if ($hasVariants && is_array($variantsInput)) {
    foreach ($variantsInput as $index => $variant) {
        $variantName      = clean_text($variant['variant_name'] ?? '');
        $variantBarcode   = clean_text($variant['barcode'] ?? ($variant['sku'] ?? ''));
        $variantSku       = $variantBarcode;
        $variantPrice     = $variantsSamePrice ? $sharedVariantPrice : (float)($variant['price'] ?? 0);
        $variantStockQty  = (int)($variant['stock_qty'] ?? 0);
        $variantLowAlert  = (int)($variant['low_stock_alert'] ?? 0);
        $variantStatus    = isset($variant['status']) ? (int)$variant['status'] : 1;
        $variantSortOrder = (int)($variant['sort_order'] ?? 0);

        if ($variantName === '') {
            $errors[] = 'يوجد Variant بدون اسم.';
            continue;
        }

        if ($variantBarcode === '') {
            $variantBarcode = slugify_text($name . ' ' . $variantName);
        }
        if ($variantSku === '') {
            $variantSku = $variantBarcode;
        }

        if ($variantSku === '') {
            $errors[] = 'تعذر توليد SKU لأحد الـ Variants.';
        }

        if ($variantPrice < 0) {
            $errors[] = 'سعر أحد الـ Variants لا يمكن أن يكون أقل من صفر.';
        }

        if ($variantStockQty < 0) {
            $errors[] = 'كمية أحد الـ Variants لا يمكن أن تكون أقل من صفر.';
        }

        if ($variantLowAlert < 0) {
            $errors[] = 'تنبيه انخفاض المخزون لأحد الـ Variants لا يمكن أن يكون أقل من صفر.';
        }

        $fileKey = 'variant_images_' . $index;

        $preparedVariants[] = [
            'index'            => $index,
            'variant_name'     => $variantName,
            'sku'              => $variantSku,
            'barcode'          => $variantBarcode,
            'price'            => $variantPrice,
            'stock_qty'        => $variantStockQty,
            'low_stock_alert'  => $variantLowAlert,
            'status'           => $variantStatus ? 1 : 0,
            'sort_order'       => $variantSortOrder,
            'file_key'         => $fileKey,
        ];
    }

    if (count($preparedVariants) === 0) {
        $errors[] = 'لا يوجد Variants صالحة للحفظ.';
    }

    $variantSkuMap = [];
    foreach ($preparedVariants as $v) {
        if (isset($variantSkuMap[$v['sku']])) {
            $errors[] = 'يوجد SKU مكرر بين الـ Variants: ' . $v['sku'];
        }
        $variantSkuMap[$v['sku']] = true;
    }

    if ($variantsSamePrice && $sharedVariantPrice < 0) {
        $errors[] = 'السعر الموحد للـ Variants لا يمكن أن يكون أقل من صفر.';
    }

    $price         = $variantsSamePrice ? $sharedVariantPrice : 0;
    $stockQty      = 0;
    $lowStockAlert = 0;
}

$_SESSION['product_form_old'] = [
    'category_id'          => $categoryId,
    'brand_part'           => $brandPart,
    'product_part'         => $productPart,
    'name'                 => $name,
    'slug'                 => $slug,
    'sku'                  => $sku,
    'barcode'              => $barcode,
    'short_description'    => $shortDescription,
    'price'                => $price,
    'stock_qty'            => $stockQty,
    'low_stock_alert'      => $lowStockAlert,
    'allow_preorder'       => $allowPreorder,
    'access_mode'          => $accessMode,
    'access_scope'         => $accessScope,
    'access_min_subtotal'  => $accessMinSubtotal,
    'low_stock_gate_enabled' => $lowStockGateEnabled,
    'low_stock_gate_qty'   => $lowStockGateQty,
    'access_tier_ids'      => $accessTierIds,
    'has_variants'         => $hasVariants,
    'variants_same_price'  => $variantsSamePrice,
    'price_variants_shared'=> $sharedVariantPrice,
    'status'               => $status,
    'sort_order'           => $sortOrder,
    'product_type_ids'     => $normalizedProductTypeIds,
    'variants'             => $variantsInput,
];

if (!empty($errors)) {
    $_SESSION['product_form_errors'] = $errors;
    redirect_to('create.php');
}

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    prd_ensure_access_schema($conn);
    $conn->begin_transaction();

    $checkStmt = $conn->prepare("SELECT id FROM products WHERE slug = ? OR sku = ? OR barcode = ? LIMIT 1");
    $checkStmt->bind_param("sss", $slug, $sku, $barcode);
    $checkStmt->execute();
    $checkRes = $checkStmt->get_result();
    if ($checkRes && $checkRes->num_rows > 0) {
        throw new Exception('يوجد منتج سابق بنفس الـ slug أو الباركود.');
    }
    $checkStmt->close();

    foreach ($preparedVariants as $v) {
        $variantCheckStmt = $conn->prepare("SELECT id FROM product_variants WHERE sku = ? OR barcode = ? LIMIT 1");
        $variantCheckStmt->bind_param("ss", $v['sku'], $v['barcode']);
        $variantCheckStmt->execute();
        $variantCheckRes = $variantCheckStmt->get_result();
        if ($variantCheckRes && $variantCheckRes->num_rows > 0) {
            throw new Exception('يوجد Variant سابق بنفس الـ SKU: ' . $v['sku']);
        }
        $variantCheckStmt->close();
    }

    $selectedMainImage  = prd_validate_existing_product_image($_POST['existing_main_image'] ?? '');
    $selectedExtraImage = prd_validate_existing_product_image($_POST['existing_extra_image'] ?? '');

    $mainImageName  = upload_product_image($_FILES['main_image'] ?? null, 'prd_', $brandPart) ?: $selectedMainImage;
    $extraImageName = upload_product_image($_FILES['extra_image'] ?? null, 'prd_', $brandPart) ?: $selectedExtraImage;

    $insertProduct = $conn->prepare("
        INSERT INTO products (
            category_id,
            brand_part,
            product_part,
            name,
            slug,
            sku,
            barcode,
            short_description,
            main_image,
            extra_image,
            price,
            has_variants,
            variants_same_price,
            stock_qty,
            low_stock_alert,
            allow_preorder,
            access_mode,
            access_scope,
            access_min_subtotal,
            low_stock_gate_enabled,
            low_stock_gate_qty,
            status,
            sort_order
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $insertProduct->bind_param(
        "isssssssssdiiiiissdiiii",
        $categoryId,
        $brandPart,
        $productPart,
        $name,
        $slug,
        $sku,
        $barcode,
        $shortDescription,
        $mainImageName,
        $extraImageName,
        $price,
        $hasVariants,
        $variantsSamePrice,
        $stockQty,
        $lowStockAlert,
        $allowPreorder,
        $accessMode,
        $accessScope,
        $accessMinSubtotal,
        $lowStockGateEnabled,
        $lowStockGateQty,
        $status,
        $sortOrder
    );

    $insertProduct->execute();
    $productId = (int)$conn->insert_id;
    $insertProduct->close();

    prd_save_product_access_tiers($conn, $productId, $accessTierIds);

    if (!empty($normalizedProductTypeIds)) {
        $insertTypeLink = $conn->prepare("
            INSERT INTO product_type_links (product_id, product_type_id)
            VALUES (?, ?)
        ");

        foreach ($normalizedProductTypeIds as $typeId) {
            $typeId = (int)$typeId;
            $insertTypeLink->bind_param("ii", $productId, $typeId);
            $insertTypeLink->execute();
        }

        $insertTypeLink->close();
    }

    if ($hasVariants && !empty($preparedVariants)) {
        $insertVariant = $conn->prepare("
            INSERT INTO product_variants (
                product_id,
                variant_name,
                sku,
                barcode,
                price,
                stock_qty,
                low_stock_alert,
                variant_image,
                status,
                sort_order
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        foreach ($preparedVariants as $variantRow) {
            $variantImageName = upload_product_image($_FILES[$variantRow['file_key']] ?? null, 'vrn_', $brandPart);

            $variantName     = $variantRow['variant_name'];
            $variantSku      = $variantRow['sku'];
            $variantBarcode  = $variantRow['barcode'];
            $variantPrice    = $variantRow['price'];
            $variantStockQty = $variantRow['stock_qty'];
            $variantLowAlert = $variantRow['low_stock_alert'];
            $variantStatus   = $variantRow['status'];
            $variantSort     = $variantRow['sort_order'];

            $insertVariant->bind_param(
                "isssdiisii",
                $productId,
                $variantName,
                $variantSku,
                $variantBarcode,
                $variantPrice,
                $variantStockQty,
                $variantLowAlert,
                $variantImageName,
                $variantStatus,
                $variantSort
            );

            $insertVariant->execute();
        }

        $insertVariant->close();
    }

    $conn->commit();

    unset($_SESSION['product_form_old'], $_SESSION['product_form_errors']);
    $_SESSION['success_message'] = 'تمت إضافة المنتج بنجاح.';
    redirect_to('index.php');

} catch (Throwable $e) {
    $conn->rollback();

    $_SESSION['product_form_errors'] = ['خطأ أثناء الحفظ: ' . $e->getMessage()];
    redirect_to('create.php');
}