<?php
include "session.php";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../db.php';


// Handle AJAX delete request
if (isset($_POST['action']) && $_POST['action'] === 'delete_variant' && isset($_POST['variant_id'])) {
    try {
        $pdo->beginTransaction();
        
        // Delete variant attributes first
        $stmt = $pdo->prepare("DELETE FROM variant_attributes WHERE variant_id = ?");
        $stmt->execute([$_POST['variant_id']]);
        
        // Delete the variant
        $stmt = $pdo->prepare("DELETE FROM product_variants WHERE id = ?");
        $stmt->execute([$_POST['variant_id']]);
        
        $pdo->commit();
        echo json_encode(['success' => true]);
        exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

if (!isset($_GET['id'])) {
    header("Location: index.php");
    exit;
}

$product_id = $_GET['id'];

// Fetch product details with base price
$product = $pdo->prepare("SELECT p.*, c.name as category_name FROM products p 
                         LEFT JOIN categories c ON p.category_id = c.id 
                         WHERE p.id = ?");
$product->execute([$product_id]);
$product = $product->fetch(PDO::FETCH_ASSOC);

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

// Fetch all available attributes
$attributes = $pdo->query("SELECT * FROM attributes")->fetchAll(PDO::FETCH_ASSOC);

// Fetch all product variants with their attributes
$variants = $pdo->prepare("
    SELECT pv.*, 
           (SELECT GROUP_CONCAT(CONCAT(a.name, ': ', va.attribute_value) SEPARATOR ' - ') 
            FROM variant_attributes va
            JOIN attributes a ON a.id = va.attribute_id
            WHERE va.variant_id = pv.id) as attributes,
           (SELECT GROUP_CONCAT(CONCAT(va.attribute_id, ':', va.attribute_value) SEPARATOR ',') 
            FROM variant_attributes va
            WHERE va.variant_id = pv.id) as attribute_ids
    FROM product_variants pv
    WHERE pv.product_id = ?
");
$variants->execute([$product_id]);
$variants = $variants->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action'])) {
    try {
        $pdo->beginTransaction();
        
        // Delete old variants
        $pdo->prepare("DELETE FROM variant_attributes WHERE variant_id IN 
                      (SELECT id FROM product_variants WHERE product_id = ?)")->execute([$product_id]);
        $pdo->prepare("DELETE FROM product_variants WHERE product_id = ?")->execute([$product_id]);
        
        // Add new variants
        foreach ($_POST['variants'] as $variant) {
            $sku = !empty($variant['sku']) ? $variant['sku'] : 'SKU-' . $product_id . '-' . substr(uniqid(), -6);
            $price = !empty($variant['price']) ? $variant['price'] : $product['price'];
            
            $stmt = $pdo->prepare("INSERT INTO product_variants (product_id, sku, price, stock) 
                                  VALUES (?, ?, ?, ?)");
            $stmt->execute([
                $product_id,
                $sku,
                $price,
                $variant['stock']
            ]);
            $variant_id = $pdo->lastInsertId();
            
            // Add variant attributes
            if (!empty($variant['attribute_ids'])) {
                $attr_pairs = explode(',', $variant['attribute_ids']);
                foreach ($attr_pairs as $attr_pair) {
                    list($attr_id, $attr_value) = explode(':', $attr_pair);
                    $pdo->prepare("INSERT INTO variant_attributes (variant_id, attribute_id, attribute_value) 
                                  VALUES (?, ?, ?)")->execute([$variant_id, $attr_id, $attr_value]);
                }
            }
        }
        
        $pdo->commit();
        $_SESSION['message'] = "تم تحديث متغيرات المنتج بنجاح";
        header("Location: index.php");
        exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error_message'] = "حدث خطأ أثناء تحديث المتغيرات: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>متغيرات المنتج - لوحة التحكم</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #4361ee;
            --primary-light: #3f37c9;
            --secondary: #3a0ca3;
            --success: #4cc9f0;
            --danger: #f72585;
            --warning: #f8961e;
            --info: #4895ef;
            --dark: #212529;
            --light: #f8f9fa;
            --gray: #6c757d;
            --white: #ffffff;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Tajawal', sans-serif;
        }
        
        body {
            background-color: #f5f7fb;
            color: var(--dark);
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .header h1 {
            color: var(--primary);
            font-size: 28px;
            font-weight: 700;
        }
        
        .product-info {
            display: flex;
            align-items: center;
            gap: 20px;
            margin-bottom: 20px;
            padding: 15px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        
        .product-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }
        
        .product-details h2 {
            margin-bottom: 5px;
            color: var(--primary);
        }
        
        .product-details p {
            color: var(--gray);
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary {
            background-color: var(--primary);
            color: white;
            border: none;
        }
        
        .btn-primary:hover {
            background-color: var(--primary-light);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(67, 97, 238, 0.2);
        }
        
        .btn-back {
            background-color: var(--gray);
            color: white;
            border: none;
        }
        
        .btn-back:hover {
            background-color: #5a6268;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(108, 117, 125, 0.2);
        }
        
        .btn-success {
            background-color: var(--success);
            color: white;
            border: none;
        }
        
        .btn-success:hover {
            background-color: #2fb4d8;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(76, 201, 240, 0.2);
        }
        
        .card {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            padding: 25px;
            margin-bottom: 30px;
        }
        
        .table-responsive {
            overflow-x: auto;
            margin-bottom: 20px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 12px 15px;
            text-align: right;
            border-bottom: 1px solid #e0e0e0;
        }
        
        th {
            background-color: var(--primary);
            color: white;
            font-weight: 500;
        }
        
        tr:hover {
            background-color: #f8f9fa;
        }
        
        .form-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .form-control:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 0.2rem rgba(67, 97, 238, 0.25);
        }
        
        .btn-remove {
            background-color: var(--danger);
            color: white;
            border: none;
            padding: 6px 10px;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .btn-remove:hover {
            background-color: #d31666;
        }
        
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
            margin-top: 20px;
        }
        
        .no-variants {
            text-align: center;
            padding: 20px;
            color: var(--gray);
        }
        
        .attribute-select {
            margin-bottom: 10px;
        }
        
        .base-price-hint {
            font-size: 12px;
            color: var(--gray);
            margin-top: 5px;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            width: 400px;
            max-width: 90%;
        }
        
        .modal-actions {
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        
        @media (max-width: 768px) {
            .product-info {
                flex-direction: column;
                text-align: center;
            }
            
            th, td {
                padding: 8px 10px;
                font-size: 14px;
            }
            
            .form-actions {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <button class="sidebar-toggle" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>
    
    <div class="sidebar-overlay" onclick="toggleSidebar()"></div>
    
    <?php include 'sidebar.php'; ?>

    <div class="container">
        <div class="header">
            <h1><i class="fas fa-list"></i> متغيرات المنتج</h1>
            <a href="index.php" class="btn btn-back">
                <i class="fas fa-arrow-right"></i> رجوع
            </a>
        </div>
        
        <div class="product-info">
            <?php if (!empty($product['image'])): ?>
                <img src="<?= $product['image'] ?>" class="product-image" alt="صورة المنتج">
            <?php else: ?>
                <div style="width:80px;height:80px;background:#eee;border-radius:8px;display:flex;align-items:center;justify-content:center;">
                    <i class="fas fa-image" style="color:#aaa;font-size:24px;"></i>
                </div>
            <?php endif; ?>
            <div class="product-details">
                <h2><?= htmlspecialchars($product['name']) ?></h2>
                <p><?= htmlspecialchars($product['category_name'] ?? 'بدون فئة') ?></p>
                <p>السعر الأساسي: <?= $product['price'] ?> دج</p>
            </div>
        </div>
        
        <div class="card">
            <form method="post" id="variantsForm">
                <div class="table-responsive">
                    <table id="variantsTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>SKU</th>
                                <th>الخصائص</th>
                                <th>السعر</th>
                                <th>الكمية</th>
                                <th>إجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($variants)): ?>
                                <tr>
                                    <td colspan="6" class="no-variants">لا توجد متغيرات لهذا المنتج</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($variants as $index => $variant): ?>
                                    <tr data-variant-id="<?= $variant['id'] ?>">
                                        <td><?= $index + 1 ?></td>
                                        <td>
                                            <input type="hidden" name="variants[<?= $index ?>][id]" value="<?= $variant['id'] ?>">
                                            <input type="text" name="variants[<?= $index ?>][sku]" class="form-control" value="<?= $variant['sku'] ?>" placeholder="سيتم إنشاؤه تلقائياً إذا ترك فارغاً">
                                            <input type="hidden" name="variants[<?= $index ?>][attribute_ids]" value="<?= $variant['attribute_ids'] ?>">
                                        </td>
                                        <td><?= $variant['attributes'] ?: '<button type="button" class="btn btn-success" onclick="selectAttributes(this)" style="padding:5px 10px; font-size:12px;"><i class="fas fa-plus"></i> اختر خصائص</button>' ?></td>
                                        <td>
                                            <input type="number" name="variants[<?= $index ?>][price]" class="form-control" step="0.01" min="0" value="<?= $variant['price'] ?>" placeholder="سعر المنتج الأساسي: <?= $product['price'] ?>">
                                            <div class="base-price-hint">اتركه فارغاً لأخذ سعر المنتج الأساسي</div>
                                        </td>
                                        <td>
                                            <input type="number" name="variants[<?= $index ?>][stock]" class="form-control" min="0" value="<?= $variant['stock'] ?>" required>
                                        </td>
                                        <td>
                                            <button type="button" class="btn-remove" onclick="removeVariant(this)">
                                                <i class="fas fa-trash"></i> حذف
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <div class="form-actions">
                    <button type="button" class="btn btn-success" id="addVariantBtn">
                        <i class="fas fa-plus"></i> إضافة متغير
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> حفظ المتغيرات
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div id="attributeModal" class="modal">
        <div class="modal-content">
            <h3 style="margin-bottom:15px;">اختر خصائص المتغير</h3>
            <div id="modalAttributes">
                <?php foreach ($attributes as $attr): ?>
                    <div class="attribute-select">
                        <label><?= htmlspecialchars($attr['name']) ?></label>
                        <select class="form-control" data-attr-id="<?= $attr['id'] ?>">
                            <option value="">اختر <?= htmlspecialchars($attr['name']) ?></option>
                            <?php 
                            $values = explode(',', $attr['values_list']);
                            foreach ($values as $value): 
                                $value = trim($value);
                                if (!empty($value)): ?>
                                    <option value="<?= htmlspecialchars($value) ?>"><?= htmlspecialchars($value) ?></option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-back" onclick="closeModal()">إلغاء</button>
                <button type="button" class="btn btn-primary" id="confirmAttributes">تأكيد</button>
            </div>
        </div>
    </div>

    <script>
        let currentVariantRow = null;
        
        document.getElementById('addVariantBtn').addEventListener('click', function() {
            const tbody = document.querySelector('#variantsTable tbody');
            const rowCount = tbody.querySelectorAll('tr').length;
            
            if (tbody.querySelector('.no-variants')) {
                tbody.innerHTML = '';
            }
            
            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td>${rowCount + 1}</td>
                <td>
                    <input type="hidden" name="variants[${rowCount}][id]" value="">
                    <input type="text" name="variants[${rowCount}][sku]" class="form-control" placeholder="سيتم إنشاؤه تلقائياً إذا ترك فارغاً">
                    <input type="hidden" name="variants[${rowCount}][attribute_ids]" value="">
                </td>
                <td>
                    <button type="button" class="btn btn-success" onclick="selectAttributes(this)" style="padding:5px 10px; font-size:12px;">
                        <i class="fas fa-plus"></i> اختر خصائص
                    </button>
                </td>
                <td>
                    <input type="number" name="variants[${rowCount}][price]" class="form-control" step="0.01" min="0" placeholder="سعر المنتج الأساسي: <?= $product['price'] ?>">
                    <div class="base-price-hint">اتركه فارغاً لأخذ سعر المنتج الأساسي</div>
                </td>
                <td>
                    <input type="number" name="variants[${rowCount}][stock]" class="form-control" min="0" required>
                </td>
                <td>
                    <button type="button" class="btn-remove" onclick="removeVariant(this)">
                        <i class="fas fa-trash"></i> حذف
                    </button>
                </td>
            `;
            
            tbody.appendChild(newRow);
        });
        
        function selectAttributes(button) {
            currentVariantRow = button.closest('tr');
            document.getElementById('attributeModal').style.display = 'flex';
            
            const selects = document.querySelectorAll('#modalAttributes select');
            selects.forEach(select => {
                select.value = '';
            });
        }
        
        function closeModal() {
            document.getElementById('attributeModal').style.display = 'none';
        }
        
        document.getElementById('confirmAttributes').addEventListener('click', function() {
            const selects = document.querySelectorAll('#modalAttributes select');
            let attributePairs = [];
            let attributeDisplay = [];
            
            selects.forEach(select => {
                const attrId = select.dataset.attrId;
                const attrName = select.previousElementSibling.textContent;
                const attrValue = select.value;
                
                if (attrValue) {
                    attributePairs.push(`${attrId}:${attrValue}`);
                    attributeDisplay.push(`${attrName}: ${attrValue}`);
                }
            });
            
            if (attributePairs.length > 0) {
                const attributeIdsInput = currentVariantRow.querySelector('input[name$="[attribute_ids]"]');
                const attributesCell = currentVariantRow.querySelector('td:nth-child(3)');
                
                attributeIdsInput.value = attributePairs.join(',');
                attributesCell.innerHTML = attributeDisplay.join(' - ');
            }
            
            closeModal();
        });
        
        function removeVariant(button) {
            const row = button.closest('tr');
            const variantId = row.querySelector('input[name$="[id]"]').value;
            
            if (variantId) {
                // Send AJAX request to delete from database
                fetch(window.location.href, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `action=delete_variant&variant_id=${variantId}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        row.remove();
                        updateTableRows();
                    } else {
                        alert('حدث خطأ أثناء الحذف: ' + (data.error || 'غير معروف'));
                    }
                })
                .catch(error => {
                    alert('حدث خطأ أثناء الحذف: ' + error.message);
                });
            } else {
                // For new rows not yet saved in database
                row.remove();
                updateTableRows();
            }
        }
        
        function updateTableRows() {
            const rows = document.querySelectorAll('#variantsTable tbody tr');
            if (rows.length === 0) {
                document.querySelector('#variantsTable tbody').innerHTML = 
                    '<tr><td colspan="6" class="no-variants">لا توجد متغيرات لهذا المنتج</td></tr>';
            } else {
                rows.forEach((tr, index) => {
                    tr.cells[0].textContent = index + 1;
                    // Update input names to maintain correct indexing
                    const inputs = tr.querySelectorAll('input');
                    inputs.forEach(input => {
                        const name = input.name.replace(/variants\[\d+\]/, `variants[${index}]`);
                        input.name = name;
                    });
                });
            }
        }
        
        window.onclick = function(event) {
            if (event.target == document.getElementById('attributeModal')) {
                closeModal();
            }
        }
    </script>
</body>
</html>