<?php

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

$product_id = (int)($_GET['product_id'] ?? $_POST['product_id'] ?? 0);

if ($product_id <= 0) {
    header("Location: list.php");
    exit;
}

$stmt_product = $conn->prepare("
    SELECT
        products.id,
        products.name,
        products.sku,
        products.image,
        products.base_price,
        products.stock_qty,
        products.has_variants,
        products.status,
        brands.name AS brand_name,
        categories.name AS category_name
    FROM products
    LEFT JOIN brands ON brands.id = products.brand_id
    LEFT JOIN categories ON categories.id = products.category_id
    WHERE products.id = ?
    LIMIT 1
");
$stmt_product->bind_param("i", $product_id);
$stmt_product->execute();
$product_result = $stmt_product->get_result();
$product = $product_result->fetch_assoc();
$stmt_product->close();

if (!$product) {
    header("Location: list.php");
    exit;
}

$errors = [];

$variant_name  = trim($_POST['variant_name'] ?? '');
$variant_value = trim($_POST['variant_value'] ?? '');
$sku           = trim($_POST['sku'] ?? '');
$price         = $_POST['price'] ?? $product['base_price'];
$stock_qty     = $_POST['stock_qty'] ?? '0';
$status        = (int)($_POST['status'] ?? 1);
$image         = trim($_POST['image'] ?? '');
$sort_order    = $_POST['sort_order'] ?? '0';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_variant'])) {
    if ($variant_name === '') {
        $errors[] = 'اسم المتغير مطلوب. مثال: اللون أو الحجم.';
    }

    if ($variant_value === '') {
        $errors[] = 'قيمة المتغير مطلوبة. مثال: أحمر أو 250 مل.';
    }

    if ($price === '' || !is_numeric($price) || (float)$price < 0) {
        $errors[] = 'السعر غير صحيح.';
    }

    if ($stock_qty === '' || !is_numeric($stock_qty) || (int)$stock_qty < 0) {
        $errors[] = 'المخزون غير صحيح.';
    }

    if ($sort_order === '' || !is_numeric($sort_order) || (int)$sort_order < 0) {
        $errors[] = 'ترتيب العرض غير صحيح.';
    }

    if ($sku !== '') {
        $stmt_check_sku = $conn->prepare("SELECT id FROM product_variants WHERE sku = ? LIMIT 1");
        if ($stmt_check_sku) {
            $stmt_check_sku->bind_param("s", $sku);
            $stmt_check_sku->execute();
            $check_result = $stmt_check_sku->get_result();
            if ($check_result && $check_result->num_rows > 0) {
                $errors[] = 'SKU الخاص بالمتغير مستخدم مسبقاً.';
            }
            $stmt_check_sku->close();
        }
    }

    if (empty($errors)) {
        $stmt_insert = $conn->prepare("
            INSERT INTO product_variants (
                product_id,
                variant_name,
                variant_value,
                sku,
                price,
                stock_qty,
                status,
                image,
                sort_order,
                created_at,
                updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        ");

        if ($stmt_insert) {
            $final_price      = (float)$price;
            $final_stock_qty  = (int)$stock_qty;
            $final_sort_order = (int)$sort_order;

            $stmt_insert->bind_param(
                "isssdiisi",
                $product_id,
                $variant_name,
                $variant_value,
                $sku,
                $final_price,
                $final_stock_qty,
                $status,
                $image,
                $final_sort_order
            );

            if ($stmt_insert->execute()) {
                $stmt_insert->close();

                $stmt_update_product = $conn->prepare("
                    UPDATE products
                    SET has_variants = 1, updated_at = NOW()
                    WHERE id = ?
                    LIMIT 1
                ");
                if ($stmt_update_product) {
                    $stmt_update_product->bind_param("i", $product_id);
                    $stmt_update_product->execute();
                    $stmt_update_product->close();
                }

                header("Location: variants.php?product_id={$product_id}&added=1");
                exit;
            } else {
                $errors[] = 'فشل في إضافة المتغير.';
            }

            $stmt_insert->close();
        } else {
            $errors[] = 'تعذر تجهيز إضافة المتغير. تأكد من جدول product_variants.';
        }
    }
}

if (isset($_GET['delete_variant'])) {
    $delete_variant_id = (int)($_GET['delete_variant']);

    if ($delete_variant_id > 0) {
        $stmt_delete = $conn->prepare("
            DELETE FROM product_variants
            WHERE id = ? AND product_id = ?
            LIMIT 1
        ");
        if ($stmt_delete) {
            $stmt_delete->bind_param("ii", $delete_variant_id, $product_id);
            $stmt_delete->execute();
            $stmt_delete->close();
        }

        $check_variants_stmt = $conn->prepare("SELECT COUNT(*) AS total FROM product_variants WHERE product_id = ?");
        if ($check_variants_stmt) {
            $check_variants_stmt->bind_param("i", $product_id);
            $check_variants_stmt->execute();
            $count_result = $check_variants_stmt->get_result();
            $count_row = $count_result ? $count_result->fetch_assoc() : null;
            $check_variants_stmt->close();

            if ((int)($count_row['total'] ?? 0) === 0) {
                $stmt_update_product = $conn->prepare("
                    UPDATE products
                    SET has_variants = 0, updated_at = NOW()
                    WHERE id = ?
                    LIMIT 1
                ");
                if ($stmt_update_product) {
                    $stmt_update_product->bind_param("i", $product_id);
                    $stmt_update_product->execute();
                    $stmt_update_product->close();
                }
            }
        }

        header("Location: variants.php?product_id={$product_id}&deleted=1");
        exit;
    }
}

$variants = [];
$stmt_variants = $conn->prepare("
    SELECT *
    FROM product_variants
    WHERE product_id = ?
    ORDER BY sort_order ASC, id DESC
");
if ($stmt_variants) {
    $stmt_variants->bind_param("i", $product_id);
    $stmt_variants->execute();
    $variants_result = $stmt_variants->get_result();
    while ($row = $variants_result->fetch_assoc()) {
        $variants[] = $row;
    }
    $stmt_variants->close();
}

$page_title = 'متغيرات المنتج';

require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>

<div class="content-page">
    <div class="container-fluid">

        <div class="page-header-card mb-4">
            <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
                <div>
                    <h1 class="page-title mb-2">متغيرات المنتج</h1>
                    <p class="page-subtitle mb-0">
                        المنتج:
                        <strong><?php echo htmlspecialchars($product['name']); ?></strong>
                        / <?php echo htmlspecialchars($product['brand_name'] ?? '---'); ?>
                    </p>
                </div>

                <div class="d-flex flex-wrap gap-2">
                    <a href="edit.php?id=<?php echo (int)$product_id; ?>" class="btn btn-outline-secondary">
                        <i class="fa-solid fa-arrow-right me-1"></i>
                        رجوع للمنتج
                    </a>
                    <a href="list.php" class="btn btn-outline-primary">
                        <i class="fa-solid fa-list me-1"></i>
                        قائمة المنتجات
                    </a>
                </div>
            </div>
        </div>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <ul class="mb-0 ps-3">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <?php if (isset($_GET['added'])): ?>
            <div class="alert alert-success">تمت إضافة المتغير بنجاح.</div>
        <?php endif; ?>

        <?php if (isset($_GET['deleted'])): ?>
            <div class="alert alert-success">تم حذف المتغير بنجاح.</div>
        <?php endif; ?>

        <div class="row g-4">
            <div class="col-12 col-xl-4">
                <div class="card custom-card">
                    <div class="card-header bg-transparent border-0">
                        <h5 class="mb-0">إضافة متغير جديد</h5>
                    </div>

                    <div class="card-body">
                        <div class="mb-3 p-3 rounded-3" style="background:#f8fafc;border:1px solid #e5e7eb;">
                            <div class="d-flex align-items-center gap-3">
                                <img
                                    src="<?php echo htmlspecialchars(products_image_url($product['image'] ?? '')); ?>"
                                    alt="<?php echo htmlspecialchars($product['name'] ?? ''); ?>"
                                    style="width:58px;height:58px;object-fit:cover;border-radius:14px;border:1px solid #e5e7eb;"
                                >
                                <div>
                                    <div class="fw-bold"><?php echo htmlspecialchars($product['name']); ?></div>
                                    <div class="small text-muted">
                                        السعر الأساسي: <?php echo products_format_price($product['base_price'] ?? 0); ?>
                                    </div>
                                    <div class="small text-muted">
                                        مخزون المنتج: <?php echo number_format((int)($product['stock_qty'] ?? 0)); ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <form method="post">
                            <input type="hidden" name="product_id" value="<?php echo (int)$product_id; ?>">
                            <input type="hidden" name="add_variant" value="1">

                            <div class="row g-3">
                                <div class="col-12 col-md-6">
                                    <label class="form-label">اسم المتغير</label>
                                    <input type="text" name="variant_name" class="form-control" placeholder="مثال: اللون" value="<?php echo htmlspecialchars($variant_name); ?>">
                                </div>

                                <div class="col-12 col-md-6">
                                    <label class="form-label">قيمة المتغير</label>
                                    <input type="text" name="variant_value" class="form-control" placeholder="مثال: أحمر" value="<?php echo htmlspecialchars($variant_value); ?>">
                                </div>

                                <div class="col-12">
                                    <label class="form-label">SKU</label>
                                    <input type="text" name="sku" class="form-control" value="<?php echo htmlspecialchars($sku); ?>">
                                </div>

                                <div class="col-12 col-md-4">
                                    <label class="form-label">السعر</label>
                                    <input type="number" step="0.01" min="0" name="price" class="form-control" value="<?php echo htmlspecialchars((string)$price); ?>">
                                </div>

                                <div class="col-12 col-md-4">
                                    <label class="form-label">المخزون</label>
                                    <input type="number" min="0" name="stock_qty" class="form-control" value="<?php echo htmlspecialchars((string)$stock_qty); ?>">
                                </div>

                                <div class="col-12 col-md-4">
                                    <label class="form-label">الحالة</label>
                                    <select name="status" class="form-select">
                                        <option value="1" <?php echo ($status === 1) ? 'selected' : ''; ?>>نشط</option>
                                        <option value="0" <?php echo ($status === 0) ? 'selected' : ''; ?>>متوقف</option>
                                    </select>
                                </div>

                                <div class="col-12">
                                    <label class="form-label">الصورة</label>
                                    <input type="text" name="image" class="form-control" value="<?php echo htmlspecialchars($image); ?>" placeholder="اسم الملف أو رابط مباشر">
                                </div>

                                <div class="col-12">
                                    <label class="form-label">ترتيب العرض</label>
                                    <input type="number" min="0" name="sort_order" class="form-control" value="<?php echo htmlspecialchars((string)$sort_order); ?>">
                                </div>
                            </div>

                            <div class="mt-4 d-grid">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fa-solid fa-plus me-1"></i>
                                    إضافة المتغير
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-12 col-xl-8">
                <div class="card custom-card">
                    <div class="card-header bg-transparent border-0 d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">المتغيرات الحالية</h5>
                        <span class="badge text-bg-info"><?php echo count($variants); ?> متغير</span>
                    </div>

                    <div class="card-body">
                        <?php if (!empty($variants)): ?>
                            <div class="table-responsive">
                                <table class="table align-middle custom-table">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>الصورة</th>
                                            <th>النوع</th>
                                            <th>القيمة</th>
                                            <th>SKU</th>
                                            <th>السعر</th>
                                            <th>المخزون</th>
                                            <th>الحالة</th>
                                            <th>الترتيب</th>
                                            <th>الإجراء</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($variants as $variant): ?>
                                            <tr>
                                                <td><?php echo (int)$variant['id']; ?></td>
                                                <td>
                                                    <img
                                                        src="<?php echo htmlspecialchars(products_image_url($variant['image'] ?? '')); ?>"
                                                        alt="<?php echo htmlspecialchars($variant['variant_value'] ?? ''); ?>"
                                                        style="width:46px;height:46px;object-fit:cover;border-radius:12px;border:1px solid #e5e7eb;"
                                                    >
                                                </td>
                                                <td><?php echo htmlspecialchars($variant['variant_name']); ?></td>
                                                <td class="fw-bold"><?php echo htmlspecialchars($variant['variant_value']); ?></td>
                                                <td><?php echo htmlspecialchars($variant['sku'] ?: '---'); ?></td>
                                                <td><?php echo products_format_price($variant['price'] ?? 0); ?></td>
                                                <td><?php echo number_format((int)$variant['stock_qty']); ?></td>
                                                <td><?php echo products_status_badge($variant['status'] ?? 0); ?></td>
                                                <td><?php echo (int)$variant['sort_order']; ?></td>
                                                <td>
                                                    <a
                                                        href="variants.php?product_id=<?php echo (int)$product_id; ?>&delete_variant=<?php echo (int)$variant['id']; ?>"
                                                        class="btn btn-sm btn-outline-danger"
                                                        onclick="return confirm('هل تريد حذف هذا المتغير؟');"
                                                    >
                                                        <i class="fa-solid fa-trash"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="empty-state-box text-center py-5">
                                <i class="fa-solid fa-layer-group mb-3" style="font-size:48px;color:#96b8cc;"></i>
                                <h5 class="mb-2">لا توجد متغيرات لهذا المنتج</h5>
                                <p class="text-muted mb-0">أضف أول متغير مثل لون أو حجم أو نوع.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<?php require_once '../includes/footer.php'; ?>