<?php include __DIR__ . '/../layout/header.php'; ?>

<div class="admin-card-header" style="padding:0 0 20px;border-bottom:none;">
    <div>
        <h2 style="font-size:18px;font-weight:800;color:var(--text-1);margin:0;">Yeni Ürün Ekle</h2>
        <p style="font-size:12px;color:var(--text-3);margin:4px 0 0;">Tüm alanları doldurarak yeni ürün ekleyin</p>
    </div>
    <a href="<?php echo $baseUrl; ?>/admin/products" class="admin-btn">
        <i class="fa fa-arrow-left"></i> Listeye Dön
    </a>
</div>

<form action="<?php echo $baseUrl; ?>/admin/products/store" method="POST" enctype="multipart/form-data" id="productForm">
    <div class="form-grid">

        <!-- LEFT COLUMN -->
        <div class="form-column">

            <!-- Main Info -->
            <div class="admin-card">
                <div class="section-title"><i class="fa fa-info-circle"></i> Temel Bilgiler</div>

                <div class="admin-form-group">
                    <label for="name">Ürün Adı *</label>
                    <input type="text" id="name" name="name" required class="admin-input" placeholder="Örn: Everest Lazer Yazıcı">
                </div>

                <div class="admin-form-group">
                    <label for="slug">SEO URL (Slug)</label>
                    <input type="text" id="slug" name="slug" class="admin-input" placeholder="oto-oluşturulur">
                    <small class="form-hint">Boş bırakırsanız ürün adından otomatik oluşturulur.</small>
                </div>

                <div class="admin-form-group">
                    <label for="brand_slug">Marka</label>
                    <select id="brand_slug" name="brand_slug" class="admin-select">
                        <option value="">— Marka Seçin —</option>
                        <?php
                        $settings = \App\Models\Settings::all();
                        $brands   = $settings['brands'] ?? [];
                        foreach ($brands as $b):
                        ?>
                        <option value="<?php echo htmlspecialchars($b['slug']); ?>"><?php echo htmlspecialchars($b['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="admin-form-group">
                    <label for="description">Ürün Açıklaması</label>
                    <textarea id="description" name="description" rows="10" class="admin-textarea" placeholder="Ürün özellikleri ve detayları..."></textarea>
                </div>
            </div>

            <!-- Images -->
            <div class="admin-card">
                <div class="section-title"><i class="fa fa-picture-o"></i> Görseller</div>

                <div class="admin-form-group">
                    <label for="images">Bilgisayardan Yükle</label>
                    <div class="upload-area" onclick="document.getElementById('images').click()">
                        <i class="fa fa-cloud-upload"></i>
                        <p>Görselleri buraya sürükleyin veya tıklayın</p>
                        <p style="font-size:11px;margin-top:5px;color:var(--text-3);">JPG, PNG, WEBP — Çoklu seçim yapabilirsiniz</p>
                    </div>
                    <input type="file" id="images" name="images[]" multiple accept="image/*" style="display:none;">
                    <div id="image_preview_container" style="display:flex;gap:10px;flex-wrap:wrap;margin-top:10px;"></div>
                </div>

                <div class="admin-form-group">
                    <label for="image_urls">URL'den Görsel Çek</label>
                    <textarea id="image_urls" name="image_urls" rows="3" class="admin-textarea" placeholder="https://ornek.com/gorsel.jpg&#10;Her satıra bir URL girin"></textarea>
                </div>
            </div>

            <!-- Categories -->
            <div class="admin-card">
                <div class="section-title"><i class="fa fa-tags"></i> Kategoriler</div>
                <div style="max-height:260px;overflow-y:auto;padding-right:8px;">
                    <?php
                    $parents = array_filter($categories, function($c) { return empty($c->parent_slug); });
                    foreach ($parents as $parent):
                        $children = array_filter($categories, function($c) use ($parent) { return $c->parent_slug === $parent->slug; });
                    ?>
                    <div class="toggle-row" style="flex-direction:column;align-items:flex-start;gap:6px;border-bottom:1px solid var(--border);padding:10px 0;">
                        <label style="display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:var(--text-1);cursor:pointer;">
                            <input type="checkbox" name="categories[]"
                                   class="parent-category-cb"
                                   value="<?php echo htmlspecialchars($parent->slug); ?>"
                                   data-slug="<?php echo htmlspecialchars($parent->slug); ?>"
                                   style="accent-color:var(--primary);width:15px;height:15px;">
                            <?php echo htmlspecialchars($parent->name); ?>
                        </label>
                        <?php if (!empty($children)): ?>
                        <div class="subcategories-container" id="subcats-<?php echo htmlspecialchars($parent->slug); ?>"
                             style="display:none;flex-direction:column;gap:6px;margin-left:22px;border-left:2px solid var(--border);padding-left:12px;">
                            <?php foreach ($children as $child): ?>
                            <label style="display:flex;align-items:center;gap:8px;font-size:13px;cursor:pointer;color:var(--text-2);">
                                <input type="checkbox" name="categories[]"
                                       class="child-category-cb"
                                       value="<?php echo htmlspecialchars($child->slug); ?>"
                                       data-parent="<?php echo htmlspecialchars($child->parent_slug); ?>"
                                       style="accent-color:var(--primary);width:14px;height:14px;">
                                <?php echo htmlspecialchars($child->name); ?>
                            </label>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

        </div><!-- /form-column left -->

        <!-- RIGHT COLUMN -->
        <div class="form-column">

            <!-- Pricing & Stock -->
            <div class="admin-card">
                <div class="section-title"><i class="fa fa-tag"></i> Fiyat & Stok</div>

                <div class="admin-form-group">
                    <label for="model">Model / Ürün Kodu</label>
                    <input type="text" id="model" name="model" class="admin-input" placeholder="Örn: EVR-2024">
                </div>

                <div class="admin-form-group">
                    <label for="price">Fiyat *</label>
                    <input type="number" id="price" name="price" step="0.01" required min="0" class="admin-input" placeholder="0.00">
                </div>

                <div class="admin-form-group">
                    <label for="currency">Para Birimi</label>
                    <select id="currency" name="currency" class="admin-select">
                        <option value="TRY">TRY (₺)</option>
                        <option value="USD">USD ($)</option>
                        <option value="EUR">EUR (€)</option>
                    </select>
                </div>

                <div class="admin-form-group">
                    <label for="stock">Stok Adeti *</label>
                    <input type="number" id="stock" name="stock" value="10" required min="0" class="admin-input">
                </div>
            </div>

            <!-- Visibility -->
            <div class="admin-card">
                <div class="section-title"><i class="fa fa-eye"></i> Yayın Durumu</div>

                <div class="toggle-row">
                    <label for="status">
                        <i class="fa fa-toggle-on" style="color:var(--success);"></i>
                        Ürünü Yayına Al
                        <span>Aktif olduğunda müşteriler görebilir</span>
                    </label>
                    <input type="checkbox" id="status" name="status" value="1" checked style="accent-color:var(--primary);width:18px;height:18px;cursor:pointer;">
                </div>

                <div class="toggle-row">
                    <label for="featured">
                        <i class="fa fa-star" style="color:var(--warning);"></i>
                        Öne Çıkar
                        <span>Ana sayfada öne çıkan ürünler arasında göster</span>
                    </label>
                    <input type="checkbox" id="featured" name="featured" value="1" style="accent-color:var(--warning);width:18px;height:18px;cursor:pointer;">
                </div>

                <div style="margin-top:20px;">
                    <button type="submit" class="admin-btn admin-btn-primary admin-btn-block admin-btn-lg" id="saveBtn">
                        <i class="fa fa-save"></i> Ürünü Kaydet
                    </button>
                </div>
            </div>

        </div><!-- /form-column right -->

    </div><!-- /.form-grid -->
</form>

<script>
/* Category expand/collapse */
document.querySelectorAll('.parent-category-cb').forEach(function(cb) {
    cb.addEventListener('change', function() {
        var container = document.getElementById('subcats-' + this.dataset.slug);
        if (container) {
            container.style.display = this.checked ? 'flex' : 'none';
            if (!this.checked) container.querySelectorAll('.child-category-cb').forEach(function(c) { c.checked = false; });
        }
    });
    if (cb.checked) cb.dispatchEvent(new Event('change'));
});

/* Image preview */
document.getElementById('images').addEventListener('change', function() {
    var container = document.getElementById('image_preview_container');
    container.innerHTML = '';
    Array.from(this.files).forEach(function(file, i) {
        if (!file.type.match('image.*')) return;
        var reader = new FileReader();
        reader.onload = function(e) {
            var wrap = document.createElement('div');
            wrap.style.cssText = 'position:relative;width:90px;border:1px solid var(--border);border-radius:var(--r-md);overflow:hidden;background:var(--surface-2);display:flex;flex-direction:column;';
            wrap.innerHTML =
                '<img src="' + e.target.result + '" style="width:90px;height:90px;object-fit:cover;">' +
                '<label style="display:flex;align-items:center;justify-content:center;gap:4px;padding:5px;background:var(--surface-hover);color:var(--primary);cursor:pointer;font-size:10px;font-weight:700;margin:0;border-top:1px solid var(--border);">' +
                '<input type="radio" name="main_image" value="new::' + file.name + '" style="accent-color:var(--primary);"' + (i === 0 ? ' checked' : '') + '> Ana</label>';
            container.appendChild(wrap);
        };
        reader.readAsDataURL(file);
    });
});

/* Submit loading */
document.getElementById('productForm').addEventListener('submit', function() {
    var btn = document.getElementById('saveBtn');
    btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Kaydediliyor...';
    btn.disabled = true;
});
</script>

<!-- TinyMCE -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.3/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
    selector: '#description',
    plugins: 'advlist autolink lists link image charmap preview anchor pagebreak code',
    toolbar_mode: 'floating',
    height: 380,
    menubar: false,
    branding: false,
    promotion: false,
    toolbar: 'undo redo | bold italic underline | alignleft aligncenter alignright | bullist numlist | link | code',
    skin: (localStorage.getItem('admin_theme') === 'light') ? 'oxide' : 'oxide-dark',
    content_css: (localStorage.getItem('admin_theme') === 'light') ? 'default' : 'dark',
    content_style: 'body { font-family: Inter, sans-serif; font-size: 14px; }'
});
</script>

<?php include __DIR__ . '/../layout/footer.php'; ?>
