<?php
/**
 * Página de Estoque - MontaLoja SaaS
 * Versão Responsiva (Modo Loja/Varejo)
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/check-access.php';

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

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

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

// Verificar se tabela products existe
$tableExists = false;
try {
    $checkTable = $pdo->query("SHOW TABLES LIKE 'products'");
    $tableExists = $checkTable->rowCount() > 0;
} catch (Exception $e) {
    $tableExists = false;
}

// Filtros
$filter = $_GET['filter'] ?? '';
$categoryFilter = $_GET['category'] ?? '';
$search = trim($_GET['search'] ?? '');

// Processar ações
$message = '';
$messageType = '';
$products = [];
$categories = [];
$stats = ['total' => 0, 'low' => 0, 'out' => 0, 'value' => 0];

if ($tableExists) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';
        
        try {
            if ($action === 'adjust') {
                $productId = intval($_POST['product_id'] ?? 0);
                $adjustment = intval($_POST['adjustment'] ?? 0);
                $reason = trim($_POST['reason'] ?? '');
                
                if ($productId && $adjustment !== 0) {
                    // Atualizar estoque
                    $stmt = $pdo->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE id = ? AND store_id = ?");
                    $stmt->execute([$adjustment, $productId, $storeId]);
                    
                    // Registrar movimentação (se tabela existir)
                    try {
                        $type = $adjustment > 0 ? 'entrada' : 'saida';
                        $logStmt = $pdo->prepare("INSERT INTO stock_movements (store_id, product_id, type, quantity, reason, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
                        $logStmt->execute([$storeId, $productId, $type, abs($adjustment), $reason]);
                    } catch (Exception $e) {
                        // Tabela stock_movements pode não existir
                    }
                    
                    $message = 'Estoque ajustado com sucesso!';
                    $messageType = 'success';
                }
            }
        } catch (Exception $e) {
            $message = 'Erro ao processar: ' . $e->getMessage();
            $messageType = 'error';
        }
    }

    // Buscar categorias
    try {
        $catStmt = $pdo->prepare("SELECT * FROM categories WHERE store_id = ? ORDER BY name");
        $catStmt->execute([$storeId]);
        $categories = $catStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $categories = [];
    }

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

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

        if ($search) {
            $sql .= " AND (p.name LIKE ? OR p.sku LIKE ?)";
            $searchTerm = "%$search%";
            $params[] = $searchTerm;
            $params[] = $searchTerm;
        }

        // Filtros de estoque
        if ($filter === 'low') {
            $sql .= " AND p.stock_quantity <= COALESCE(p.low_stock_threshold, 5) AND p.stock_quantity > 0";
        } elseif ($filter === 'out') {
            $sql .= " AND p.stock_quantity = 0";
        } elseif ($filter === 'ok') {
            $sql .= " AND p.stock_quantity > COALESCE(p.low_stock_threshold, 5)";
        }

        $sql .= " ORDER BY p.stock_quantity ASC, p.name ASC";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $products = [];
    }

    // Estatísticas
    try {
        $allProductsStmt = $pdo->prepare("SELECT * FROM products WHERE store_id = ?");
        $allProductsStmt->execute([$storeId]);
        $allProducts = $allProductsStmt->fetchAll(PDO::FETCH_ASSOC);

        $stats = [
            'total' => count($allProducts),
            'low' => count(array_filter($allProducts, fn($p) => ($p['stock_quantity'] ?? 0) <= ($p['low_stock_threshold'] ?? 5) && ($p['stock_quantity'] ?? 0) > 0)),
            'out' => count(array_filter($allProducts, fn($p) => ($p['stock_quantity'] ?? 0) == 0)),
            'value' => array_sum(array_map(fn($p) => ($p['stock_quantity'] ?? 0) * ($p['price'] ?? 0), $allProducts))
        ];
    } catch (Exception $e) {
        $stats = ['total' => 0, 'low' => 0, 'out' => 0, 'value' => 0];
    }
}

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

<?php include __DIR__ . '/../includes/responsive-styles.php'; ?>

<style>
.stock-indicator {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.stock-bar {
    width: 60px;
    height: 8px;
    background: var(--border);
    border-radius: 4px;
    overflow: hidden;
}

.stock-bar-fill {
    height: 100%;
    border-radius: 4px;
    transition: width 0.3s;
}

.stock-bar-fill.ok {
    background: #22C55E;
}

.stock-bar-fill.low {
    background: #F59E0B;
}

.stock-bar-fill.out {
    background: #EF4444;
}

.stock-value {
    font-weight: 700;
    min-width: 40px;
}

.stock-value.ok { color: #22C55E; }
.stock-value.low { color: #F59E0B; }
.stock-value.out { color: #EF4444; }

.quick-adjust {
    display: flex;
    gap: 0.25rem;
    align-items: center;
}

.quick-adjust button {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    border: 1px solid var(--border);
    background: var(--bg-card);
    color: var(--text-primary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    padding: 0;
    flex-shrink: 0;
    font-size: 18px;
    font-weight: 700;
    line-height: 1;
}

.quick-adjust button:hover {
    background: var(--primary);
    color: #000;
    border-color: var(--primary);
    transform: scale(1.1);
}
</style>

    <main class="main-content">
        <div class="page-header page-header-flex">
            <div>
                <h1><iconify-icon icon="solar:box-bold"></iconify-icon> Controle de Estoque</h1>
                <p>Monitore e gerencie o estoque dos seus produtos</p>
            </div>
            <a href="produtos.php" class="btn btn-primary">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                <span>Adicionar 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; ?>
        
        <!-- Filtros -->
        <form method="GET" class="filter-bar">
            <div class="search-box" style="flex: 1; max-width: 300px;">
                
                <input type="text" name="search" class="form-input" placeholder="Buscar produto ou SKU..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            
            <select name="category" class="form-input" style="max-width: 180px;">
                <option value="">Todas Categorias</option>
                <?php foreach ($categories as $cat): ?>
                <option value="<?php echo $cat['id']; ?>" <?php echo $categoryFilter == $cat['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($cat['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
            
            <select name="filter" class="form-input" style="max-width: 180px;">
                <option value="">Todos os Níveis</option>
                <option value="ok" <?php echo $filter === 'ok' ? 'selected' : ''; ?>>Estoque OK</option>
                <option value="low" <?php echo $filter === 'low' ? 'selected' : ''; ?>>Estoque Baixo</option>
                <option value="out" <?php echo $filter === 'out' ? 'selected' : ''; ?>>Sem Estoque</option>
            </select>
            
            <button type="submit" class="btn btn-primary">
                <iconify-icon icon="solar:filter-bold"></iconify-icon>
                Filtrar
            </button>
        </form>
        
        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <iconify-icon icon="solar:box-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo $stats['total']; ?></span>
                    <span class="stat-label">Total de Produtos</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(245, 158, 11, 0.1); color: #F59E0B;">
                    <iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo $stats['low']; ?></span>
                    <span class="stat-label">Estoque Baixo</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:close-circle-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo $stats['out']; ?></span>
                    <span class="stat-label">Sem Estoque</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:wallet-money-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value">R$ <?php echo number_format($stats['value'], 0, ',', '.'); ?></span>
                    <span class="stat-label">Valor em Estoque</span>
                </div>
            </div>
        </div>
        
        <?php if (empty($products)): ?>
        <div class="empty-state">
            <iconify-icon icon="solar:box-bold"></iconify-icon>
            <h3>Nenhum produto encontrado</h3>
            <p>Não há produtos com os filtros selecionados.</p>
        </div>
        <?php else: ?>
        
        <!-- Versão Cards (Mobile) -->
        <div class="mobile-cards">
            <?php foreach ($products as $product): 
                $lowStock = $product['low_stock_threshold'] ?? 5;
                $stockLevel = $product['stock_quantity'] == 0 ? 'out' : ($product['stock_quantity'] <= $lowStock ? 'low' : 'ok');
                $stockPercent = $lowStock > 0 ? min(100, ($product['stock_quantity'] / ($lowStock * 2)) * 100) : 100;
            ?>
            <div class="mobile-card">
                <div class="mobile-card-header">
                    <div style="flex: 1;">
                        <div class="mobile-card-title"><?php echo htmlspecialchars($product['name']); ?></div>
                        <div class="mobile-card-subtitle">
                            <?php if ($product['sku']): ?>
                            SKU: <?php echo htmlspecialchars($product['sku']); ?>
                            <?php endif; ?>
                            <?php if ($product['category_name']): ?>
                            • <?php echo htmlspecialchars($product['category_name']); ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="mobile-card-info">
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Em Estoque</div>
                        <div class="stock-indicator">
                            <span class="stock-value <?php echo $stockLevel; ?>"><?php echo $product['stock_quantity']; ?></span>
                            <div class="stock-bar">
                                <div class="stock-bar-fill <?php echo $stockLevel; ?>" style="width: <?php echo $stockPercent; ?>%;"></div>
                            </div>
                        </div>
                    </div>
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Mínimo</div>
                        <div class="mobile-card-info-value"><?php echo $lowStock; ?></div>
                    </div>
                </div>
                
                <div class="mobile-card-info">
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Preço Venda</div>
                        <div class="mobile-card-info-value text-primary">R$ <?php echo number_format($product['price'] ?? 0, 2, ',', '.'); ?></div>
                    </div>
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Preço Custo</div>
                        <div class="mobile-card-info-value">R$ <?php echo number_format(0, 2, ',', '.'); ?></div>
                    </div>
                </div>
                
                <div class="mobile-card-actions">
                    <button type="button" class="btn btn-secondary btn-sm" style="flex: 1;" onclick='openAdjustModal(<?php echo json_encode($product); ?>)'>
                        <iconify-icon icon="solar:pen-bold"></iconify-icon>
                        Ajustar Estoque
                    </button>
                    <div class="quick-adjust">
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="action" value="adjust">
                            <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                            <input type="hidden" name="adjustment" value="-1">
                            <input type="hidden" name="reason" value="Ajuste rápido">
                            <button type="submit" title="-1">−</button>
                        </form>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="action" value="adjust">
                            <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                            <input type="hidden" name="adjustment" value="1">
                            <input type="hidden" name="reason" value="Ajuste rápido">
                            <button type="submit" title="+1">+</button>
                        </form>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Versão Tabela (Desktop) -->
        <div class="card desktop-table">
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Produto</th>
                            <th>Categoria</th>
                            <th>Estoque</th>
                            <th>Mínimo</th>
                            <th>Preço Venda</th>
                            <th>Valor Total</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $product): 
                            $lowStock = $product['low_stock_threshold'] ?? 5;
                            $stockLevel = $product['stock_quantity'] == 0 ? 'out' : ($product['stock_quantity'] <= $lowStock ? 'low' : 'ok');
                            $stockPercent = $lowStock > 0 ? min(100, ($product['stock_quantity'] / ($lowStock * 2)) * 100) : 100;
                            $totalValue = $product['stock_quantity'] * ($product['price'] ?? 0);
                        ?>
                        <tr>
                            <td>
                                <div style="font-weight: 600;"><?php echo htmlspecialchars($product['name']); ?></div>
                                <?php if ($product['sku']): ?>
                                <div style="font-size: 0.85rem; color: var(--text-muted);">SKU: <?php echo htmlspecialchars($product['sku']); ?></div>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($product['category_name'] ?? '-'); ?></td>
                            <td>
                                <div class="stock-indicator">
                                    <span class="stock-value <?php echo $stockLevel; ?>"><?php echo $product['stock_quantity']; ?></span>
                                    <div class="stock-bar">
                                        <div class="stock-bar-fill <?php echo $stockLevel; ?>" style="width: <?php echo $stockPercent; ?>%;"></div>
                                    </div>
                                </div>
                            </td>
                            <td><?php echo $lowStock; ?></td>
                            <td>R$ <?php echo number_format($product['price'] ?? 0, 2, ',', '.'); ?></td>
                            <td style="font-weight: 600;">R$ <?php echo number_format($totalValue, 2, ',', '.'); ?></td>
                            <td>
                                <div class="actions-cell">
                                    <button type="button" class="btn btn-secondary btn-sm" title="Ajustar Estoque" onclick='openAdjustModal(<?php echo json_encode($product); ?>)'>
                                        <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                    </button>
                                    <div class="quick-adjust">
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="action" value="adjust">
                                            <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                                            <input type="hidden" name="adjustment" value="-1">
                                            <input type="hidden" name="reason" value="Ajuste rápido">
                                            <button type="submit" title="-1">−</button>
                                        </form>
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="action" value="adjust">
                                            <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                                            <input type="hidden" name="adjustment" value="1">
                                            <input type="hidden" name="reason" value="Ajuste rápido">
                                            <button type="submit" title="+1">+</button>
                                        </form>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </main>
    
    <!-- Modal Ajuste de Estoque -->
    <div id="adjustModal" class="modal-overlay">
        <div class="modal-content card" style="max-width: 450px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                <h2 style="font-size: 1.25rem;">Ajustar Estoque</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>
                </button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="adjust">
                <input type="hidden" name="product_id" id="adjustProductId" value="">
                
                <div class="form-group">
                    <label class="form-label">Produto</label>
                    <div id="adjustProductName" style="font-weight: 600; padding: 0.75rem; background: var(--bg); border-radius: var(--radius);"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Estoque Atual</label>
                    <div id="adjustCurrentStock" style="font-weight: 600; font-size: 1.25rem; color: var(--primary);"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Ajuste *</label>
                    <input type="number" name="adjustment" id="adjustAmount" class="form-input" placeholder="Ex: 10 ou -5" required>
                    <small style="color: var(--text-muted);">Use números positivos para entrada e negativos para saída</small>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Motivo</label>
                    <select name="reason" class="form-input">
                        <option value="Compra/Reposição">Compra/Reposição</option>
                        <option value="Venda manual">Venda manual</option>
                        <option value="Inventário">Inventário</option>
                        <option value="Devolução">Devolução</option>
                        <option value="Perda/Avaria">Perda/Avaria</option>
                        <option value="Outro">Outro</option>
                    </select>
                </div>
                
                <div style="display: flex; gap: 1rem; justify-content: flex-end; flex-wrap: wrap;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
                    <button type="submit" class="btn btn-primary">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        Confirmar Ajuste
                    </button>
                </div>
            </form>
        </div>
    </div>

<script>
function openAdjustModal(product) {
    document.getElementById('adjustProductId').value = product.id;
    document.getElementById('adjustProductName').textContent = product.name;
    document.getElementById('adjustCurrentStock').textContent = product.stock_quantity + ' unidades';
    document.getElementById('adjustAmount').value = '';
    document.getElementById('adjustModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

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

document.getElementById('adjustModal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeModal();
});
</script>

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