<?php
require_once 'db_config.php';
session_start();

if (!isset($_SESSION['usuario_id'])) {
    header("Location: index.php");
    exit;
}

$usuario_id = $_SESSION['usuario_id'];

// Buscar ativos com saldo livre para o select do modal
$stmtAtivos = $pdo->prepare("
    SELECT id, ticker, (quantidade_total - quantidade_bloqueada) as saldo_livre 
    FROM ativos 
    WHERE usuario_id = ? AND (quantidade_total - quantidade_bloqueada) >= 100
    ORDER BY ticker ASC
");
$stmtAtivos->execute([$usuario_id]);
$ativos_livres = $stmtAtivos->fetchAll();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Operações de Opções - Carteira PRO</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="../css/global.css">
    <link rel="stylesheet" href="../css/layout.css">
    <style>
        .modal-overlay {
            background-color: rgba(15, 23, 42, 0.6);
            backdrop-filter: blur(4px);
        }
        .modal-content {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- Sidebar -->
        <?php require_once 'menu.php'; ?>
        
        <!-- Main Content -->
        <main class="main-content">
            <div class="topbar animate-slide-up">
                <div class="flex items-center gap-4">
                    <button id="menu-toggle" class="lg:hidden text-gray-500 hover:text-blue-500">☰</button>
                    <h2 class="text-xl font-bold text-gray-800 m-0">🔄 Gestão de Opções</h2>
                </div>
                <div class="flex items-center gap-4">
                    <div class="flex items-center gap-2 font-medium text-gray-700">
                        <span>Olá, <?php echo htmlspecialchars($_SESSION['usuario_nome'] ?? 'Usuário'); ?></span>
                    </div>
                </div>
            </div>
            
            <div class="content-wrapper animate-slide-up delay-100">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-lg font-bold text-gray-800">Opções Abertas (Open)</h3>
                    <button onclick="abrirModalNovaOperacao()" class="btn btn-primary shadow-lg hover:shadow-xl transform hover:-translate-y-1 transition-all">
                        + Nova Venda Coberta
                    </button>
                </div>

                <div id="alert-container"></div>

                <div class="table-container mb-8">
                    <table class="data-table" id="tabela-operacoes-abertas">
                        <thead>
                            <tr>
                                <th>Ativo</th>
                                <th>Ticker Opção</th>
                                <th>Tipo</th>
                                <th>Strike</th>
                                <th>Prêmio</th>
                                <th>Contratos</th>
                                <th>Notional</th>
                                <th>Vencimento</th>
                                <th>Ações</th>
                            </tr>
                        </thead>
                        <tbody id="tbody-abertas">
                            <tr><td colspan="9" class="text-center py-4">Carregando...</td></tr>
                        </tbody>
                    </table>
                </div>

                <div class="flex justify-between items-center mb-6 mt-12">
                    <h3 class="text-lg font-bold text-gray-800">Histórico de Opções (History)</h3>
                </div>

                <div class="table-container">
                    <table class="data-table" id="tabela-operacoes-historico">
                        <thead>
                            <tr>
                                <th>Ativo</th>
                                <th>Ticker Opção</th>
                                <th>Status</th>
                                <th>Fechamento</th>
                                <th>Lucro Bruto</th>
                                <th>IR (15%)</th>
                                <th>Lucro Líquido</th>
                                <th>Data Fechamento</th>
                            </tr>
                        </thead>
                        <tbody id="tbody-historico">
                            <tr><td colspan="8" class="text-center py-4">Carregando...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>

    <!-- MODAL NOVA VENDA COBERTA -->
    <div id="modalNovaOperacao" class="fixed inset-0 z-50 hidden flex items-center justify-center modal-overlay p-4 overflow-y-auto">
        <div class="bg-white rounded-3xl shadow-2xl w-full max-w-lg p-8 modal-content transform scale-95 opacity-0 border-t-6 border-blue-500 my-8">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-2xl font-bold text-gray-800">Nova Venda Coberta</h3>
                <button onclick="fecharModal('modalNovaOperacao')" class="text-gray-400 hover:text-red-500 text-2xl font-bold">&times;</button>
            </div>
            
            <form id="formNovaOperacao" onsubmit="salvarNovaOperacao(event)" class="space-y-4">
                <input type="hidden" id="op-tipo" value="CALL">
                <input type="hidden" id="op-direcao" value="VENDA">
                
                <div class="form-group">
                    <label class="form-label">Ativo Subjacente (Com saldo livre >= 100)</label>
                    <select id="op-ativo-id" class="form-control" required onchange="atualizarMaxContratos()">
                        <option value="">Selecione um ativo...</option>
                        <?php foreach ($ativos_livres as $ativo): ?>
                            <option value="<?php echo $ativo['id']; ?>" data-saldo="<?php echo $ativo['saldo_livre']; ?>">
                                <?php echo htmlspecialchars($ativo['ticker']); ?> (Livre: <?php echo $ativo['saldo_livre']; ?> ações)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="grid grid-cols-2 gap-4">
                    <div class="form-group">
                        <label class="form-label">Ticker da Opção</label>
                        <input type="text" id="op-ticker-opcao" class="form-control uppercase" required placeholder="Ex: PETRC400">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Qtd. Contratos (1 = 100 ações)</label>
                        <input type="number" id="op-contratos" class="form-control" required min="1" step="1">
                        <p class="text-xs text-gray-500 mt-1" id="hint-contratos">Ações bloqueadas: 0</p>
                    </div>
                </div>
                
                <div class="grid grid-cols-2 gap-4">
                    <div class="form-group">
                        <label class="form-label">Strike (R$)</label>
                        <input type="number" id="op-strike" class="form-control" required min="0.01" step="0.01">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Prêmio Recebido (R$)</label>
                        <input type="number" id="op-premium" class="form-control" required min="0.01" step="0.01">
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div class="form-group">
                        <label class="form-label">Data da Operação</label>
                        <input type="date" id="op-data" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Data de Vencimento</label>
                        <input type="date" id="op-vencimento" class="form-control" required>
                    </div>
                </div>

                <div class="flex gap-4 mt-8">
                    <button type="button" onclick="fecharModal('modalNovaOperacao')" class="flex-1 py-3 px-4 rounded-xl border-2 border-gray-200 text-gray-600 font-bold hover:bg-gray-50 transition-colors">Cancelar</button>
                    <button type="submit" class="flex-1 py-3 px-4 rounded-xl bg-blue-600 text-white font-bold hover:bg-blue-700 transition-colors shadow-md">Salvar Venda Coberta</button>
                </div>
            </form>
        </div>
    </div>

    <!-- MODAL GERENCIAR OPERAÇÃO -->
    <div id="modalGerenciar" class="fixed inset-0 z-50 hidden flex items-center justify-center modal-overlay p-4">
        <div class="bg-white rounded-3xl shadow-2xl w-full max-w-md p-8 modal-content transform scale-95 opacity-0 border-t-6 border-purple-500">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-2xl font-bold text-gray-800">Gerenciar Opção</h3>
                <button onclick="fecharModal('modalGerenciar')" class="text-gray-400 hover:text-red-500 text-2xl font-bold">&times;</button>
            </div>
            
            <div class="bg-gray-50 p-4 rounded-xl mb-6 border border-gray-200">
                <div class="flex justify-between mb-2">
                    <span class="text-gray-500 font-medium">Opção:</span>
                    <span class="font-bold text-purple-600 text-lg" id="ger-ticker-display"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500 font-medium">Prêmio Recebido:</span>
                    <span class="font-bold text-green-600" id="ger-premio-display"></span>
                </div>
            </div>

            <form id="formGerenciar" onsubmit="salvarGerenciamento(event)" class="space-y-4">
                <input type="hidden" id="ger-id">
                
                <div class="form-group">
                    <label class="form-label">Novo Status</label>
                    <select id="ger-status" class="form-control" required onchange="togglePrecoFechamento()">
                        <option value="VENCIDA">Vencida (Virou Pó) - 100% Lucro</option>
                        <option value="EXERCIDA">Exercida (Ações serão vendidas)</option>
                        <option value="FECHADA">Recomprada (Fechada Manualmente)</option>
                    </select>
                </div>

                <div class="form-group" id="div-preco-fechamento" style="display: none;">
                    <label class="form-label">Preço de Recompra (R$)</label>
                    <input type="number" id="ger-preco" class="form-control" min="0" step="0.01" value="0">
                    <p class="text-xs text-gray-500 mt-1">Quanto você pagou para recomprar a opção.</p>
                </div>

                <div class="flex gap-4 mt-8">
                    <button type="button" onclick="fecharModal('modalGerenciar')" class="flex-1 py-3 px-4 rounded-xl border-2 border-gray-200 text-gray-600 font-bold hover:bg-gray-50 transition-colors">Cancelar</button>
                    <button type="submit" class="flex-1 py-3 px-4 rounded-xl bg-purple-600 text-white font-bold hover:bg-purple-700 transition-colors shadow-md">Confirmar</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Scripts -->
    <script src="../javascript/api_client.js"></script>
    <script>
        // Setar data de hoje por padrão
        document.getElementById('op-data').valueAsDate = new Date();

        document.addEventListener('DOMContentLoaded', () => {
            carregarOperacoesAbertas();
            carregarHistorico();
        });

        // Funções de Modal
        function abrirModal(id) {
            const modal = document.getElementById(id);
            const content = modal.querySelector('.modal-content');
            modal.classList.remove('hidden');
            void modal.offsetWidth; // trigger reflow
            content.classList.remove('scale-95', 'opacity-0');
            content.classList.add('scale-100', 'opacity-100');
        }

        function fecharModal(id) {
            const modal = document.getElementById(id);
            const content = modal.querySelector('.modal-content');
            content.classList.remove('scale-100', 'opacity-100');
            content.classList.add('scale-95', 'opacity-0');
            setTimeout(() => { modal.classList.add('hidden'); }, 300);
        }

        function atualizarMaxContratos() {
            const select = document.getElementById('op-ativo-id');
            const option = select.options[select.selectedIndex];
            const inputContratos = document.getElementById('op-contratos');
            const hint = document.getElementById('hint-contratos');
            
            if (option.value) {
                const saldo = parseInt(option.getAttribute('data-saldo'));
                const maxContratos = Math.floor(saldo / 100);
                inputContratos.max = maxContratos;
                
                inputContratos.addEventListener('input', () => {
                    const val = parseInt(inputContratos.value) || 0;
                    hint.textContent = `Ações bloqueadas: ${val * 100} de ${saldo} livres`;
                    if (val > maxContratos) {
                        hint.classList.add('text-red-500');
                    } else {
                        hint.classList.remove('text-red-500');
                    }
                });
            }
        }

        async function carregarOperacoesAbertas() {
            try {
                const res = await ApiClient.get('api_operacoes.php?tipo=abertas');
                const tbody = document.getElementById('tbody-abertas');
                tbody.innerHTML = '';
                
                if (!res.data || res.data.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="9" class="text-center py-8 text-gray-500">Nenhuma operação aberta encontrada.</td></tr>';
                    return;
                }

                res.data.forEach(op => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td class="font-bold text-lg">${op.ativo_subjacente}</td>
                        <td><span class="badge badge-aberta">${op.ticker_opcao}</span></td>
                        <td>${op.direcao} ${op.tipo_opcao}</td>
                        <td class="font-medium">${Utils.formatarMoeda(op.strike)}</td>
                        <td class="text-green-600 font-bold">${Utils.formatarMoeda(op.premium)}</td>
                        <td>${op.contracts}</td>
                        <td>${Utils.formatarMoeda(op.notional)}</td>
                        <td class="font-medium">${Utils.formatarData(op.data_vencimento)}</td>
                        <td>
                            <button onclick='abrirModalGerenciar(${JSON.stringify(op)})' class="px-3 py-1 bg-purple-100 text-purple-700 rounded-lg text-sm font-bold hover:bg-purple-200 transition-colors">Gerenciar</button>
                        </td>
                    `;
                    tbody.appendChild(tr);
                });
            } catch (e) {
                console.error(e);
            }
        }

        async function carregarHistorico() {
            try {
                const res = await ApiClient.get('api_operacoes.php?tipo=historico');
                const tbody = document.getElementById('tbody-historico');
                tbody.innerHTML = '';
                
                if (!res.data || res.data.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="8" class="text-center py-8 text-gray-500">Nenhum histórico encontrado.</td></tr>';
                    return;
                }

                res.data.forEach(op => {
                    let badgeClass = 'badge-fechada';
                    if (op.status === 'EXERCIDA') badgeClass = 'badge-exercida';
                    if (op.status === 'VENCIDA') badgeClass = 'badge-vencida';

                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td class="font-bold text-lg">${op.ativo_subjacente}</td>
                        <td class="font-medium text-gray-700">${op.ticker_opcao}</td>
                        <td><span class="badge ${badgeClass}">${op.status}</span></td>
                        <td>${Utils.formatarMoeda(op.preco_fechamento)}</td>
                        <td class="${op.gross >= 0 ? 'text-green-600' : 'text-red-600'} font-medium">${Utils.formatarMoeda(op.gross)}</td>
                        <td class="text-red-500">${Utils.formatarMoeda(op.ir)}</td>
                        <td class="${op.net >= 0 ? 'text-green-600' : 'text-red-600'} font-bold text-lg">${Utils.formatarMoeda(op.net)}</td>
                        <td class="text-gray-500 text-sm">${Utils.formatarData(op.data_fechamento)}</td>
                    `;
                    tbody.appendChild(tr);
                });
            } catch (e) {
                console.error(e);
            }
        }

        function abrirModalNovaOperacao() {
            document.getElementById('formNovaOperacao').reset();
            document.getElementById('op-data').valueAsDate = new Date();
            abrirModal('modalNovaOperacao');
        }

        async function salvarNovaOperacao(e) {
            e.preventDefault();
            
            const data = {
                ativo_id: document.getElementById('op-ativo-id').value,
                ticker_opcao: document.getElementById('op-ticker-opcao').value,
                tipo_opcao: document.getElementById('op-tipo').value,
                direcao: document.getElementById('op-direcao').value,
                contracts: document.getElementById('op-contratos').value,
                strike: document.getElementById('op-strike').value,
                premium: document.getElementById('op-premium').value,
                data_operacao: document.getElementById('op-data').value,
                data_vencimento: document.getElementById('op-vencimento').value
            };

            try {
                const res = await ApiClient.post('api_operacoes.php', data);
                if (res.status === 'success') {
                    Alertas.sucesso(res.message);
                    fecharModal('modalNovaOperacao');
                    carregarOperacoesAbertas();
                    
                    // Atualizar a página para recarregar os saldos livres no select
                    setTimeout(() => window.location.reload(), 1500);
                }
            } catch (error) {
                Alertas.erro(error.message);
            }
        }

        function abrirModalGerenciar(op) {
            document.getElementById('ger-id').value = op.id;
            document.getElementById('ger-ticker-display').textContent = op.ticker_opcao;
            document.getElementById('ger-premio-display').textContent = Utils.formatarMoeda(op.premium);
            
            document.getElementById('ger-status').value = 'VENCIDA';
            togglePrecoFechamento();
            
            abrirModal('modalGerenciar');
        }

        function togglePrecoFechamento() {
            const status = document.getElementById('ger-status').value;
            const div = document.getElementById('div-preco-fechamento');
            const input = document.getElementById('ger-preco');
            
            if (status === 'FECHADA') {
                div.style.display = 'block';
                input.required = true;
            } else {
                div.style.display = 'none';
                input.required = false;
                input.value = 0;
            }
        }

        async function salvarGerenciamento(e) {
            e.preventDefault();
            
            const data = {
                id: document.getElementById('ger-id').value,
                status: document.getElementById('ger-status').value,
                preco_fechamento: document.getElementById('ger-preco').value
            };

            try {
                const res = await ApiClient.put('api_operacoes.php', data);
                if (res.status === 'success') {
                    Alertas.sucesso(res.message);
                    fecharModal('modalGerenciar');
                    carregarOperacoesAbertas();
                    carregarHistorico();
                }
            } catch (error) {
                Alertas.erro(error.message);
            }
        }
    </script>
</body>
</html>
