<?php

include "session.php";
require_once 'config.php';

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

$product_id = $_GET['id'];

// جلب بيانات المنتج
$product = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$product->execute([$product_id]);
$product = $product->fetch(PDO::FETCH_ASSOC);

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

// جلب جميع الفئات والخصائص المتاحة
$categories = $pdo->query("SELECT * FROM categories")->fetchAll(PDO::FETCH_ASSOC);
$attributes = $pdo->query("SELECT * FROM attributes")->fetchAll(PDO::FETCH_ASSOC);

// جلب خصائص المنتج الحالية
$product_attrs = $pdo->prepare("
    SELECT attribute_id, value 
    FROM product_attributes 
    WHERE product_id = ?
");
$product_attrs->execute([$product_id]);
$product_attrs = $product_attrs->fetchAll(PDO::FETCH_ASSOC);

// جلب صور المنتج
$product_images = $pdo->prepare("SELECT * FROM product_images WHERE product_id = ?");
$product_images->execute([$product_id]);
$product_images = $product_images->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // تحديث بيانات المنتج الأساسية
    $stmt = $pdo->prepare("UPDATE products SET 
                          category_id = :category_id, 
                          name = :name, 
                          description = :description, 
                          price = :price, 
                          stock_quantity = :stock,
                          is_active = :is_active
                          WHERE id = :id");
    $stmt->execute([
        ':category_id' => $_POST['category_id'],
        ':name' => $_POST['name'],
        ':description' => $_POST['description'],
        ':price' => $_POST['price'],
        ':stock' => $_POST['stock'],
        ':is_active' => isset($_POST['is_active']) ? 1 : 0,
        ':id' => $product_id
    ]);
    
    // معالجة الصور المرفوعة
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            $image_name = uniqid() . '_' . basename($_FILES['images']['name'][$key]);
            $target_path = "uploads/" . $image_name;
            
            if (move_uploaded_file($tmp_name, $target_path)) {
                $is_primary = ($key == 0 && empty($product_images)) ? 1 : 0;
                $pdo->prepare("INSERT INTO product_images (product_id, image_url, is_primary) VALUES (?, ?, ?)")
                   ->execute([$product_id, $target_path, $is_primary]);
            }
        }
    }
    
    // تحديث الصورة الأساسية
    if (!empty($_POST['primary_image'])) {
        $pdo->prepare("UPDATE product_images SET is_primary = 0 WHERE product_id = ?")->execute([$product_id]);
        $pdo->prepare("UPDATE product_images SET is_primary = 1 WHERE id = ?")->execute([$_POST['primary_image']]);
    }
    
    // حذف الصور المحددة
    if (!empty($_POST['delete_images'])) {
        foreach ($_POST['delete_images'] as $image_id) {
            $image = $pdo->prepare("SELECT image_url FROM product_images WHERE id = ?")->fetch([$image_id]);
            if ($image && file_exists($image['image_url'])) {
                unlink($image['image_url']);
            }
            $pdo->prepare("DELETE FROM product_images WHERE id = ?")->execute([$image_id]);
        }
    }
    
    // حذف الخصائص القديمة
    $pdo->prepare("DELETE FROM product_attributes WHERE product_id = ?")->execute([$product_id]);
    
    // إضافة الخصائص الجديدة
    if (!empty($_POST['attributes'])) {
        foreach ($_POST['attributes'] as $attribute_id => $values) {
            foreach ($values as $value) {
                $stmt = $pdo->prepare("INSERT INTO product_attributes (product_id, attribute_id, value) 
                                      VALUES (:product_id, :attribute_id, :value)");
                $stmt->execute([
                    ':product_id' => $product_id,
                    ':attribute_id' => $attribute_id,
                    ':value' => $value
                ]);
            }
        }
    }
    
    $_SESSION['message'] = "تم تحديث المنتج بنجاح";
    header("Location: index.php");
    exit;
}
?>

<!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;
        }
        
        .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);
        }
        
        .card {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            padding: 25px;
            margin-bottom: 30px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(67, 97, 238, 0.25);
            outline: none;
        }
        
        textarea.form-control {
            min-height: 120px;
            resize: vertical;
        }
        
        .form-check {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .form-check-input {
            width: 18px;
            height: 18px;
        }
        
        .image-upload-container {
            margin-top: 20px;
        }
        
        .image-preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 15px;
        }
        
        .image-preview {
            position: relative;
            width: 120px;
            height: 120px;
            border-radius: 8px;
            overflow: hidden;
            border: 1px solid #ddd;
        }
        
        .image-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .image-actions {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            justify-content: center;
            padding: 8px;
            gap: 10px;
        }
        
        .image-actions button {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 14px;
        }
        
        .primary-badge {
            position: absolute;
            top: 5px;
            left: 5px;
            background-color: var(--success);
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
        }
        
        .attributes-container {
            margin-top: 20px;
        }
        
        .attribute-group {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
            align-items: center;
        }
        
        .attribute-select {
            flex: 1;
        }
        
        .attribute-values {
            flex: 2;
        }
        
        .btn-remove-attribute {
            background-color: var(--danger);
            color: white;
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .btn-add-attribute {
            background-color: var(--success);
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 6px;
            cursor: pointer;
            margin-top: 10px;
        }
        
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
            margin-top: 30px;
        }
        
        @media (max-width: 768px) {
            .attribute-group {
                flex-direction: column;
                gap: 10px;
            }
            
            .attribute-select, .attribute-values {
                width: 100%;
            }
            
            .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-edit"></i> تعديل المنتج</h1>
            <a href="index.php" class="btn btn-back">
                <i class="fas fa-arrow-right"></i> رجوع
            </a>
        </div>
        
        <div class="card">
            <form method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="name">اسم المنتج</label>
                    <input type="text" id="name" name="name" class="form-control" value="<?= htmlspecialchars($product['name']) ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="category_id">الفئة</label>
                    <select id="category_id" name="category_id" class="form-control">
                        <option value="">اختر الفئة</option>
                        <?php foreach ($categories as $category): ?>
                            <option value="<?= $category['id'] ?>" <?= $category['id'] == $product['category_id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($category['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="description">وصف المنتج</label>
                    <textarea id="description" name="description" class="form-control"><?= htmlspecialchars($product['description']) ?></textarea>
                </div>
                
                <div class="form-row" style="display: flex; gap: 20px;">
                    <div class="form-group" style="flex: 1;">
                        <label for="price">السعر (دج)</label>
                        <input type="number" id="price" name="price" class="form-control" step="0.01" min="0" value="<?= $product['price'] ?>" required>
                    </div>
                    
                    <div class="form-group" style="flex: 1;">
                        <label for="stock">الكمية المتاحة</label>
                        <input type="number" id="stock" name="stock" class="form-control" min="0" value="<?= $product['stock_quantity'] ?>" required>
                    </div>
                </div>
                
                <div class="form-check">
                    <input type="checkbox" id="is_active" name="is_active" class="form-check-input" <?= $product['is_active'] ? 'checked' : '' ?>>
                    <label for="is_active">المنتج نشط</label>
                </div>
                
                <div class="form-group image-upload-container">
                    <label>صور المنتج</label>
                    <input type="file" name="images[]" multiple accept="image/*" style="margin-bottom: 15px;">
                    
                    <div class="image-preview-container">
                        <?php foreach ($product_images as $image): ?>
                            <div class="image-preview">
                                <img src="<?= $image['image_url'] ?>" alt="صورة المنتج">
                                <?php if ($image['is_primary']): ?>
                                    <span class="primary-badge">أساسي</span>
                                <?php endif; ?>
                                <div class="image-actions">
                                    <button type="button" onclick="setPrimaryImage(<?= $image['id'] ?>)">
                                        <i class="fas fa-star"></i> أساسي
                                    </button>
                                    <button type="button" onclick="deleteImage(<?= $image['id'] ?>)">
                                        <i class="fas fa-trash"></i> حذف
                                    </button>
                                </div>
                                <input type="checkbox" name="delete_images[]" value="<?= $image['id'] ?>" style="display: none;" id="delete_<?= $image['id'] ?>">
                                <input type="radio" name="primary_image" value="<?= $image['id'] ?>" <?= $image['is_primary'] ? 'checked' : '' ?> style="display: none;">
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <div class="attributes-container">
                    <label>خصائص المنتج</label>
                    
                    <div id="attributeGroups">
                        <?php 
                        $grouped_attrs = [];
                        foreach ($product_attrs as $attr) {
                            $grouped_attrs[$attr['attribute_id']][] = $attr['value'];
                        }
                        
                        foreach ($grouped_attrs as $attr_id => $values): 
                            $attribute = null;
                            foreach ($attributes as $attr) {
                                if ($attr['id'] == $attr_id) {
                                    $attribute = $attr;
                                    break;
                                }
                            }
                            if ($attribute):
                        ?>
                            <div class="attribute-group">
                                <div class="attribute-select">
                                    <select name="attributes[<?= $attr_id ?>][]" class="form-control" multiple>
                                        <?php 
                                        $attr_values = explode(',', $attribute['values_list']);
                                        foreach ($attr_values as $val):
                                            $val = trim($val);
                                        ?>
                                            <option value="<?= $val ?>" <?= in_array($val, $values) ? 'selected' : '' ?>><?= $val ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <button type="button" class="btn-remove-attribute" onclick="this.parentNode.remove()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        <?php 
                            endif;
                        endforeach; 
                        ?>
                    </div>
                    
                    <button type="button" class="btn-add-attribute" id="addAttributeBtn">
                        <i class="fas fa-plus"></i> إضافة خاصية
                    </button>
                </div>
                
                <div class="form-actions">
                    <button type="reset" class="btn btn-back">
                        <i class="fas fa-undo"></i> إعادة تعيين
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> حفظ التغييرات
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // إضافة خاصية جديدة
        document.getElementById('addAttributeBtn').addEventListener('click', function() {
            const attributeGroups = document.getElementById('attributeGroups');
            const newGroup = document.createElement('div');
            newGroup.className = 'attribute-group';
            
            const selectHtml = `
                <div class="attribute-select">
                    <select name="attributes[new][]" class="form-control" onchange="updateAttributeValues(this)">
                        <option value="">اختر خاصية</option>
                        <?php foreach ($attributes as $attr): ?>
                            <option value="<?= $attr['id'] ?>"><?= htmlspecialchars($attr['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="attribute-values">
                    <select name="attribute_values[]" class="form-control" multiple disabled>
                        <option value="">اختر خاصية أولاً</option>
                    </select>
                </div>
            `;
            
            newGroup.innerHTML = selectHtml + `
                <button type="button" class="btn-remove-attribute" onclick="this.parentNode.remove()">
                    <i class="fas fa-times"></i>
                </button>
            `;
            
            attributeGroups.appendChild(newGroup);
        });
        
        // تحديث قيم الخاصية عند اختيارها
        function updateAttributeValues(selectElement) {
            const attributeId = selectElement.value;
            const valuesSelect = selectElement.closest('.attribute-group').querySelector('.attribute-values select');
            
            if (!attributeId) {
                valuesSelect.innerHTML = '<option value="">اختر خاصية أولاً</option>';
                valuesSelect.disabled = true;
                valuesSelect.name = 'attribute_values[]';
                return;
            }
            
            // هنا يمكنك جلب القيم من قاعدة البيانات أو من مصدر آخر
            // لأغراض العرض، سنستخدم مثالاً بسيطاً
            const attribute = <?php echo json_encode($attributes); ?>.find(a => a.id == attributeId);
            
            if (attribute) {
                const values = attribute.values_list.split(',').map(v => v.trim());
                let optionsHtml = '';
                
                values.forEach(value => {
                    optionsHtml += `<option value="${value}">${value}</option>`;
                });
                
                valuesSelect.innerHTML = optionsHtml;
                valuesSelect.disabled = false;
                valuesSelect.name = `attributes[${attributeId}][]`;
            }
        }
        
        // تعيين الصورة كأساسية
        function setPrimaryImage(imageId) {
            document.querySelectorAll('input[name="primary_image"]').forEach(radio => {
                radio.checked = (radio.value == imageId);
            });
            
            // تحديث الواجهة
            document.querySelectorAll('.primary-badge').forEach(badge => {
                badge.style.display = 'none';
            });
            
            const badge = document.querySelector(`.image-preview input[value="${imageId}"]`).parentNode.querySelector('.primary-badge');
            if (badge) {
                badge.style.display = 'block';
            }
        }
        
        // حذف الصورة
        function deleteImage(imageId) {
            const checkbox = document.getElementById(`delete_${imageId}`);
            checkbox.checked = !checkbox.checked;
            
            const preview = checkbox.parentNode;
            if (checkbox.checked) {
                preview.style.opacity = '0.5';
                preview.style.border = '2px solid var(--danger)';
            } else {
                preview.style.opacity = '1';
                preview.style.border = '1px solid #ddd';
            }
        }
    </script>
</body>
</html>