<?php
/**
 * Página de Produtos - MontaLoja SaaS
 * Versão Responsiva
 */
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/plan-limits.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;
}

$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Buscar categorias
$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);

// Processar ações
$message = '';
$messageType = '';
// Função para processar variações do produto
function processProductVariations($pdo, $productId, $variations) {
    if (!$productId) return;
    $existingIds = [];
    $stmt = $pdo->prepare("SELECT id FROM product_variations WHERE product_id = ?");
    $stmt->execute([$productId]);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $existingIds[] = $row['id'];
    }
    $newIds = [];
    if (!empty($variations) && is_array($variations)) {
        foreach ($variations as $v) {
            $vId = !empty($v['id']) ? intval($v['id']) : null;
            $vName = trim($v['name'] ?? '');
            $vValue = trim($v['value'] ?? '');
            $vPriceAdj = floatval($v['price_adjustment'] ?? 0);
            $vStock = intval($v['stock_quantity'] ?? 0);
            if ($vName && $vValue) {
                if ($vId && in_array($vId, $existingIds)) {
                    $stmt = $pdo->prepare("UPDATE product_variations SET name = ?, value = ?, price_adjustment = ?, stock_quantity = ? WHERE id = ? AND product_id = ?");
                    $stmt->execute([$vName, $vValue, $vPriceAdj, $vStock, $vId, $productId]);
                    $newIds[] = $vId;
                } else {
                    $stmt = $pdo->prepare("INSERT INTO product_variations (product_id, name, value, price_adjustment, stock_quantity) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([$productId, $vName, $vValue, $vPriceAdj, $vStock]);
                    $newIds[] = $pdo->lastInsertId();
                }
            }
        }
    }
    $toDelete = array_diff($existingIds, $newIds);
    if (!empty($toDelete)) {
        $placeholders = implode(',', array_fill(0, count($toDelete), '?'));
        $stmt = $pdo->prepare("DELETE FROM product_variations WHERE id IN ($placeholders)");
        $stmt->execute(array_values($toDelete));
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $price = floatval($_POST['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) {
            // Verificar limite de produtos do plano
            $productLimit = canAddProduct($pdo, $storeId);
            if (!$productLimit['allowed']) {
                $_SESSION['flash_message'] = $productLimit['message'];
                $_SESSION['flash_type'] = 'error';
                header('Location: /pages/produtos/');
                exit;
            }
            $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
            error_log("Editing product - existing_images: " . ($_POST["existing_images"] ?? "none"));
            $imageData = processProductImages($pdo, $storeId, $productId);
            if ($imageData['main'] || count($imageData['all']) > 0) {
                updateProductImages($pdo, $productId, $imageData['main'], $imageData['all']);
            }
            // Processar variações
            processProductVariations($pdo, $productId, $_POST['variations'] ?? []);

            $_SESSION['flash_message'] = 'Produto adicionado com sucesso!';
            $_SESSION['flash_type'] = 'success';
        } else {
            $_SESSION['flash_message'] = 'Preencha nome e preço do produto.';
            $_SESSION['flash_type'] = 'error';
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    } elseif ($action === 'edit') {
        $id = intval($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $price = floatval($_POST['price'] ?? 0);
        $stock = intval($_POST['stock'] ?? 0);
        $sku = trim($_POST['sku'] ?? '');
        $categoryId = !empty($_POST['category_id']) ? intval($_POST['category_id']) : null;

        if ($id && $name && $price > 0) {
            $stmt = $pdo->prepare("UPDATE products SET category_id = ?, name = ?, description = ?, price = ?, stock_quantity = ?, sku = ? WHERE id = ? AND store_id = ?");
            $stmt->execute([$categoryId, $name, $description, $price, $stock, $sku, $id, $storeId]);
            $_SESSION['flash_message'] = 'Produto atualizado com sucesso!';
            $_SESSION['flash_type'] = 'success';
            // Processar imagens
            error_log("Editing product - existing_images: " . ($_POST["existing_images"] ?? "none"));
            $imageData = processProductImages($pdo, $storeId, $id);
            if ($imageData['main'] || count($imageData['all']) > 0) {
                updateProductImages($pdo, $id, $imageData['main'], $imageData['all']);
            }
            // Processar variações
            processProductVariations($pdo, $id, $_POST['variations'] ?? []);

        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    } elseif ($action === 'toggle' && isset($_POST['id'])) {
        $stmt = $pdo->prepare("UPDATE products SET is_active = NOT is_active WHERE id = ? AND store_id = ?");
        $stmt->execute([$_POST['id'], $storeId]);
        $_SESSION['flash_message'] = 'Status alterado com sucesso!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    } elseif ($action === 'delete' && isset($_POST['id'])) {
        $stmt = $pdo->prepare("DELETE FROM products WHERE id = ? AND store_id = ?");
        $stmt->execute([$_POST['id'], $storeId]);
        $_SESSION['flash_message'] = 'Produto removido com sucesso!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    } elseif ($action === 'update_stock' && isset($_POST['id'])) {
        $newStock = intval($_POST['stock'] ?? 0);
        $stmt = $pdo->prepare("UPDATE products SET stock_quantity = ? WHERE id = ? AND store_id = ?");
        $stmt->execute([$newStock, $_POST['id'], $storeId]);
        $_SESSION['flash_message'] = 'Estoque atualizado!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
}

// Verificar mensagens flash
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_type'] ?? 'success';
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
}

// Filtro por categoria
$filterCategory = $_GET['category'] ?? '';

// Buscar produtos
$sql = "SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
        FROM products p
        LEFT JOIN categories c ON p.category_id = c.id
        WHERE p.store_id = ?";
$params = [$storeId];

if ($filterCategory) {
    $sql .= " AND p.category_id = ?";
    $params[] = $filterCategory;
}

$sql .= " ORDER BY p.name ASC";
$productsStmt = $pdo->prepare($sql);
$productsStmt->execute($params);
$products = $productsStmt->fetchAll(PDO::FETCH_ASSOC);


// Carregar variações para cada produto
foreach ($products as &$product) {
    $varStmt = $pdo->prepare("SELECT id, name, value, price_adjustment, stock_quantity FROM product_variations WHERE product_id = ?");
    $varStmt->execute([$product['id']]);
    $product['variations'] = $varStmt->fetchAll(PDO::FETCH_ASSOC);
}
unset($product);

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

<style>
/* ========================================
   ESTILOS RESPONSIVOS PARA PRODUTOS
   ======================================== */

/* Header da Página */
.page-header-flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}

/* Stats Grid Responsivo */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1rem;
    margin-bottom: 1.5rem;
}

@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 480px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .stat-card {
        padding: 1rem;
    }
    
    .stat-value {
        font-size: 1.5rem !important;
    }
}

/* Filtro Responsivo */
.filter-form {
    display: flex;
    align-items: center;
    gap: 1rem;
    flex-wrap: wrap;
}

@media (max-width: 600px) {
    .filter-form {
        flex-direction: column;
        align-items: stretch;
    }
    
    .filter-form select {
        width: 100% !important;
        min-width: unset !important;
    }
    
    .filter-form label {
        margin-bottom: 0.5rem;
    }
}

/* Cards de Produtos para Mobile */
.products-grid {
    display: none;
}

.products-table {
    display: block;
}

@media (max-width: 900px) {
    .products-table {
        display: none;
    }
    
    .products-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 1rem;
    }
}

@media (max-width: 400px) {
    .products-grid {
        grid-template-columns: 1fr;
    }
}

/* Card de Produto Individual */
.product-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 1.25rem;
    transition: all 0.2s ease;
}

.product-card:hover {
    border-color: var(--primary);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.product-card-image {
    width: 100%;
    height: 150px;
    margin-bottom: 0.75rem;
    border-radius: 8px;
    overflow: hidden;
    background: var(--bg-secondary);
}

.product-card-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 1rem;
}

.product-card-title {
    font-weight: 600;
    font-size: 1rem;
    color: var(--text-primary);
    margin-bottom: 0.25rem;
}

.product-card-desc {
    font-size: 0.85rem;
    color: var(--text-muted);
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.product-card-category {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    padding: 0.25rem 0.6rem;
    border-radius: 6px;
    font-size: 0.75rem;
    white-space: nowrap;
}

.product-card-info {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 0.75rem;
    margin: 1rem 0;
    padding: 1rem 0;
    border-top: 1px solid var(--border-color);
    border-bottom: 1px solid var(--border-color);
}

.product-info-item {
    text-align: center;
}

.product-info-label {
    font-size: 0.7rem;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 0.25rem;
}

.product-info-value {
    font-weight: 600;
    font-size: 0.95rem;
}

.product-info-value.price {
    color: var(--primary);
}

.product-info-value.stock-low {
    color: var(--error);
}

.product-info-value.stock-warning {
    color: var(--warning);
}

.product-card-actions {
    display: flex;
    gap: 0.5rem;
    justify-content: flex-end;
}

.product-card-actions .btn {
    flex: 1;
    justify-content: center;
}

/* Tabela Responsiva */
.table-container {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.data-table th,
.data-table td {
    white-space: nowrap;
}

@media (max-width: 1100px) {
    .data-table th:nth-child(3),
    .data-table td:nth-child(3) {
        display: none; /* Esconde SKU */
    }
}

@media (max-width: 950px) {
    .data-table th:nth-child(2),
    .data-table td:nth-child(2) {
        display: none; /* Esconde Categoria */
    }
}

/* Modal Responsivo */
.modal-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.7);
    z-index: 1000;
    align-items: center;
    justify-content: center;
    padding: 1rem;
    overflow-y: auto;
}

.modal-content {
    width: 100%;
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;
    background: var(--bg-card);
    border-radius: 16px;
    padding: 1.5rem;
}

@media (max-width: 600px) {
    .modal-content {
        padding: 1.25rem;
        border-radius: 12px;
    }
    
    .modal-content h2 {
        font-size: 1.1rem;
    }
    
    .form-grid-2 {
        grid-template-columns: 1fr !important;
    }
}

.form-grid-2 {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
}

/* Botões Responsivos */
@media (max-width: 480px) {
    .page-header-flex {
        flex-direction: column;
        align-items: stretch;
    }
    
    .page-header-flex .btn {
        width: 100%;
        justify-content: center;
    }
    
    .btn-group-responsive {
        flex-direction: column;
        width: 100%;
    }
    
    .btn-group-responsive .btn {
        width: 100%;
    }
}

/* Empty State Responsivo */
.empty-state {
    padding: 3rem 1.5rem;
}

@media (max-width: 480px) {
    .empty-state {
        padding: 2rem 1rem;
    }
    
    .empty-state iconify-icon {
        font-size: 3rem !important;
    }
    
    .empty-state h3 {
        font-size: 1.1rem;
    }
}

/* Ações da Tabela */
.actions-cell {
    display: flex;
    gap: 0.5rem;
    flex-wrap: nowrap;
}

@media (max-width: 480px) {
    .actions-cell .btn-sm {
        padding: 0.4rem;
    }
}
/* === UPLOAD DE IMAGENS === */
.product-images-section {
    margin-top: 1rem;
}

.image-upload-area {
    border: 2px dashed var(--border);
    border-radius: 12px;
    padding: 1.5rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.5rem;
    background: var(--bg-secondary);
}

.image-upload-area:hover {
    border-color: var(--primary);
    background: rgba(var(--primary-rgb), 0.05);
}

.image-upload-area .upload-icon {
    font-size: 2.5rem;
    color: var(--primary);
}

.image-upload-area span {
    font-weight: 500;
    color: var(--text-primary);
}

.image-upload-area small {
    color: var(--text-muted);
    font-size: 0.75rem;
}

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

.image-preview-item {
    position: relative;
    aspect-ratio: 1;
    border-radius: 8px;
    overflow: hidden;
    border: 2px solid var(--border);
    background: var(--bg-secondary);
}

.image-preview-item.is-main {
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(var(--primary-rgb), 0.2);
}

.image-preview-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-preview-item .main-badge {
    position: absolute;
    top: 4px;
    left: 4px;
    background: var(--primary);
    color: white;
    font-size: 0.6rem;
    padding: 2px 6px;
    border-radius: 4px;
    font-weight: 600;
}

.image-preview-item .remove-btn {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 22px;
    height: 22px;
    border-radius: 50%;
    background: var(--error);
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    line-height: 1;
    opacity: 1;
    transition: opacity 0.2s;
}

.image-preview-item:hover .remove-btn {
    opacity: 1;
}

.image-preview-item .set-main-btn {
    position: absolute;
    bottom: 4px;
    left: 4px;
    right: 4px;
    background: rgba(0,0,0,0.7);
    color: white;
    font-size: 0.65rem;
    padding: 4px;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.2s;
}

.image-preview-item:hover .set-main-btn {
    opacity: 1;
}

@media (max-width: 480px) {
    .image-preview-grid {
        grid-template-columns: repeat(3, 1fr);
    }
}

/* === VARIAÇÕES DO PRODUTO === */
.product-variations-section {
    margin-top: 1.5rem;
    padding-top: 1.5rem;
    border-top: 1px solid var(--border);
}

.variation-item {
    display: grid;
    grid-template-columns: 1fr 1fr 100px 100px auto;
    gap: 0.5rem;
    align-items: end;
    padding: 0.75rem;
    background: var(--bg-secondary);
    border-radius: 8px;
    margin-bottom: 0.5rem;
}

.variation-item .form-group {
    margin-bottom: 0;
}

.variation-item .form-label {
    font-size: 0.7rem;
    margin-bottom: 0.25rem;
}

.variation-item .form-input {
    padding: 0.5rem;
    font-size: 0.85rem;
}

.variation-item .remove-variation-btn {
    background: var(--error);
    color: white;
    border: none;
    border-radius: 6px;
    padding: 0.5rem;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

@media (max-width: 768px) {
    .variation-item {
        grid-template-columns: 1fr 1fr;
        gap: 0.75rem;
    }
    
    .variation-item .remove-variation-btn {
        grid-column: span 2;
        justify-self: end;
    }
}

</style>

    <main class="main-content">
        <div class="page-header page-header-flex">
            <div>
                <h1><iconify-icon icon="solar:bag-bold"></iconify-icon> Produtos</h1>
                <p>Gerencie os produtos para venda</p>
            </div>
            <a href="/pages/produtos/novo.php" class="btn btn-primary">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                <span>Novo Produto</span>
            </a>
        </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; ?>

        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <iconify-icon icon="solar:bag-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo count($products); ?></span>
                    <span class="stat-label">Total de Produtos</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(34, 197, 94, 0.1); color: #22C55E;">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo count(array_filter($products, fn($p) => $p['is_active'])); ?></span>
                    <span class="stat-label">Ativos</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(239, 68, 68, 0.1); color: #EF4444;">
                    <iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo count(array_filter($products, fn($p) => ($p['stock_quantity'] ?? 0) <= 5)); ?></span>
                    <span class="stat-label">Estoque Baixo</span>
                </div>
            </div>
        </div>

        <!-- Filtro por Categoria -->
        <?php if (!empty($categories)): ?>
        <div class="card" style="margin-bottom: 1.5rem; padding: 1rem;">
            <form method="GET" class="filter-form">
                <label style="font-weight: 500; color: var(--text-muted);">Filtrar por categoria:</label>
                <select name="category" class="form-input" style="width: auto; min-width: 200px;" onchange="this.form.submit()">
                    <option value="">Todas as categorias</option>
                    <?php foreach ($categories as $cat): ?>
                    <option value="<?php echo $cat['id']; ?>" <?php echo $filterCategory == $cat['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($cat['name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
                <?php if ($filterCategory): ?>
                <a href="/pages/produtos.php" class="btn btn-secondary btn-sm">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                    Limpar
                </a>
                <?php endif; ?>
            </form>
        </div>
        <?php endif; ?>

        <?php if (empty($products)): ?>
        <div class="empty-state">
            <iconify-icon icon="solar:bag-bold"></iconify-icon>
            <h3>Nenhum produto cadastrado</h3>
            <p>Adicione produtos para vender.</p>
            <button class="btn btn-primary" onclick="openAddModal()" style="margin-top: 1rem;">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                Adicionar Produto
            </a>
        </div>
        <?php else: ?>
        
        <!-- Versão Cards (Mobile) -->
        <div class="products-grid">
            <?php foreach ($products as $product): ?>
            <div class="product-card">
                <?php if (!empty($product['image_url'])): ?>
                <div class="product-card-image">
                    <img src="<?php echo htmlspecialchars($product['image_url']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
                </div>
                <?php endif; ?>

                <div class="product-card-header">
                    <div style="flex: 1;">
                        <div class="product-card-title"><?php echo htmlspecialchars($product['name']); ?></div>
                        <?php if ($product['description']): ?>
                        <div class="product-card-desc"><?php echo htmlspecialchars($product['description']); ?></div>
                        <?php endif; ?>
                    </div>
                    <?php if ($product['is_active']): ?>
                    <span class="badge badge-success">Ativo</span>
                    <?php else: ?>
                    <span class="badge badge-secondary">Inativo</span>
                    <?php endif; ?>
                </div>
                
                <?php if ($product['category_name']): ?>
                <div style="margin-bottom: 0.75rem;">
                    <span class="product-card-category" style="background: <?php echo htmlspecialchars($product['category_color'] ?? '#CCA43B'); ?>20; color: <?php echo htmlspecialchars($product['category_color'] ?? '#CCA43B'); ?>;">
                        <iconify-icon icon="<?php echo htmlspecialchars($product['category_icon'] ?? 'solar:tag-bold'); ?>"></iconify-icon>
                        <?php echo htmlspecialchars($product['category_name']); ?>
                    </span>
                </div>
                <?php endif; ?>
                
                <div class="product-card-info">
                    <div class="product-info-item">
                        <div class="product-info-label">Preço</div>
                        <div class="product-info-value price">R$ <?php echo number_format($product['price'], 2, ',', '.'); ?></div>
                    </div>
                    <div class="product-info-item">
                        <div class="product-info-label">Estoque</div>
                        <?php
                        $stock = $product['stock_quantity'] ?? 0;
                        $stockClass = $stock <= 5 ? 'stock-low' : ($stock <= 10 ? 'stock-warning' : '');
                        ?>
                        <div class="product-info-value <?php echo $stockClass; ?>"><?php echo $stock; ?></div>
                    </div>
                    <div class="product-info-item">
                        <div class="product-info-label">SKU</div>
                        <div class="product-info-value" style="font-size: 0.8rem;"><?php echo $product['sku'] ? htmlspecialchars($product['sku']) : '-'; ?></div>
                    </div>
                </div>
                
                <div class="product-card-actions">
                    <a href="/pages/produtos/editar.php?id=<?php echo $product['id']; ?>" class="btn btn-secondary btn-sm">
                        <iconify-icon icon="solar:pen-bold"></iconify-icon>
                        Editar
                    </a>
                    <form method="POST" style="flex: 1;">
                        <input type="hidden" name="action" value="toggle">
                        <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
                        <button type="submit" class="btn btn-secondary btn-sm" style="width: 100%;">
                            <iconify-icon icon="<?php echo $product['is_active'] ? 'solar:eye-closed-bold' : 'solar:eye-bold'; ?>"></iconify-icon>
                            <?php echo $product['is_active'] ? 'Desativar' : 'Ativar'; ?>
                        </button>
                    </form>
                    <form method="POST" onsubmit="return confirm('Tem certeza que deseja excluir este produto?');">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
                        <button type="submit" class="btn btn-secondary btn-sm" style="color: var(--error);">
                            <iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>
                        </button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Versão Tabela (Desktop) -->
        <div class="card products-table">
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th style="width: 80px;">Foto</th>
                            <th>Produto</th>
                            <th>Categoria</th>
                            <th>SKU</th>
                            <th>Preço</th>
                            <th>Estoque</th>
                            <th>Status</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $product): ?>
                        <tr>
                            <td>
                                <?php if (!empty($product['image_url'])): ?>
                                <img src="<?php echo htmlspecialchars($product['image_url']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>" style="width: 60px; height: 60px; object-fit: cover; border-radius: 8px; border: 1px solid var(--border);">
                                <?php else: ?>
                                <div style="width: 60px; height: 60px; background: var(--bg-secondary); border-radius: 8px; display: flex; align-items: center; justify-content: center; border: 1px solid var(--border);">
                                    <iconify-icon icon="solar:image-bold" style="font-size: 1.5rem; color: var(--text-muted);"></iconify-icon>
                                </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div style="font-weight: 600;"><?php echo htmlspecialchars($product['name']); ?></div>
                                <?php if ($product['description']): ?>
                                <div style="font-size: 0.8rem; color: var(--text-muted);"><?php echo htmlspecialchars(substr($product['description'], 0, 50)); ?></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($product['category_name']): ?>
                                <span style="display: inline-flex; align-items: center; gap: 0.35rem; padding: 0.25rem 0.6rem; border-radius: 6px; font-size: 0.8rem; background: <?php echo htmlspecialchars($product['category_color'] ?? '#CCA43B'); ?>20; color: <?php echo htmlspecialchars($product['category_color'] ?? '#CCA43B'); ?>;">
                                    <iconify-icon icon="<?php echo htmlspecialchars($product['category_icon'] ?? 'solar:tag-bold'); ?>"></iconify-icon>
                                    <?php echo htmlspecialchars($product['category_name']); ?>
                                </span>
                                <?php else: ?>
                                <span style="color: var(--text-muted); font-size: 0.85rem;">Sem categoria</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($product['sku']): ?>
                                <code style="background: var(--bg-darker); padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.8rem;"><?php echo htmlspecialchars($product['sku']); ?></code>
                                <?php else: ?>
                                <span style="color: var(--text-muted);">-</span>
                                <?php endif; ?>
                            </td>
                            <td style="font-weight: 600; color: var(--primary);">
                                R$ <?php echo number_format($product['price'], 2, ',', '.'); ?>
                            </td>
                            <td>
                                <?php
                                $stock = $product['stock_quantity'] ?? 0;
                                $stockClass = $stock <= 5 ? 'color: var(--error);' : ($stock <= 10 ? 'color: var(--warning);' : '');
                                ?>
                                <span style="font-weight: 600; <?php echo $stockClass; ?>"><?php echo $stock; ?></span>
                            </td>
                            <td>
                                <?php if ($product['is_active']): ?>
                                <span class="badge badge-success">Ativo</span>
                                <?php else: ?>
                                <span class="badge badge-secondary">Inativo</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="actions-cell">
                                    <a href="/pages/produtos/editar.php?id=<?php echo $product['id']; ?>" class="btn btn-secondary btn-sm" title="Editar">
                                        <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                    </a>
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="action" value="toggle">
                                        <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
                                        <button type="submit" class="btn btn-secondary btn-sm" title="<?php echo $product['is_active'] ? 'Desativar' : 'Ativar'; ?>">
                                            <iconify-icon icon="<?php echo $product['is_active'] ? 'solar:eye-closed-bold' : 'solar:eye-bold'; ?>"></iconify-icon>
                                        </button>
                                    </form>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Tem certeza que deseja excluir este produto?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
                                        <button type="submit" class="btn btn-secondary btn-sm" style="color: var(--error);">
                                            <iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </main>

    <!-- Modal Adicionar/Editar -->
    <div id="productModal" class="modal-overlay">
        <div class="modal-content card">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                <h2 id="modalTitle" style="font-size: 1.25rem;">Novo Produto</h2>
                <button onclick="closeModal()" style="background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 1.5rem;">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                </a>
            </div>
            <form method="POST" id="productForm" enctype="multipart/form-data">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="productId" value="">

                <div class="form-group">
                    <label class="form-label">Nome do Produto *</label>
                    <input type="text" name="name" id="productName" class="form-input" placeholder="Ex: Pomada Modeladora" required>
                </div>

                <div class="form-group">
                    <label class="form-label">Categoria</label>
                    <select name="category_id" id="productCategory" class="form-input">
                        <option value="">Selecione uma categoria</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>" data-color="<?php echo htmlspecialchars($cat['color']); ?>" data-icon="<?php echo htmlspecialchars($cat['icon']); ?>">
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (empty($categories)): ?>
                    <p style="font-size: 0.8rem; color: var(--text-muted); margin-top: 0.5rem;">
                        <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                        <a href="/pages/categorias.php" style="color: var(--primary);">Crie categorias</a> para organizar seus produtos.
                    </p>
                    <?php endif; ?>
                </div>

                <div class="form-group">
                    <label class="form-label">Descrição</label>
                    <textarea name="description" id="productDescription" class="form-input" rows="2" placeholder="Descrição do produto..."></textarea>
                </div>

                <div class="form-grid-2">
                    <div class="form-group">
                        <label class="form-label">Preço *</label>
                        <input type="number" name="price" id="productPrice" class="form-input" step="0.01" min="0.01" placeholder="0,00" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Estoque</label>
                        <input type="number" name="stock" id="productStock" class="form-input" min="0" value="0">
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">SKU (código)</label>
                    <input type="text" name="sku" id="productSku" class="form-input" placeholder="Ex: POMADA-001">
                </div>

                <!-- Seção de Upload de Imagens -->
                <div class="form-group product-images-section">
                    <label class="form-label">Fotos do Produto (máx. 5)</label>
                    <input type="hidden" name="main_image_index" id="mainImageIndex" value="0">
                    <input type="hidden" name="existing_images" id="existingImages" value="[]">
                    
                    <div class="image-upload-area" id="imageUploadArea" onclick="document.getElementById('productImagesInput').click()">
                        <iconify-icon icon="solar:camera-add-bold-duotone" class="upload-icon"></iconify-icon>
                        <span>Clique para adicionar fotos</span>
                        <small>JPG, PNG ou WebP (máx. 2MB cada)</small>
                    </div>
                    
                    <input type="file" name="product_images[]" id="productImagesInput" multiple accept="image/jpeg,image/png,image/webp" style="display: none;" onchange="handleImageUpload(this)">
                    
                    <div class="image-preview-grid" id="imagePreviewGrid"></div>
                </div>


                <!-- Seção de Variações do Produto -->
                <div class="form-group product-variations-section">
                    <label class="form-label">Variações do Produto</label>
                    <p style="font-size: 0.8rem; color: var(--text-muted); margin-bottom: 0.75rem;">
                        <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                        Adicione variações como Tamanho (P, M, G) ou Cor (Azul, Vermelho)
                    </p>
                    
                    <div id="variationsContainer"></div>
                    
                    <button type="button" class="btn btn-secondary btn-sm" onclick="addVariation()" style="margin-top: 0.5rem;">
                        <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                        Adicionar Variação
                </div>

                <div style="display: flex; gap: 1rem; justify-content: flex-end; margin-top: 1.5rem; flex-wrap: wrap;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
                    <button type="submit" class="btn btn-primary" id="submitBtn">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        <span id="submitBtnText">Salvar</span>
                </div>
            </form>
        </div>
    </div>

<script>
function openAddModal() {
    document.getElementById('modalTitle').textContent = 'Novo Produto';
    document.getElementById('formAction').value = 'add';
    document.getElementById('productId').value = '';
    document.getElementById('productName').value = '';
    document.getElementById('productCategory').value = '';
    document.getElementById('productDescription').value = '';
    document.getElementById('productPrice').value = '';
    document.getElementById('productStock').value = '0';
    document.getElementById('productSku').value = '';
    document.getElementById('submitBtnText').textContent = 'Salvar';
    // Limpar variações
    clearVariations();
    document.getElementById('productModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function openEditModal(product) {
    document.getElementById('modalTitle').textContent = 'Editar Produto';
    document.getElementById('formAction').value = 'edit';
    document.getElementById('productId').value = product.id;
    document.getElementById('productName').value = product.name;
    document.getElementById('productCategory').value = product.category_id || '';
    document.getElementById('productDescription').value = product.description || '';
    document.getElementById('productPrice').value = product.price;
    document.getElementById('productStock').value = product.stock_quantity || 0;
    document.getElementById('productSku').value = product.sku || '';
    document.getElementById('submitBtnText').textContent = 'Atualizar';
    // Carregar variações do produto
    loadExistingVariations(product.variations || []);
    document.getElementById('productModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    document.getElementById('productModal').style.display = 'none';
    document.body.style.overflow = '';
}

// Fechar modal ao clicar fora
document.getElementById('productModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal();
    }
});

// Fechar modal com ESC
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeModal();
    }
});

// ==========================================
// GERENCIAMENTO DE IMAGENS DO PRODUTO
// ==========================================
var productImages = [];
var mainImageIndex = 0;

function handleImageUpload(input) {
    var files = input.files;
    var maxImages = 5;
    var currentCount = productImages.length;
    var allowedTypes = ["image/jpeg", "image/png", "image/webp"];
    var maxSize = 2 * 1024 * 1024; // 2MB
    
    for (var i = 0; i < files.length; i++) {
        if (currentCount + i >= maxImages) {
            alert("Máximo de " + maxImages + " fotos permitidas!");
            break;
        }
        
        var file = files[i];
        
        if (!allowedTypes.includes(file.type)) {
            alert("Tipo de arquivo não permitido: " + file.name);
            continue;
        }
        
        if (file.size > maxSize) {
            alert("Arquivo muito grande (máx 2MB): " + file.name);
            continue;
        }
        
        productImages.push({
            file: file,
            url: URL.createObjectURL(file),
            isNew: true
        });
    }
    
    input.value = "";
    renderImagePreviews();
}

function renderImagePreviews() {
    var grid = document.getElementById("imagePreviewGrid");
    grid.innerHTML = "";
    
    productImages.forEach(function(img, index) {
        var item = document.createElement("div");
        item.className = "image-preview-item" + (index === mainImageIndex ? " is-main" : "");
        
        var imgEl = document.createElement("img");
        imgEl.src = img.url;
        imgEl.alt = "Foto " + (index + 1);
        item.appendChild(imgEl);
        
        if (index === mainImageIndex) {
            var badge = document.createElement("span");
            badge.className = "main-badge";
            badge.textContent = "PRINCIPAL";
            item.appendChild(badge);
        }
        
        var removeBtn = document.createElement("button");
        removeBtn.type = "button";
        removeBtn.className = "remove-btn";
        removeBtn.innerHTML = "\u00d7";
        (function(idx) {
            removeBtn.onclick = function(e) {
                e.stopPropagation();
                removeImage(idx);
            };
        })(index);
        item.appendChild(removeBtn);
        
        if (index !== mainImageIndex) {
            var setMainBtn = document.createElement("button");
            setMainBtn.type = "button";
            setMainBtn.className = "set-main-btn";
            setMainBtn.textContent = "Definir principal";
            (function(idx) {
                setMainBtn.onclick = function(e) {
                    e.stopPropagation();
                    setMainImage(idx);
                };
            })(index);
            item.appendChild(setMainBtn);
        }
        
        grid.appendChild(item);
    });
    
    document.getElementById("mainImageIndex").value = mainImageIndex;
    updateUploadAreaVisibility();
}

function removeImage(index) {
    if (productImages[index].url.startsWith("blob:")) {
        URL.revokeObjectURL(productImages[index].url);
    }
    productImages.splice(index, 1);
    
    if (mainImageIndex >= productImages.length) {
        mainImageIndex = Math.max(0, productImages.length - 1);
    } else if (index < mainImageIndex) {
        mainImageIndex--;
    }
    
    renderImagePreviews();
}

function setMainImage(index) {
    mainImageIndex = index;
    renderImagePreviews();
}

function updateUploadAreaVisibility() {
    var uploadArea = document.getElementById("imageUploadArea");
    if (productImages.length >= 5) {
        uploadArea.style.display = "none";
    } else {
        uploadArea.style.display = "flex";
    }
}

function clearProductImages() {
    productImages.forEach(function(img) {
        if (img.url.startsWith("blob:")) {
            URL.revokeObjectURL(img.url);
        }
    });
    productImages = [];
    mainImageIndex = 0;
    renderImagePreviews();
}

function loadExistingImages(imageUrl, imagesJson) {
    console.log("loadExistingImages called with:", imageUrl, imagesJson);
    clearProductImages();
    
    if (imageUrl) {
        productImages.push({
            url: imageUrl,
            isNew: false,
            existing: imageUrl
        });
    }
    
    if (imagesJson && imagesJson !== "null") {
        try {
            var images = typeof imagesJson === "string" ? JSON.parse(imagesJson) : imagesJson;
            images.forEach(function(url) {
                if (url !== imageUrl) {
                    productImages.push({
                        url: url,
                        isNew: false,
                        existing: url
                    });
                }
            });
        } catch (e) { console.error("Error parsing images:", e); }
    }
    
    renderImagePreviews();
}

// Sobrescrever funções originais para incluir limpeza de imagens
var originalOpenAddModal = openAddModal;
openAddModal = function() {
    originalOpenAddModal();
    clearProductImages();
};

var originalOpenEditModal = openEditModal;
openEditModal = function(product) {
    originalOpenEditModal(product);
    loadExistingImages(product.image_url, product.images);
};

var originalCloseModal = closeModal;
closeModal = function() {
    originalCloseModal();
    clearProductImages();
};


// ==========================================
// GERENCIAMENTO DE VARIAÇÕES DO PRODUTO
// ==========================================
var productVariations = [];

function addVariation(data) {
    data = data || { id: null, name: "", value: "", price_adjustment: 0, stock_quantity: 0 };
    var index = productVariations.length;
    productVariations.push(data);
    renderVariations();
}

function removeVariation(index) {
    productVariations.splice(index, 1);
    renderVariations();
}

function renderVariations() {
    var container = document.getElementById("variationsContainer");
    container.innerHTML = "";
    
    productVariations.forEach(function(v, index) {
        var item = document.createElement("div");
        item.className = "variation-item";
        item.innerHTML = '<input type="hidden" name="variations[' + index + '][id]" value="' + (v.id || "") + '">' +
            '<div class="form-group">' +
            '<label class="form-label">Tipo</label>' +
            '<input type="text" name="variations[' + index + '][name]" class="form-input" placeholder="Ex: Tamanho" value="' + (v.name || "") + '" required>' +
            '</div>' +
            '<div class="form-group">' +
            '<label class="form-label">Valor</label>' +
            '<input type="text" name="variations[' + index + '][value]" class="form-input" placeholder="Ex: M" value="' + (v.value || "") + '" required>' +
            '</div>' +
            '<div class="form-group">' +
            '<label class="form-label">Ajuste R$</label>' +
            '<input type="number" name="variations[' + index + '][price_adjustment]" class="form-input" step="0.01" value="' + (v.price_adjustment || 0) + '">' +
            '</div>' +
            '<div class="form-group">' +
            '<label class="form-label">Estoque</label>' +
            '<input type="number" name="variations[' + index + '][stock_quantity]" class="form-input" min="0" value="' + (v.stock_quantity || 0) + '">' +
            '</div>' +
            '<button type="button" class="remove-variation-btn" onclick="removeVariation(' + index + ')" title="Remover">' +
            '<iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>' +
            '</button>';
        container.appendChild(item);
    });
}

function clearVariations() {
    productVariations = [];
    renderVariations();
}

function loadExistingVariations(variations) {
    clearVariations();
    if (variations && Array.isArray(variations)) {
        variations.forEach(function(v) {
            productVariations.push(v);
        });
        renderVariations();
    }
}

// Interceptar envio do form
document.getElementById("productForm").addEventListener("submit", function(e) {
    var existingImagesData = [];
    var newFiles = [];
    
    productImages.forEach(function(img, index) {
        if (!img.isNew && img.existing) {
            existingImagesData.push({
                url: img.existing,
                isMain: index === mainImageIndex
            });
        } else if (img.isNew && img.file) {
            newFiles.push(img.file);
        }
    });
    
    document.getElementById("existingImages").value = JSON.stringify(existingImagesData);
    
    // Adicionar novos arquivos ao input
    if (newFiles.length > 0) {
        var dataTransfer = new DataTransfer();
        newFiles.forEach(function(file) {
            dataTransfer.items.add(file);
        });
        document.getElementById("productImagesInput").files = dataTransfer.files;
    }
});


</script>

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