<?php
/**
 * Página Novo Produto - MontaLoja SaaS
 * Sistema de Variações estilo Shopify
 */
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/check-access.php';
require_once __DIR__ . '/../../includes/product-image-handler.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId && !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

$categoriesStmt = $pdo->prepare("SELECT * FROM categories WHERE store_id = ? AND is_active = 1 ORDER BY name ASC");
$categoriesStmt->execute([$storeId]);
$categories = $categoriesStmt->fetchAll(PDO::FETCH_ASSOC);

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $costPrice = floatval($_POST['cost_price'] ?? 0);
    $stock = intval($_POST['stock'] ?? 0);
    $sku = trim($_POST['sku'] ?? '');
    $categoryId = !empty($_POST['category_id']) ? intval($_POST['category_id']) : null;

    if ($name && $price > 0) {
        // Inserir produto
        $stmt = $pdo->prepare("INSERT INTO products (store_id, category_id, name, description, price, stock_quantity, sku, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, 1, NOW())");
        $stmt->execute([$storeId, $categoryId, $name, $description, $price, $stock, $sku]);
        $productId = $pdo->lastInsertId();

        // Processar imagens
        $imageData = processProductImages($pdo, $storeId, $productId);
        if ($imageData['main'] || count($imageData['all']) > 0) {
            updateProductImages($pdo, $productId, $imageData['main'], $imageData['all']);
        }

        // Processar opções e variantes estilo Shopify
        $options = json_decode($_POST['product_options'] ?? '[]', true);
        $variants = json_decode($_POST['product_variants'] ?? '[]', true);
        
        if (!empty($options)) {
            foreach ($options as $idx => $opt) {
                $optName = trim($opt['name'] ?? '');
                if (!$optName) continue;
                
                $stmt = $pdo->prepare("INSERT INTO product_options (product_id, name, position) VALUES (?, ?, ?)");
                $stmt->execute([$productId, $optName, $idx]);
                $optionId = $pdo->lastInsertId();
                
                $values = $opt['values'] ?? [];
                foreach ($values as $vIdx => $val) {
                    $val = trim($val);
                    if ($val) {
                        $stmt = $pdo->prepare("INSERT INTO product_option_values (option_id, value, position) VALUES (?, ?, ?)");
                        $stmt->execute([$optionId, $val, $vIdx]);
                    }
                }
            }
        }
        
        if (!empty($variants)) {
            foreach ($variants as $variant) {
                $stmt = $pdo->prepare("INSERT INTO product_variants (product_id, option_values, title, price, sku, stock_quantity) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $productId,
                    json_encode($variant['options'] ?? []),
                    $variant['title'] ?? '',
                    floatval($variant['price'] ?? $price),
                    $variant['sku'] ?? '',
                    intval($variant['stock'] ?? 0)
                ]);
            }
        }

        $_SESSION['flash_message'] = 'Produto criado com sucesso!';
        $_SESSION['flash_type'] = 'success';
        header('Location: /pages/produtos/');
        exit;
    } else {
        $message = 'Preencha o nome e o preço do produto.';
        $messageType = 'error';
    }
}

$pageTitle = 'Novo Produto';
include __DIR__ . '/../../includes/dashboard-header.php';
?>

<style>
/* Tabs System */
.product-tabs { margin-bottom: 1.5rem; }

.tabs-header {
    display: flex;
    border-bottom: 2px solid var(--border);
    margin-bottom: 1.5rem;
    overflow-x: auto;
    scrollbar-width: none;
}
.tabs-header::-webkit-scrollbar { display: none; }

.tab-btn {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 1rem 1.25rem;
    background: none;
    border: none;
    color: var(--text-muted);
    font-size: 0.9rem;
    font-weight: 500;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    margin-bottom: -2px;
    transition: all 0.2s;
    white-space: nowrap;
}
.tab-btn:hover { color: var(--primary); background: var(--primary-light); }
.tab-btn.active { color: var(--primary); border-bottom-color: var(--primary); }

.tab-content { display: none; animation: fadeIn 0.3s ease; }
.tab-content.active { display: block; }

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

.tab-title {
    font-size: 1rem;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 1.25rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding-bottom: 0.75rem;
    border-bottom: 1px solid var(--border);
}
.tab-title iconify-icon { color: var(--primary); }

/* Upload de Imagens */
.upload-zone {
    border: 2px dashed var(--border);
    border-radius: var(--radius-lg);
    padding: 2rem 1rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s;
    background: var(--bg-card-hover);
    display: flex;
    flex-direction: column;
    align-items: center;
}
.upload-zone:hover { border-color: var(--primary); background: var(--primary-light); }
.upload-zone iconify-icon { font-size: 2.5rem; color: var(--primary); margin-bottom: 0.5rem; }

.image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
    gap: 0.75rem;
    margin-top: 1rem;
}

.image-item {
    position: relative;
    aspect-ratio: 1;
    border-radius: var(--radius-md);
    overflow: hidden;
    border: 2px solid var(--border);
}
.image-item.main { border-color: var(--primary); }
.image-item img { width: 100%; height: 100%; object-fit: cover; }
.image-item .badge-main {
    position: absolute;
    bottom: 4px;
    left: 4px;
    background: var(--primary);
    color: #000;
    font-size: 0.6rem;
    padding: 2px 6px;
    border-radius: 4px;
    font-weight: 600;
}
.image-item .btn-remove {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 24px;
    height: 24px;
    background: var(--error);
    color: white;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    font-size: 14px;
}

/* ========== VARIANTES ESTILO SHOPIFY ========== */
.variants-section {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    padding: 1.5rem;
    margin-top: 1rem;
}

.option-card {
    background: var(--bg-card-hover);
    border: 1px solid var(--border);
    border-radius: var(--radius-md);
    padding: 1rem;
    margin-bottom: 1rem;
    transition: all 0.2s ease;
}

.option-card.dragging {
    opacity: 0.5;
    border: 2px dashed var(--primary);
}

.option-card.drag-over {
    border-color: var(--primary);
    background: var(--primary-light);
}

.option-card.collapsed .option-values-container,
.option-card.collapsed .option-footer {
    display: none;
}

.option-card.collapsed {
    padding: 0.75rem 1rem;
}

.option-card.collapsed .option-card-header {
    margin-bottom: 0;
}

.option-summary {
    display: none;
    font-size: 0.85rem;
    color: var(--text-muted);
    margin-left: auto;
    padding-right: 0.5rem;
}

.option-card.collapsed .option-summary {
    display: block;
}

.option-expand-btn {
    display: none;
    background: none;
    border: none;
    color: var(--text-muted);
    cursor: pointer;
    padding: 0.5rem;
    font-size: 1.25rem;
}

.option-card.collapsed .option-expand-btn {
    display: flex;
}

.option-card.collapsed .option-delete-btn {
    display: none;
}

.option-card-header {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-bottom: 1rem;
}

.option-drag-handle {
    cursor: grab;
    color: var(--text-muted);
    font-size: 1.25rem;
    padding: 0.25rem;
    transition: color 0.2s;
}

.option-drag-handle:hover {
    color: var(--primary);
}

.option-drag-handle:active {
    cursor: grabbing;
}

.option-name-input { flex: 1; }

.option-delete-btn {
    background: none;
    border: none;
    color: var(--text-muted);
    cursor: pointer;
    padding: 0.5rem;
    border-radius: var(--radius-sm);
    transition: all 0.2s;
}
.option-delete-btn:hover { color: var(--error); background: rgba(239, 68, 68, 0.1); }

.option-values-container { margin-top: 0.75rem; }

.option-values-label {
    font-size: 0.8rem;
    color: var(--text-muted);
    margin-bottom: 0.5rem;
    display: block;
}

.option-values-wrapper {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    align-items: center;
    padding: 0.5rem;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius-md);
    min-height: 44px;
}

.value-tag {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    background: var(--primary);
    color: #000;
    padding: 0.35rem 0.6rem;
    border-radius: 6px;
    font-size: 0.85rem;
    font-weight: 500;
}

.value-tag-remove {
    background: none;
    border: none;
    color: #000;
    cursor: pointer;
    font-size: 1rem;
    line-height: 1;
    padding: 0;
    margin-left: 0.25rem;
    opacity: 0.7;
}
.value-tag-remove:hover { opacity: 1; }

.value-input-wrapper { flex: 1; min-width: 120px; }

.value-input {
    border: none;
    background: transparent;
    outline: none;
    font-size: 0.9rem;
    width: 100%;
    color: var(--text-primary);
}
.value-input::placeholder { color: var(--text-muted); }

.option-footer {
    display: flex;
    justify-content: space-between;
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid var(--border);
}

.btn-text {
    background: none;
    border: none;
    color: var(--error);
    cursor: pointer;
    font-size: 0.85rem;
    padding: 0.5rem;
}
.btn-text:hover { text-decoration: underline; }

.btn-done {
    background: var(--text-primary);
    color: var(--bg-card);
    border: none;
    padding: 0.5rem 1rem;
    border-radius: var(--radius-md);
    font-size: 0.85rem;
    font-weight: 500;
    cursor: pointer;
}

.add-option-btn {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    background: none;
    border: none;
    color: var(--text-secondary);
    cursor: pointer;
    font-size: 0.9rem;
    padding: 0.75rem 0;
}
.add-option-btn:hover { color: var(--primary); }
.add-option-btn iconify-icon { font-size: 1.25rem; }

/* Lista de Variantes */
.variants-list {
    margin-top: 1.5rem;
    border-top: 1px solid var(--border);
    padding-top: 1.5rem;
}

.variants-list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.variants-list-title {
    font-size: 0.9rem;
    color: var(--text-muted);
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.variants-table {
    width: 100%;
    border-collapse: collapse;
}

.variants-table th {
    text-align: left;
    font-size: 0.75rem;
    font-weight: 500;
    color: var(--text-muted);
    text-transform: uppercase;
    padding: 0.75rem 0.5rem;
    border-bottom: 1px solid var(--border);
}

.variants-table td {
    padding: 0.75rem 0.5rem;
    border-bottom: 1px solid var(--border);
    vertical-align: middle;
}

.variant-row:hover { background: var(--bg-card-hover); }

.variant-checkbox {
    width: 18px;
    height: 18px;
    accent-color: var(--primary);
}

.variant-icon {
    width: 32px;
    height: 32px;
    background: var(--bg-card-hover);
    border-radius: var(--radius-sm);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--primary);
}

.variant-info {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.variant-title { font-weight: 500; font-size: 0.9rem; }

.variant-price-input,
.variant-stock-input {
    width: 100px;
    padding: 0.5rem;
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    background: var(--bg-card);
    color: var(--text-primary);
    font-size: 0.85rem;
}

.variants-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 1rem 0.5rem;
    background: var(--bg-card-hover);
    border-radius: 0 0 var(--radius-md) var(--radius-md);
    font-size: 0.85rem;
    color: var(--text-secondary);
}

.tab-nav {
    display: flex;
    gap: 0.75rem;
    justify-content: flex-end;
    margin-top: 1.5rem;
    padding-top: 1rem;
    border-top: 1px solid var(--border);
}

.form-footer {
    display: flex;
    gap: 1rem;
    justify-content: space-between;
    margin-top: 2rem;
    padding-top: 1.5rem;
    border-top: 1px solid var(--border);
}

/* Responsivo */
@media (max-width: 768px) {
    .tab-btn span { display: none; }
    .tab-btn iconify-icon { font-size: 1.25rem; }
    .variants-table { font-size: 0.85rem; }
    .variant-price-input, .variant-stock-input { width: 80px; }
    .form-footer { flex-direction: column-reverse; gap: 0.75rem; }
    .form-footer .btn { width: 100%; justify-content: center; }
}
</style>

<main class="main-content">
    <a href="/pages/produtos/" class="btn btn-secondary btn-sm" style="margin-bottom:1rem;">
        <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
        <span class="hide-mobile">Voltar</span>
    </a>

    <div class="page-header">
        <h1><iconify-icon icon="solar:box-add-bold"></iconify-icon> Novo Produto</h1>
        <p>Cadastre um novo produto na sua loja</p>
    </div>

    <?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>">
        <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:danger-circle-bold'; ?>"></iconify-icon>
        <?php echo $message; ?>
    </div>
    <?php endif; ?>

    <div class="card">
        <form method="POST" enctype="multipart/form-data" id="productForm">
            <input type="hidden" name="product_options" id="productOptionsInput" value="[]">
            <input type="hidden" name="product_variants" id="productVariantsInput" value="[]">
            
            <div class="product-tabs">
                <div class="tabs-header">
                    <button type="button" class="tab-btn active" data-tab="tab-info">
                        <iconify-icon icon="solar:document-text-bold"></iconify-icon>
                        <span>Informações</span>
                    </button>
                    <button type="button" class="tab-btn" data-tab="tab-pricing">
                        <iconify-icon icon="solar:tag-price-bold"></iconify-icon>
                        <span>Preço e Estoque</span>
                    </button>
                    <button type="button" class="tab-btn" data-tab="tab-variants">
                        <iconify-icon icon="solar:layers-bold"></iconify-icon>
                        <span>Variantes</span>
                    </button>
                </div>

                <!-- Tab 1: Informações -->
                <div class="tab-content active" id="tab-info">
                    <h3 class="tab-title">
                        <iconify-icon icon="solar:document-text-bold"></iconify-icon>
                        Informações Básicas
                    </h3>

                    <div class="form-group">
                        <label class="form-label">Nome do Produto *</label>
                        <input type="text" name="name" class="form-input" placeholder="Ex: Camiseta Básica" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Categoria</label>
                        <select name="category_id" class="form-input">
                            <option value="">Selecione uma categoria</option>
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Descrição</label>
                        <textarea name="description" class="form-input form-textarea" rows="4" placeholder="Descreva seu produto..."></textarea>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Fotos do Produto (máx. 5)</label>
                        <input type="hidden" name="main_image_index" id="mainImageIndex" value="0">
                        
                        <div class="upload-zone" id="uploadZone" onclick="document.getElementById('imageInput').click()">
                            <iconify-icon icon="solar:camera-add-bold-duotone"></iconify-icon>
                            <span>Clique para adicionar fotos</span>
                            <small>JPG, PNG ou WebP (máx. 2MB)</small>
                        </div>
                        <input type="file" name="product_images[]" id="imageInput" multiple accept="image/*" style="display:none;" onchange="handleImages(this)">
                        <div class="image-grid" id="imageGrid"></div>
                    </div>

                    <div class="tab-nav">
                        <button type="button" class="btn btn-primary" onclick="goToTab('tab-pricing')">
                            Próximo <iconify-icon icon="solar:arrow-right-bold"></iconify-icon>
                        </button>
                    </div>
                </div>

                <!-- Tab 2: Preço e Estoque -->
                <div class="tab-content" id="tab-pricing">
                    <h3 class="tab-title">
                        <iconify-icon icon="solar:tag-price-bold"></iconify-icon>
                        Preço e Estoque
                    </h3>

                    <div class="form-grid-2">
                        <div class="form-group">
                            <label class="form-label">Preço de Venda *</label>
                            <input type="number" name="price" id="basePrice" class="form-input" step="0.01" min="0.01" placeholder="0,00" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Preço de Custo</label>
                            <input type="number" name="cost_price" class="form-input" step="0.01" min="0" placeholder="0,00">
                        </div>
                    </div>

                    <div class="form-grid-2">
                        <div class="form-group">
                            <label class="form-label">Quantidade em Estoque</label>
                            <input type="number" name="stock" id="baseStock" class="form-input" min="0" value="0">
                        </div>
                        <div class="form-group">
                            <label class="form-label">SKU (Código)</label>
                            <input type="text" name="sku" class="form-input" placeholder="ABC-123">
                        </div>
                    </div>

                    <div class="tab-nav">
                        <button type="button" class="btn btn-secondary" onclick="goToTab('tab-info')">
                            <iconify-icon icon="solar:arrow-left-bold"></iconify-icon> Voltar
                        </button>
                        <button type="button" class="btn btn-primary" onclick="goToTab('tab-variants')">
                            Próximo <iconify-icon icon="solar:arrow-right-bold"></iconify-icon>
                        </button>
                    </div>
                </div>

                <!-- Tab 3: Variantes (Estilo Shopify) -->
                <div class="tab-content" id="tab-variants">
                    <h3 class="tab-title">
                        <iconify-icon icon="solar:layers-bold"></iconify-icon>
                        Variantes do Produto
                    </h3>

                    <p style="color: var(--text-muted); margin-bottom: 1rem; font-size: 0.9rem;">
                        Adicione opções como Tamanho, Cor ou Material. Cada opção pode ter múltiplos valores.
                        As variantes serão geradas automaticamente combinando todas as opções.
                    </p>

                    <div class="variants-section">
                        <div id="optionsContainer"></div>
                        
                        <button type="button" class="add-option-btn" onclick="addOption()" id="addOptionBtn">
                            <iconify-icon icon="solar:add-circle-linear"></iconify-icon>
                            Adicionar opção (ex: Cor, Tamanho)
                        </button>

                        <!-- Lista de variantes geradas -->
                        <div class="variants-list" id="variantsList" style="display: none;">
                            <div class="variants-list-header">
                                <span class="variants-list-title">
                                    <iconify-icon icon="solar:layers-linear"></iconify-icon>
                                    <span id="variantCount">0</span> variantes geradas
                                </span>
                            </div>

                            <table class="variants-table">
                                <thead>
                                    <tr>
                                        <th style="width:40px;"></th>
                                        <th>Variante</th>
                                        <th style="width:130px;">Preço (R$)</th>
                                        <th style="width:100px;">Estoque</th>
                                    </tr>
                                </thead>
                                <tbody id="variantsTableBody"></tbody>
                            </table>

                            <div class="variants-footer">
                                <span id="totalStockDisplay">Estoque total: <strong>0 disponíveis</strong></span>
                            </div>
                        </div>
                    </div>

                    <div class="tab-nav">
                        <button type="button" class="btn btn-secondary" onclick="goToTab('tab-pricing')">
                            <iconify-icon icon="solar:arrow-left-bold"></iconify-icon> Voltar
                        </button>
                    </div>
                </div>
            </div>

            <div class="form-footer">
                <a href="/pages/produtos/" class="btn btn-secondary">Cancelar</a>
                <button type="submit" class="btn btn-primary">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    Salvar Produto
                </button>
            </div>
        </form>
    </div>
</main>

<script>
// ========== TABS ==========
document.querySelectorAll('.tab-btn').forEach(function(btn){
    btn.addEventListener('click', function(){ goToTab(this.dataset.tab); });
});

function goToTab(id){
    document.querySelectorAll('.tab-btn').forEach(function(b){ b.classList.remove('active'); });
    document.querySelectorAll('.tab-content').forEach(function(c){ c.classList.remove('active'); });
    document.querySelector('[data-tab="'+id+'"]').classList.add('active');
    document.getElementById(id).classList.add('active');
}

// ========== IMAGENS ==========
var images = [], mainIdx = 0;

function handleImages(input){
    var files = input.files, max = 5, types = ['image/jpeg','image/png','image/webp'], maxSize = 2*1024*1024;
    for(var i=0; i < files.length && images.length < max; i++){
        var f = files[i];
        if(!types.includes(f.type)){ alert('Tipo não permitido: '+f.name); continue; }
        if(f.size > maxSize){ alert('Arquivo muito grande: '+f.name); continue; }
        images.push({file:f, url:URL.createObjectURL(f)});
    }
    input.value=''; 
    renderImages();
}

function renderImages(){
    var grid = document.getElementById('imageGrid');
    grid.innerHTML = '';
    images.forEach(function(img,i){
        var div = document.createElement('div');
        div.className = 'image-item' + (i===mainIdx?' main':'');
        div.innerHTML = '<img src="'+img.url+'">' +
            (i===mainIdx?'<span class="badge-main">PRINCIPAL</span>':'') +
            '<button type="button" class="btn-remove" onclick="removeImg('+i+'); event.stopPropagation();">&times;</button>';
        div.onclick = function(){ mainIdx=i; renderImages(); };
        grid.appendChild(div);
    });
    document.getElementById('mainImageIndex').value = mainIdx;
    document.getElementById('uploadZone').style.display = images.length >= 5 ? 'none' : 'flex';
}

function removeImg(i){ 
    URL.revokeObjectURL(images[i].url); 
    images.splice(i,1); 
    if(mainIdx >= images.length) mainIdx = Math.max(0, images.length - 1); 
    else if(i < mainIdx) mainIdx--; 
    renderImages(); 
}

// ========== SISTEMA DE VARIANTES ESTILO SHOPIFY ==========
var productOptions = [];
var optionIdCounter = 0;
var generatedVariants = [];

function addOption(data) {
    if (productOptions.length >= 3) {
        alert('Máximo de 3 opções permitido.');
        return;
    }
    
    data = data || { name: '', values: [] };
    var optId = ++optionIdCounter;
    productOptions.push({ id: optId, name: data.name, values: data.values.slice() });
    renderOptions();
    
    // Esconder botão se já tem 3 opções
    if (productOptions.length >= 3) {
        document.getElementById('addOptionBtn').style.display = 'none';
    }
}

function renderOptions() {
    var container = document.getElementById('optionsContainer');
    container.innerHTML = '';
    
    productOptions.forEach(function(opt, idx) {
        var card = document.createElement('div');
        card.className = 'option-card' + (opt.collapsed ? ' collapsed' : '');
        card.id = 'option-' + opt.id;
        card.draggable = true;
        card.dataset.optionId = opt.id;
        
        var valueTags = '';
        opt.values.forEach(function(val, vIdx) {
            valueTags += '<span class="value-tag">' + escapeHtml(val) + 
                '<button type="button" class="value-tag-remove" onclick="removeValue(' + opt.id + ', ' + vIdx + ')">&times;</button></span>';
        });
        
        var valuesPreview = opt.values.length > 0 ? opt.values.join(', ') : 'Sem valores';
        
        card.innerHTML = 
            '<div class="option-card-header">' +
                '<span class="option-drag-handle" title="Arrastar para reordenar"><iconify-icon icon="solar:hamburger-menu-linear"></iconify-icon></span>' +
                '<div class="form-group option-name-input" style="margin:0;">' +
                    '<label class="form-label" style="font-size:0.75rem;">Nome da opção</label>' +
                    '<input type="text" class="form-input" placeholder="Ex: Cor, Tamanho, Material" value="' + escapeHtml(opt.name || '') + '" onchange="updateOptionName(' + opt.id + ', this.value)" onblur="generateVariants()">' +
                '</div>' +
                '<span class="option-summary">' + escapeHtml(valuesPreview) + '</span>' +
                '<button type="button" class="option-expand-btn" onclick="expandOption(' + opt.id + ')" title="Expandir">' +
                    '<iconify-icon icon="solar:alt-arrow-down-linear"></iconify-icon>' +
                '</button>' +
                '<button type="button" class="option-delete-btn" onclick="deleteOption(' + opt.id + ')" title="Remover opção">' +
                    '<iconify-icon icon="solar:trash-bin-trash-linear"></iconify-icon>' +
                '</button>' +
            '</div>' +
            '<div class="option-values-container">' +
                '<label class="option-values-label">Valores da opção (pressione Enter ou vírgula para adicionar)</label>' +
                '<div class="option-values-wrapper" id="values-wrapper-' + opt.id + '">' +
                    valueTags +
                    '<div class="value-input-wrapper">' +
                        '<input type="text" class="value-input" id="value-input-' + opt.id + '" placeholder="Digite e pressione Enter" onkeydown="handleValueKeydown(event, ' + opt.id + ')">' +
                    '</div>' +
                '</div>' +
            '</div>' +
            '<div class="option-footer">' +
                '<button type="button" class="btn-text" onclick="deleteOption(' + opt.id + ')">Excluir opção</button>' +
                '<button type="button" class="btn-done" onclick="collapseOption(' + opt.id + ')">Concluído</button>' +
            '</div>';
        
        // Adicionar eventos de drag and drop
        card.addEventListener('dragstart', handleDragStart);
        card.addEventListener('dragend', handleDragEnd);
        card.addEventListener('dragover', handleDragOver);
        card.addEventListener('dragenter', handleDragEnter);
        card.addEventListener('dragleave', handleDragLeave);
        card.addEventListener('drop', handleDrop);
        
        container.appendChild(card);
    });
}

function escapeHtml(text) {
    var div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function handleValueKeydown(e, optId) {
    if (e.key === 'Enter' || e.key === ',') {
        e.preventDefault();
        var input = document.getElementById('value-input-' + optId);
        var val = input.value.replace(',', '').trim();
        if (val) {
            addValue(optId, val);
            input.value = '';
        }
    }
}

function addValue(optId, val) {
    var opt = productOptions.find(function(o) { return o.id === optId; });
    if (opt && val && !opt.values.includes(val)) {
        opt.values.push(val);
        renderOptions();
        generateVariants();
        setTimeout(function() {
            var input = document.getElementById('value-input-' + optId);
            if (input) input.focus();
        }, 50);
    }
}

function removeValue(optId, vIdx) {
    var opt = productOptions.find(function(o) { return o.id === optId; });
    if (opt) {
        opt.values.splice(vIdx, 1);
        renderOptions();
        generateVariants();
    }
}

function updateOptionName(optId, name) {
    var opt = productOptions.find(function(o) { return o.id === optId; });
    if (opt) {
        opt.name = name;
    }
}

function deleteOption(optId) {
    productOptions = productOptions.filter(function(o) { return o.id !== optId; });
    renderOptions();
    generateVariants();
    
    // Mostrar botão novamente
    if (productOptions.length < 3) {
        document.getElementById('addOptionBtn').style.display = 'flex';
    }
}

function collapseOption(optId) {
    var opt = productOptions.find(function(o) { return o.id === optId; });
    if (opt) {
        // Adicionar valor pendente se houver
        var input = document.getElementById('value-input-' + optId);
        if (input && input.value.trim()) {
            if (!opt.values.includes(input.value.trim())) {
                opt.values.push(input.value.trim());
            }
        }
        opt.collapsed = true;
        renderOptions();
        generateVariants();
    }
}

function expandOption(optId) {
    var opt = productOptions.find(function(o) { return o.id === optId; });
    if (opt) {
        opt.collapsed = false;
        renderOptions();
        // Focar no input de valores
        setTimeout(function() {
            var input = document.getElementById('value-input-' + optId);
            if (input) input.focus();
        }, 50);
    }
}

// ========== DRAG AND DROP ==========
var draggedOption = null;

function handleDragStart(e) {
    draggedOption = this;
    this.classList.add('dragging');
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', this.dataset.optionId);
}

function handleDragEnd(e) {
    this.classList.remove('dragging');
    document.querySelectorAll('.option-card').forEach(function(card) {
        card.classList.remove('drag-over');
    });
    draggedOption = null;
}

function handleDragOver(e) {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
}

function handleDragEnter(e) {
    e.preventDefault();
    if (this !== draggedOption) {
        this.classList.add('drag-over');
    }
}

function handleDragLeave(e) {
    this.classList.remove('drag-over');
}

function handleDrop(e) {
    e.preventDefault();
    e.stopPropagation();
    
    this.classList.remove('drag-over');
    
    if (draggedOption && this !== draggedOption) {
        var draggedId = parseInt(draggedOption.dataset.optionId);
        var targetId = parseInt(this.dataset.optionId);
        
        var draggedIdx = productOptions.findIndex(function(o) { return o.id === draggedId; });
        var targetIdx = productOptions.findIndex(function(o) { return o.id === targetId; });
        
        if (draggedIdx !== -1 && targetIdx !== -1) {
            // Remover o item arrastado
            var draggedItem = productOptions.splice(draggedIdx, 1)[0];
            // Inserir na nova posição
            productOptions.splice(targetIdx, 0, draggedItem);
            
            renderOptions();
            generateVariants();
        }
    }
}

// ========== GERAÇÃO DE VARIANTES ==========
function generateVariants() {
    var validOptions = productOptions.filter(function(o) { 
        return o.name && o.name.trim() && o.values.length > 0; 
    });
    
    if (validOptions.length === 0) {
        generatedVariants = [];
        document.getElementById('variantsList').style.display = 'none';
        updateHiddenInputs();
        return;
    }
    
    // Gerar todas as combinações
    var combinations = cartesian(validOptions.map(function(o) { return o.values; }));
    
    var basePrice = parseFloat(document.getElementById('basePrice').value) || 0;
    
    // Manter preços/estoques existentes
    var oldVariants = {};
    generatedVariants.forEach(function(v) {
        oldVariants[v.title] = { price: v.price, stock: v.stock };
    });
    
    generatedVariants = combinations.map(function(combo, idx) {
        var title = combo.join(' / ');
        var optionsMap = {};
        validOptions.forEach(function(opt, i) {
            optionsMap[opt.name] = combo[i];
        });
        
        var existing = oldVariants[title];
        
        return {
            id: idx,
            title: title,
            options: optionsMap,
            price: existing ? existing.price : basePrice,
            stock: existing ? existing.stock : 0,
            sku: ''
        };
    });
    
    renderVariantsTable();
    document.getElementById('variantsList').style.display = 'block';
    updateHiddenInputs();
}

function cartesian(arrays) {
    if (arrays.length === 0) return [[]];
    return arrays.reduce(function(acc, arr) {
        var result = [];
        acc.forEach(function(a) {
            arr.forEach(function(b) {
                result.push(a.concat([b]));
            });
        });
        return result;
    }, [[]]);
}

function renderVariantsTable() {
    var tbody = document.getElementById('variantsTableBody');
    tbody.innerHTML = '';
    
    var totalStock = 0;
    
    generatedVariants.forEach(function(variant, idx) {
        totalStock += parseInt(variant.stock) || 0;
        
        var tr = document.createElement('tr');
        tr.className = 'variant-row';
        tr.innerHTML = 
            '<td><input type="checkbox" class="variant-checkbox" checked></td>' +
            '<td>' +
                '<div class="variant-info">' +
                    '<div class="variant-icon"><iconify-icon icon="solar:box-linear"></iconify-icon></div>' +
                    '<div class="variant-title">' + escapeHtml(variant.title) + '</div>' +
                '</div>' +
            '</td>' +
            '<td>' +
                '<input type="number" class="variant-price-input" value="' + (variant.price || 0).toFixed(2) + '" step="0.01" min="0" onchange="updateVariantPrice(' + idx + ', this.value)">' +
            '</td>' +
            '<td>' +
                '<input type="number" class="variant-stock-input" value="' + (variant.stock || 0) + '" min="0" onchange="updateVariantStock(' + idx + ', this.value)">' +
            '</td>';
        
        tbody.appendChild(tr);
    });
    
    document.getElementById('variantCount').textContent = generatedVariants.length;
    document.getElementById('totalStockDisplay').innerHTML = 
        'Estoque total: <strong>' + totalStock + ' disponíveis</strong>';
}

function updateVariantPrice(idx, val) {
    generatedVariants[idx].price = parseFloat(val) || 0;
    updateHiddenInputs();
}

function updateVariantStock(idx, val) {
    generatedVariants[idx].stock = parseInt(val) || 0;
    updateHiddenInputs();
    
    var total = generatedVariants.reduce(function(sum, v) { return sum + (parseInt(v.stock) || 0); }, 0);
    document.getElementById('totalStockDisplay').innerHTML = 
        'Estoque total: <strong>' + total + ' disponíveis</strong>';
}

function updateHiddenInputs() {
    document.getElementById('productOptionsInput').value = JSON.stringify(
        productOptions.filter(function(o) { return o.name && o.values.length > 0; })
            .map(function(o) { return { name: o.name, values: o.values }; })
    );
    
    document.getElementById('productVariantsInput').value = JSON.stringify(generatedVariants);
}

// Atualizar preço base em todas as variantes quando mudar
document.getElementById('basePrice').addEventListener('change', function() {
    if (generatedVariants.length > 0 && confirm('Aplicar este preço a todas as variantes?')) {
        var newPrice = parseFloat(this.value) || 0;
        generatedVariants.forEach(function(v) {
            v.price = newPrice;
        });
        renderVariantsTable();
        updateHiddenInputs();
    }
});
</script>

<?php include __DIR__ . '/../../includes/dashboard-footer.php'; ?>
