<?php include 'db.php'; ?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مصمم السراير الاحترافي | تجربة واقعية</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&display=swap" rel="stylesheet">
    <style>
        :root { --soft-blue: #f0f7ff; --deep-blue: #0d6efd; --text-dark: #2c3e50; }
        body { background-color: #f8fafc; font-family: 'Cairo', sans-serif; color: var(--text-dark); }
        .main-card { background: white; border-radius: 30px; overflow: hidden; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.1); border: none; }
        
        /* منطقة المعاينة مع دعم الزوم */
        .preview-area { 
            background: radial-gradient(circle, #ffffff 0%, #e0efff 100%); 
            display: flex; align-items: center; justify-content: center; 
            min-height: 550px; position: relative; padding: 20px; 
            overflow: hidden; cursor: zoom-in;
        }
        #bed-render { 
            max-width: 85%; height: auto; 
            filter: drop-shadow(0 20px 40px rgba(0,0,0,0.15));
            transition: transform 0.1s ease-out, opacity 0.3s ease; 
            transform-origin: center center;
        }

        .options-area { padding: 40px; border-right: 1px solid #f1f5f9; }
        .section-title { font-weight: 700; margin-bottom: 20px; font-size: 1.1rem; display: flex; align-items: center; color: var(--deep-blue); }
        .section-title::before { content: ""; width: 6px; height: 22px; background: var(--deep-blue); margin-left: 12px; border-radius: 10px; }
        
        .fabric-item { cursor: pointer; border: 3px solid transparent; transition: 0.3s; border-radius: 16px; padding: 6px; text-align: center; background: #fff; }
        .fabric-item:hover { transform: translateY(-5px); box-shadow: 0 10px 15px rgba(0,0,0,0.05); }
        .fabric-item.active { border-color: var(--deep-blue); background: #f0f7ff; box-shadow: 0 10px 20px rgba(13, 110, 253, 0.15); }
        .fabric-img { width: 100%; aspect-ratio: 1/1; object-fit: cover; border-radius: 12px; margin-bottom: 8px; }
        
        .loader-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255,255,255,0.6); display: none; align-items: center; justify-content: center; z-index: 20; backdrop-filter: blur(4px); }
        .control-label { font-size: 0.85rem; font-weight: 700; margin-bottom: 12px; display: block; color: #64748b; }
        .form-range::-webkit-slider-thumb { background: var(--deep-blue); }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="row main-card g-0">
        <div class="col-lg-4 options-area">
            <h4 class="fw-bold mb-4">تخصيص السرير</h4>
            
            <div class="section-title">1. الموديل</div>
            <select id="bed-select" class="form-select form-select-lg mb-4 shadow-sm border-0 bg-light">
                <?php
                $beds = $pdo->query("SELECT * FROM beds")->fetchAll();
                foreach ($beds as $bed) {
                    echo "<option value='{$bed['id']}'>{$bed['name']}</option>";
                }
                ?>
            </select>

            <div class="section-title">2. الأقمشة المتوفرة</div>
            <div class="row g-3 mb-5" id="fabric-list">
                <?php
                $fabrics = $pdo->query("SELECT * FROM fabrics")->fetchAll();
                foreach ($fabrics as $index => $fabric) {
                    $active = ($index === 0) ? 'active' : '';
                    echo "
                    <div class='col-4'>
                        <div class='fabric-item $active' data-id='{$fabric['id']}'>
                            <img src='{$fabric['texture_path']}' class='fabric-img'>
                            <span class='small fw-bold d-block text-truncate'>{$fabric['name']}</span>
                        </div>
                    </div>";
                }
                ?>
            </div>

            <div class="section-title">3. إعدادات الرندر</div>
            <div class="mb-4">
                <label class="control-label">قوة الظلال (الواقعية):</label>
                <input type="range" class="form-range" id="opacity-slider" min="0" max="100" value="100">
            </div>
            <div class="mb-4">
                <label class="control-label">سطوع القماش (الإضاءة):</label>
                <input type="range" class="form-range" id="brightness-slider" min="50" max="150" value="100">
            </div>
        </div>

        <div class="col-lg-8 preview-area" id="zoom-container">
            <div class="loader-overlay" id="loader">
                <div class="spinner-border text-primary"></div>
            </div>
            <img id="bed-render" src="" alt="جاري المعالجة...">
            
            <div class="position-absolute bottom-0 start-0 m-4 d-flex gap-2">
                <button class="btn btn-white bg-white shadow-sm rounded-pill px-4" onclick="window.print()">🖨️ طباعة</button>
                <button class="btn btn-primary shadow rounded-pill px-4" id="btn-download">💾 حفظ التصميم</button>
            </div>
        </div>
    </div>
</div>

<script>
    const render = document.getElementById('bed-render');
    const loader = document.getElementById('loader');
    const bedSelect = document.getElementById('bed-select');
    const opacitySlider = document.getElementById('opacity-slider');
    const brightnessSlider = document.getElementById('brightness-slider');
    const fabrics = document.querySelectorAll('.fabric-item');
    const zoomContainer = document.getElementById('zoom-container');

    function updateResult() {
        const bedId = bedSelect.value;
        const activeFabric = document.querySelector('.fabric-item.active');
        const fabricId = activeFabric ? activeFabric.dataset.id : 1;
        
        loader.style.display = 'flex';
        render.style.opacity = '0.6';

        const url = `process.php?bed_id=${bedId}&fabric_id=${fabricId}&opacity=${opacitySlider.value}&brightness=${brightnessSlider.value}&t=${new Date().getTime()}`;
        
        const img = new Image();
        img.src = url;
        img.onload = () => {
            render.src = url;
            render.style.opacity = '1';
            loader.style.display = 'none';
        };
    }

    // الزوم التفاعلي
    zoomContainer.addEventListener('mousemove', (e) => {
        const rect = zoomContainer.getBoundingClientRect();
        const x = ((e.clientX - rect.left) / rect.width) * 100;
        const y = ((e.clientY - rect.top) / rect.height) * 100;
        render.style.transformOrigin = `${x}% ${y}%`;
        render.style.transform = "scale(1.8)";
    });

    zoomContainer.addEventListener('mouseleave', () => {
        render.style.transform = "scale(1)";
    });

    // الأحداث
    bedSelect.onchange = updateResult;
    opacitySlider.oninput = updateResult;
    brightnessSlider.oninput = updateResult;
    fabrics.forEach(f => {
        f.onclick = function() {
            fabrics.forEach(el => el.classList.remove('active'));
            this.classList.add('active');
            updateResult();
        }
    });

    // الحفظ
    document.getElementById('btn-download').onclick = () => {
        const a = document.createElement('a');
        a.href = render.src;
        a.download = 'bed-design.png';
        a.click();
    };

    window.onload = updateResult;
</script>
</body>
</html>