<?php
require 'db.php';

// ===== LÓGICA PARA PROCESSAR AÇÕES =====
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['acao'])) {
        switch ($_POST['acao']) {
            case 'adicionar_conta':
                $nome_conta = trim($_POST['nome_conta']);
                $descricao = trim($_POST['descricao']);
                $valor = (float)str_replace(',', '.', $_POST['valor']);
                $data_vencimento = $_POST['data_vencimento'];
                $observacoes = trim($_POST['observacoes']);
                
                if (!empty($nome_conta) && $valor > 0 && !empty($data_vencimento)) {
                    $sql = "INSERT INTO contas_pagar (nome_conta, descricao, valor, data_vencimento, observacoes) VALUES (?, ?, ?, ?, ?)";
                    $stmt = $conexao->prepare($sql);
                    $stmt->bind_param('ssdss', $nome_conta, $descricao, $valor, $data_vencimento, $observacoes);
                    if ($stmt->execute()) {
                        header("Location: contas.php?status=success");
                        exit();
                    }
                }
                header("Location: contas.php?status=error");
                exit();
                break;
                
            case 'marcar_pago':
                $id = (int)$_POST['id'];
                $data_pagamento = $_POST['data_pagamento'];
                $forma_pagamento = trim($_POST['forma_pagamento']);
                
                $sql = "UPDATE contas_pagar SET status = 'pago', data_pagamento = ?, forma_pagamento = ? WHERE id = ?";
                $stmt = $conexao->prepare($sql);
                $stmt->bind_param('ssi', $data_pagamento, $forma_pagamento, $id);
                $stmt->execute();
                header("Location: contas.php?status=paid");
                exit();
                break;
                
            case 'excluir_conta':
                $id = (int)$_POST['id'];
                $sql = "DELETE FROM contas_pagar WHERE id = ?";
                $stmt = $conexao->prepare($sql);
                $stmt->bind_param('i', $id);
                if ($stmt->execute()) {
                    header("Location: contas.php?status=deleted");
                    exit();
                }
                header("Location: contas.php?status=error");
                exit();
                break;
                
            case 'limpar_todas_contas':
                if (isset($_POST['confirmar_limpeza']) && $_POST['confirmar_limpeza'] == 'SIM') {
                    $conexao->query("TRUNCATE TABLE contas_pagar");
                    header("Location: contas.php?status=all_deleted");
                    exit();
                }
                header("Location: contas.php?status=error");
                exit();
                break;
        }
    }
}

// ===== BUSCAR CONTAS =====
$filtro = isset($_GET['filtro']) ? $_GET['filtro'] : 'todas';
$where_clause = "";
switch ($filtro) {
    case 'pendentes':
        $where_clause = "WHERE status = 'pendente'";
        break;
    case 'vencidas':
        $where_clause = "WHERE status = 'pendente' AND data_vencimento < CURDATE()";
        break;
    case 'pagas':
        $where_clause = "WHERE status = 'pago'";
        break;
    case 'vencendo':
        $where_clause = "WHERE status = 'pendente' AND data_vencimento BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)";
        break;
}

$sql_contas = "SELECT * FROM contas_pagar $where_clause ORDER BY data_vencimento ASC";
$contas = $conexao->query($sql_contas);

// Atualizar status das contas vencidas
$conexao->query("UPDATE contas_pagar SET status = 'vencido' WHERE status = 'pendente' AND data_vencimento < CURDATE()");

// Estatísticas
$stats = $conexao->query("
    SELECT 
        COUNT(CASE WHEN status = 'pendente' THEN 1 END) as pendentes,
        COUNT(CASE WHEN status = 'vencido' THEN 1 END) as vencidas,
        COUNT(CASE WHEN status = 'pago' THEN 1 END) as pagas,
        SUM(CASE WHEN status IN ('pendente', 'vencido') THEN valor ELSE 0 END) as valor_pendente
    FROM contas_pagar
")->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Controle de Contas - Financeiro Imobiliária e Aury</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #333; min-height: 100vh; }
        
        .header { background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); box-shadow: 0 4px 20px rgba(0,0,0,0.1); padding: 20px 0; margin-bottom: 30px; }
        .header-content { max-width: 1200px; margin: 0 auto; display: flex; align-items: center; justify-content: space-between; padding: 0 25px; }
        .logo-section { display: flex; align-items: center; gap: 20px; }
        .logo-section img { height: 60px; width: auto; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .title-section h1 { font-size: 28px; font-weight: 700; color: #2c3e50; margin-bottom: 5px; }
        .title-section p { font-size: 14px; color: #7f8c8d; font-weight: 500; }
        
        .container { max-width: 1200px; margin: auto; background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); padding: 30px; border-radius: 16px; box-shadow: 0 8px 32px rgba(0,0,0,0.1); }
        
        .navigation { display: flex; justify-content: center; gap: 15px; margin-bottom: 30px; padding: 15px; background: rgba(52, 73, 94, 0.05); border-radius: 12px; }
        .nav-link { padding: 12px 24px; background: linear-gradient(135deg, #3498db, #2980b9); color: white; text-decoration: none; border-radius: 8px; transition: all 0.3s ease; font-weight: 500; box-shadow: 0 2px 8px rgba(52, 152, 219, 0.3); }
        .nav-link:hover { transform: translateY(-2px); box-shadow: 0 4px 16px rgba(52, 152, 219, 0.4); }
        .nav-link.active { background: linear-gradient(135deg, #2c3e50, #34495e); box-shadow: 0 4px 16px rgba(44, 62, 80, 0.4); }
        
        .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 30px 0; }
        .stat-box { background: linear-gradient(135deg, #f8f9fa, #e9ecef); padding: 25px; border-radius: 12px; text-align: center; box-shadow: 0 4px 16px rgba(0,0,0,0.05); }
        .stat-box h3 { font-size: 14px; color: #7f8c8d; text-transform: uppercase; margin-bottom: 10px; font-weight: 600; letter-spacing: 1px; }
        .stat-box p { font-size: 28px; font-weight: 700; margin: 0; }
        .pendente { color: #f39c12; }
        .vencida { color: #e74c3c; }
        .paga { color: #27ae60; }
        
        .form-container, .filter-container { background: linear-gradient(135deg, #f8f9fa, #e9ecef); padding: 25px; border-radius: 12px; margin-bottom: 25px; box-shadow: 0 4px 16px rgba(0,0,0,0.05); }
        .form-container h2, .filter-container h2 { color: #2c3e50; margin-bottom: 20px; font-weight: 600; }
        
        .form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 20px; }
        .form-group { display: flex; flex-direction: column; }
        .form-group label { margin-bottom: 8px; font-weight: 600; color: #2c3e50; font-size: 14px; }
        .form-group input, .form-group select, .form-group textarea { padding: 12px; border: 2px solid #e9ecef; border-radius: 8px; font-size: 14px; transition: all 0.3s ease; background: white; }
        .form-group input:focus, .form-group select:focus, .form-group textarea:focus { outline: none; border-color: #3498db; box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1); }
        .form-group button { padding: 14px; background: linear-gradient(135deg, #27ae60, #2ecc71); color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 4px 16px rgba(39, 174, 96, 0.3); }
        .form-group button:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(39, 174, 96, 0.4); }
        
        .btn-small { padding: 8px 16px; font-size: 12px; margin: 2px; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; transition: all 0.3s ease; }
        .btn-success { background: linear-gradient(135deg, #27ae60, #2ecc71); color: white; }
        .btn-danger { background: linear-gradient(135deg, #e74c3c, #c0392b); color: white; }
        .btn-small:hover { transform: translateY(-1px); }
        
        table { width: 100%; border-collapse: collapse; margin-top: 20px; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 16px rgba(0,0,0,0.05); }
        th, td { padding: 16px; text-align: left; border-bottom: 1px solid #e9ecef; }
        th { background: linear-gradient(135deg, #34495e, #2c3e50); color: white; font-weight: 600; text-transform: uppercase; font-size: 12px; letter-spacing: 1px; }
        tr:hover { background-color: rgba(52, 152, 219, 0.05); }
        
        .alert { padding: 16px; margin-bottom: 20px; border-radius: 8px; text-align: center; font-weight: 600; }
        .alert-success { background: linear-gradient(135deg, #d4edda, #c3e6cb); color: #155724; border: 1px solid #c3e6cb; }
        .alert-error { background: linear-gradient(135deg, #f8d7da, #f5c6cb); color: #721c24; border: 1px solid #f5c6cb; }
        .alert-warning { background: linear-gradient(135deg, #fff3cd, #ffeaa7); color: #856404; border: 1px solid #ffeaa7; }
        
        .status-badge { padding: 6px 12px; border-radius: 20px; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; }
        .status-pendente { background: linear-gradient(135deg, #fff3cd, #ffeaa7); color: #856404; }
        .status-vencido { background: linear-gradient(135deg, #f8d7da, #fab1a0); color: #721c24; }
        .status-pago { background: linear-gradient(135deg, #d4edda, #a8e6cf); color: #155724; }
        
        .filters { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; justify-content: center; }
        .filter-btn { padding: 10px 20px; border: 2px solid #e9ecef; background: white; border-radius: 8px; text-decoration: none; color: #2c3e50; font-weight: 600; transition: all 0.3s ease; }
        .filter-btn.active { background: linear-gradient(135deg, #3498db, #2980b9); color: white; border-color: #3498db; }
        .filter-btn:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); }
        .modal-content { background-color: white; margin: 15% auto; padding: 30px; border-radius: 12px; width: 90%; max-width: 500px; box-shadow: 0 8px 32px rgba(0,0,0,0.3); }
        .modal h3 { color: #c53030; margin-bottom: 20px; }
        .modal-buttons { display: flex; gap: 10px; margin-top: 20px; }
        .modal-buttons button { flex: 1; padding: 12px; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; }
        
        @media (max-width: 768px) {
            .header-content { flex-direction: column; gap: 15px; text-align: center; }
            .navigation { flex-direction: column; align-items: center; }
            .form-row { grid-template-columns: 1fr; }
            .stats { grid-template-columns: 1fr; }
            .container { margin: 20px; padding: 20px; }
            .filters { justify-content: center; }
        }
    </style>
</head>
<body>

<div class="header">
    <div class="header-content">
        <div class="logo-section">
            <img src="/publico_html/assets/img/logo.png" alt="Logo Imobiliária">
            <div class="title-section">
                <h1>Financeiro Imobiliária e Aury</h1>
                <p>Controle de Contas a Pagar</p>
            </div>
        </div>
    </div>
</div>

<div class="container">
    
    <div class="navigation">
        <a href="index.php" class="nav-link">Dashboard</a>
        <a href="contas.php" class="nav-link active">Controle de Contas</a>
        <a href="relatorios.php" class="nav-link">Relatórios</a>
    </div>

    <?php
    if (isset($_GET['status'])) {
        if ($_GET['status'] == 'success') echo '<div class="alert alert-success">Conta adicionada com sucesso!</div>';
        elseif ($_GET['status'] == 'paid') echo '<div class="alert alert-success">Conta marcada como paga!</div>';
        elseif ($_GET['status'] == 'deleted') echo '<div class="alert alert-warning">Conta excluída com sucesso!</div>';
        elseif ($_GET['status'] == 'all_deleted') echo '<div class="alert alert-warning">Todas as contas foram excluídas!</div>';
        elseif ($_GET['status'] == 'error') echo '<div class="alert alert-error">Erro ao processar solicitação. Tente novamente.</div>';
    }
    ?>

    <div class="stats">
        <div class="stat-box"><h3>Contas Pendentes</h3><p class="pendente"><?= $stats['pendentes'] ?></p></div>
        <div class="stat-box"><h3>Contas Vencidas</h3><p class="vencida"><?= $stats['vencidas'] ?></p></div>
        <div class="stat-box"><h3>Contas Pagas</h3><p class="paga"><?= $stats['pagas'] ?></p></div>
        <div class="stat-box"><h3>Valor Pendente</h3><p class="pendente">R$ <?= number_format($stats['valor_pendente'], 2, ',', '.') ?></p></div>
    </div>

    <div class="form-container">
        <h2>Nova Conta a Pagar</h2>
        <form method="post">
            <input type="hidden" name="acao" value="adicionar_conta">
            <div class="form-row">
                <div class="form-group">
                    <label for="nome_conta">Nome da Conta*</label>
                    <input type="text" id="nome_conta" name="nome_conta" required>
                </div>
                <div class="form-group">
                    <label for="valor">Valor (R$)*</label>
                    <input type="text" id="valor" name="valor" placeholder="150,50" required>
                </div>
                <div class="form-group">
                    <label for="data_vencimento">Data de Vencimento*</label>
                    <input type="date" id="data_vencimento" name="data_vencimento" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group" style="grid-column: span 2;">
                    <label for="descricao">Descrição</label>
                    <input type="text" id="descricao" name="descricao">
                </div>
                <div class="form-group">
                    <label for="observacoes">Observações</label>
                    <textarea id="observacoes" name="observacoes" rows="3"></textarea>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <button type="submit">Adicionar Conta</button>
                </div>
            </div>
        </form>
    </div>

    <div class="filters">
        <a href="contas.php?filtro=todas" class="filter-btn <?= $filtro == 'todas' ? 'active' : '' ?>">Todas</a>
        <a href="contas.php?filtro=pendentes" class="filter-btn <?= $filtro == 'pendentes' ? 'active' : '' ?>">Pendentes</a>
        <a href="contas.php?filtro=vencendo" class="filter-btn <?= $filtro == 'vencendo' ? 'active' : '' ?>">Vencendo (7 dias)</a>
        <a href="contas.php?filtro=vencidas" class="filter-btn <?= $filtro == 'vencidas' ? 'active' : '' ?>">Vencidas</a>
        <a href="contas.php?filtro=pagas" class="filter-btn <?= $filtro == 'pagas' ? 'active' : '' ?>">Pagas</a>
    </div>

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>Lista de Contas</h3>
        <button onclick="abrirModalLimparTodasContas()" class="btn-small btn-danger">🗑️ Limpar Todas</button>
    </div>
    
    <table>
        <thead>
            <tr><th>Conta</th><th>Descrição</th><th>Valor</th><th>Vencimento</th><th>Status</th><th>Ações</th></tr>
        </thead>
        <tbody>
            <?php while ($conta = $contas->fetch_assoc()): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($conta['nome_conta']) ?></strong></td>
                    <td><?= htmlspecialchars($conta['descricao'] ?? '-') ?></td>
                    <td><strong>R$ <?= number_format($conta['valor'], 2, ',', '.') ?></strong></td>
                    <td><?= date("d/m/Y", strtotime($conta['data_vencimento'])) ?></td>
                    <td>
                        <span class="status-badge status-<?= $conta['status'] ?>">
                            <?= ucfirst($conta['status']) ?>
                        </span>
                    </td>
                    <td>
                        <?php if ($conta['status'] != 'pago'): ?>
                            <button class="btn-small btn-success" onclick="marcarPago(<?= $conta['id'] ?>, '<?= htmlspecialchars($conta['nome_conta']) ?>')">✓ Pagar</button>
                        <?php endif; ?>
                        <button class="btn-small btn-danger" onclick="excluirConta(<?= $conta['id'] ?>, '<?= htmlspecialchars($conta['nome_conta']) ?>')">🗑️</button>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<!-- Modal para marcar como pago -->
<div id="modalPagar" class="modal">
    <div class="modal-content">
        <h3>Marcar como Pago</h3>
        <form method="post">
            <input type="hidden" name="acao" value="marcar_pago">
            <input type="hidden" name="id" id="contaId">
            <div style="margin-bottom:15px;">
                <label style="display:block; margin-bottom:5px; font-weight:600;">Data do Pagamento:</label>
                <input type="date" name="data_pagamento" value="<?= date('Y-m-d') ?>" required style="width:100%; padding:10px; border:2px solid #e9ecef; border-radius:8px;">
            </div>
            <div style="margin-bottom:20px;">
                <label style="display:block; margin-bottom:5px; font-weight:600;">Forma de Pagamento:</label>
                <input type="text" name="forma_pagamento" placeholder="PIX, Cartão, etc." style="width:100%; padding:10px; border:2px solid #e9ecef; border-radius:8px;">
            </div>
            <div class="modal-buttons">
                <button type="button" onclick="fecharModal('modalPagar')" style="background: #6c757d; color: white;">Cancelar</button>
                <button type="submit" style="background: #28a745; color: white;">Confirmar</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal para confirmar exclusão de conta -->
<div id="modalExcluirConta" class="modal">
    <div class="modal-content">
        <h3>⚠️ Confirmar Exclusão</h3>
        <p>Tem certeza que deseja excluir esta conta?</p>
        <p><strong id="nomeContaExcluir"></strong></p>
        <p style="color: #c53030; font-size: 14px;">Esta ação não pode ser desfeita!</p>
        <form method="post" id="formExcluirConta">
            <input type="hidden" name="acao" value="excluir_conta">
            <input type="hidden" name="id" id="idContaExcluir">
            <div class="modal-buttons">
                <button type="button" onclick="fecharModal('modalExcluirConta')" style="background: #6c757d; color: white;">Cancelar</button>
                <button type="submit" style="background: #dc3545; color: white;">Excluir</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal para limpar todas as contas -->
<div id="modalLimparTodasContas" class="modal">
    <div class="modal-content">
        <h3>🚨 ATENÇÃO - AÇÃO IRREVERSÍVEL</h3>
        <p><strong>Você está prestes a excluir TODAS as contas!</strong></p>
        <p>Esta ação irá:</p>
        <ul style="margin: 15px 0; padding-left: 20px; color: #c53030;">
            <li>Deletar todas as contas do banco de dados</li>
            <li>Remover todo o histórico de pagamentos</li>
            <li>Zerar todas as estatísticas</li>
        </ul>
        <p style="color: #c53030; font-weight: bold;">ESTA AÇÃO NÃO PODE SER DESFEITA!</p>
        
        <form method="post" id="formLimparTodasContas">
            <input type="hidden" name="acao" value="limpar_todas_contas">
            
            <div style="margin: 20px 0; padding: 15px; background: #fff3cd; border-radius: 8px;">
                <label style="display: flex; align-items: center; font-weight: bold;">
                    <input type="checkbox" id="confirmarLimpezaContas" name="confirmar_limpeza" value="SIM" required style="margin-right: 10px;">
                    Eu confirmo que quero excluir TODAS as contas
                </label>
            </div>
            
            <div class="modal-buttons">
                <button type="button" onclick="fecharModal('modalLimparTodasContas')" style="background: #6c757d; color: white;">Cancelar</button>
                <button type="submit" style="background: #dc3545; color: white;" id="btnConfirmarLimpezaContas" disabled>Excluir Tudo</button>
            </div>
        </form>
    </div>
</div>

<script>
function marcarPago(id, nome) {
    document.getElementById('contaId').value = id;
    document.getElementById('modalPagar').style.display = 'block';
}

function excluirConta(id, nome) {
    document.getElementById('idContaExcluir').value = id;
    document.getElementById('nomeContaExcluir').textContent = nome;
    document.getElementById('modalExcluirConta').style.display = 'block';
}

function abrirModalLimparTodasContas() {
    document.getElementById('modalLimparTodasContas').style.display = 'block';
}

function fecharModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// Fechar modal clicando fora
window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
    }
}

// Habilitar botão de confirmação apenas quando checkbox marcado
document.getElementById('confirmarLimpezaContas').addEventListener('change', function() {
    document.getElementById('btnConfirmarLimpezaContas').disabled = !this.checked;
});
</script>

</body>
</html>
<?php $conexao->close(); ?>
