<?php
/**
 * Página Financeiro - MontaLoja SaaS
 * Versão Responsiva (Loja e Barbearia)
 */
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 transactions existe
$tableExists = false;
try {
    $checkTable = $pdo->query("SHOW TABLES LIKE 'transactions'");
    $tableExists = $checkTable->rowCount() > 0;
} catch (Exception $e) {
    $tableExists = false;
}

// FILTRO DE PERÍODO
$period = $_GET['period'] ?? 'month';
$dateFrom = $_GET['from'] ?? date('Y-m-01');
$dateTo = $_GET['to'] ?? date('Y-m-t');

if ($period === 'today') {
    $dateFrom = $dateTo = date('Y-m-d');
    $periodLabel = 'Hoje';
} elseif ($period === 'yesterday') {
    $dateFrom = $dateTo = date('Y-m-d', strtotime('-1 day'));
    $periodLabel = 'Ontem';
} elseif ($period === 'week') {
    $dateFrom = date('Y-m-d', strtotime('monday this week'));
    $dateTo = date('Y-m-d');
    $periodLabel = 'Esta Semana';
} elseif ($period === 'month') {
    $dateFrom = date('Y-m-01');
    $dateTo = date('Y-m-t');
    $periodLabel = 'Este Mês';
} elseif ($period === 'last_month') {
    $dateFrom = date('Y-m-01', strtotime('first day of last month'));
    $dateTo = date('Y-m-t', strtotime('last day of last month'));
    $periodLabel = 'Mês Passado';
} elseif ($period === 'year') {
    $dateFrom = date('Y-01-01');
    $dateTo = date('Y-12-31');
    $periodLabel = 'Este Ano';
} elseif ($period === 'custom') {
    $periodLabel = date('d/m', strtotime($dateFrom)) . ' - ' . date('d/m', strtotime($dateTo));
} else {
    $dateFrom = date('Y-m-01');
    $dateTo = date('Y-m-t');
    $periodLabel = 'Este Mês';
}

// Processar ações
$message = '';
$messageType = '';
$transactions = [];
$income = 0;
$expense = 0;
$balance = 0;
$byCategory = [];

if ($tableExists) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';
        
        try {
            if ($action === 'add') {
                $type = $_POST['type'] ?? 'income';
                $amount = floatval($_POST['amount'] ?? 0);
                $category = trim($_POST['category'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $date = $_POST['date'] ?? date('Y-m-d');
                $paymentMethod = $_POST['payment_method'] ?? '';
                
                if ($amount > 0 && $category) {
                    $stmt = $pdo->prepare("INSERT INTO transactions (store_id, type, amount, category, description, payment_method, transaction_date, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
                    $stmt->execute([$storeId, $type, $amount, $category, $description, $paymentMethod, $date]);
                    $message = ($type === 'income' ? 'Receita' : 'Despesa') . ' registrada com sucesso!';
                    $messageType = 'success';
                }
            } elseif ($action === 'delete' && isset($_POST['id'])) {
                $stmt = $pdo->prepare("DELETE FROM transactions WHERE id = ? AND store_id = ?");
                $stmt->execute([$_POST['id'], $storeId]);
                $message = 'Transação removida!';
                $messageType = 'success';
            }
        } catch (Exception $e) {
            $message = 'Erro ao processar: ' . $e->getMessage();
            $messageType = 'error';
        }
    }

    // Buscar transações manuais
    try {
        $sql = "SELECT *, 'manual' as source FROM transactions WHERE store_id = ? AND transaction_date BETWEEN ? AND ? ORDER BY transaction_date DESC, id DESC";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$storeId, $dateFrom, $dateTo]);
        $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Buscar pedidos da loja online como receitas
        $ordersSql = "SELECT 
            id,
            store_id,
            'income' as type,
            total_amount as amount,
            'Vendas Online' as category,
            CONCAT('Pedido #', id) as description,
            payment_method,
            DATE(created_at) as transaction_date,
            created_at,
            NULL as updated_at,
            'online' as source
        FROM orders 
        WHERE store_id = ? 
        AND DATE(created_at) BETWEEN ? AND ?
        AND status IN ('completed', 'delivered', 'paid')
        ORDER BY created_at DESC";
        $ordersStmt = $pdo->prepare($ordersSql);
        $ordersStmt->execute([$storeId, $dateFrom, $dateTo]);
        $onlineOrders = $ordersStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Mesclar transações manuais com pedidos online
        $transactions = array_merge($transactions, $onlineOrders);
        
        // Ordenar por data decrescente
        usort($transactions, function($a, $b) {
            return strtotime($b['transaction_date']) - strtotime($a['transaction_date']);
        });

        // Calcular totais
        $income = array_sum(array_map(fn($t) => $t['type'] === 'income' ? $t['amount'] : 0, $transactions));
        $expense = array_sum(array_map(fn($t) => $t['type'] === 'expense' ? $t['amount'] : 0, $transactions));
        $balance = $income - $expense;

        // Agrupar por categoria
        foreach ($transactions as $t) {
            $cat = $t['category'] ?: 'Outros';
            if (!isset($byCategory[$cat])) {
                $byCategory[$cat] = ['income' => 0, 'expense' => 0];
            }
            $byCategory[$cat][$t['type']] += $t['amount'];
        }
    } catch (Exception $e) {
        $transactions = [];
    }
}

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

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


<style>
.transaction-type {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.35rem 0.75rem;
    border-radius: 999px;
    font-size: 0.8rem;
    font-weight: 600;
}

.transaction-type.income {
    background: rgba(34, 197, 94, 0.1);
    color: #22C55E;
}

.transaction-type.expense {
    background: rgba(239, 68, 68, 0.1);
    color: #EF4444;
}

.source-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.25rem 0.5rem;
    border-radius: 999px;
    font-size: 0.75rem;
    font-weight: 500;
}

.source-badge.online {
    background: rgba(99, 102, 241, 0.1);
    color: #6366F1;
}

.source-badge.manual {
    background: rgba(156, 163, 175, 0.1);
    color: #6B7280;
}

.amount-income {
    color: #22C55E;
    font-weight: 700;
}

.amount-expense {
    color: #EF4444;
    font-weight: 700;
}

/* FILTRO - DESIGN RESPONSIVO */
.filter-section{border-radius:var(--radius-lg);padding:1rem;margin-bottom:1.5rem;overflow:hidden}
.filter-header{display:flex;align-items:center;justify-content:space-between;gap:.5rem}
.filter-title{display:flex;align-items:center;gap:.5rem;font-size:.85rem;font-weight:600;color:var(--text-secondary);margin:0}
.filter-title iconify-icon{font-size:1rem;color:var(--primary)}
.filter-period-badge{display:none;align-items:center;gap:.25rem;padding:.25rem .6rem;background:var(--primary);border-radius:50px;font-size:.7rem;font-weight:600;color:#000}
.filter-toggle-btn{display:none;align-items:center;justify-content:center;width:32px;height:32px;background:var(--bg-dark);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--text-secondary);cursor:pointer}
.filter-toggle-btn:hover,.filter-toggle-btn.active{border-color:var(--primary);color:var(--primary)}
.filter-toggle-btn iconify-icon{font-size:1rem}
.filter-body{display:flex;align-items:center;gap:1rem;margin-top:.75rem}
.filter-scroll{flex:1;overflow:hidden}
.filter-pills{display:flex;gap:.5rem;flex-wrap:wrap}
.filter-pill{display:inline-flex;align-items:center;gap:.3rem;padding:.45rem .9rem;background:var(--bg-card);border:1px solid var(--border);border-radius:50px;font-size:.8rem;font-weight:500;color:var(--text-secondary);cursor:pointer;transition:all .2s;text-decoration:none;white-space:nowrap}
.filter-pill:hover{border-color:var(--primary);color:var(--primary)}
.filter-pill.active{background:linear-gradient(135deg, var(--primary) 0%, #FFD700 100%);border-color:var(--primary);color:#000}
.filter-pill iconify-icon{font-size:.9rem}
.filter-sep{width:1px;height:28px;background:var(--border);flex-shrink:0}
.filter-dates{display:flex;align-items:center;gap:.5rem;flex-shrink:0}
.filter-dates input[type=date]{padding:.4rem .5rem;background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--text-primary);font-size:.8rem;width:130px}
.filter-dates input[type=date]:focus{outline:none;border-color:var(--primary)}
.filter-dates .sep{color:var(--text-muted);font-size:.75rem}
.filter-dates .btn-apply{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;background:var(--primary);border:none;border-radius:var(--radius-md);color:#000;cursor:pointer}
.filter-dates .btn-apply:hover{transform:scale(1.05)}

/* TABLET */
@media(max-width:992px){
.filter-body{flex-direction:column;align-items:stretch;gap:.75rem}
.filter-scroll{width:100%}
.filter-pills{flex-wrap:wrap;justify-content:flex-start}
.filter-sep{display:none}
.filter-dates{width:100%;justify-content:space-between;padding-top:.5rem;border-top:1px solid var(--border)}
.filter-dates input[type=date]{flex:1;width:auto}
}

/* MOBILE */
@media(max-width:768px){
.filter-period-badge{display:inline-flex;align-items:center;gap:.25rem;padding:.25rem .6rem;background:var(--primary);border-radius:50px;font-size:.7rem;font-weight:600;color:#000}
.filter-section{padding:.75rem}
.filter-header{margin-bottom:0}
.filter-toggle-btn{display:flex}
.filter-body{display:none;margin-top:.75rem;padding-top:.75rem;border-top:1px solid var(--border)}
.filter-body.show{display:flex}
.filter-pills{gap:.3rem}
.filter-pill{padding:.35rem .6rem;font-size:.75rem}
.filter-pill iconify-icon{font-size:.8rem}
.filter-dates{gap:.3rem}
.filter-dates input[type=date]{padding:.35rem .4rem;font-size:.75rem}
.filter-dates .btn-apply{width:28px;height:28px}
}

/* MOBILE SMALL */
@media(max-width:480px){
.filter-section{padding:.6rem}
.filter-pill{padding:.3rem .5rem;font-size:.7rem}
.filter-pill iconify-icon{display:none}
.filter-period-badge{font-size:.65rem;padding:.2rem .45rem}
.filter-dates input[type=date]{font-size:.7rem;padding:.3rem}
}

.balance-card {
    /* herda do stat-card */
}

.balance-card.positive {
    background: linear-gradient(135deg, rgba(34, 197, 94, 0.1), rgba(34, 197, 94, 0.05));
    border: 1px solid rgba(34, 197, 94, 0.2);
}

.balance-card.negative {
    background: linear-gradient(135deg, rgba(239, 68, 68, 0.1), rgba(239, 68, 68, 0.05));
    border: 1px solid rgba(239, 68, 68, 0.2);
}



/* Fix icon overflow in buttons */
.btn { overflow: hidden; }
.btn iconify-icon { font-size: 1.85rem; flex-shrink: 0; display: contents; }
</style>

    <main class="main-content">
        <div class="page-header page-header-flex">
            <div>
                <h1><iconify-icon icon="solar:wallet-money-bold"></iconify-icon> Financeiro</h1>
                <p>Controle de receitas e despesas</p>
            </div>
            <div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
                <button class="btn btn-secondary" onclick="openModal('income')">
                    <iconify-icon icon="solar:arrow-up-bold"></iconify-icon>
                    <span class="hide-mobile">Receita</span>
                </button>
                <button class="btn btn-secondary" onclick="openModal('expense')">
                    <iconify-icon icon="solar:arrow-down-bold"></iconify-icon>
                    <span class="hide-mobile">Despesa</span>
                </button>
            </div>
        </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; ?>
        
        <!-- FILTRO DE PERÍODO - RESPONSIVO -->
        <div class="filter-section">
            <div class="filter-header">
                <div style="display:flex;align-items:center;gap:.75rem;flex-wrap:wrap">
                    <h3 class="filter-title">
                        <iconify-icon icon="solar:calendar-search-bold"></iconify-icon>
                        Período
                    </h3>
                    <span class="filter-period-badge">
                        <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                        <?php echo $periodLabel; ?>
                    </span>
                </div>
                <button type="button" class="filter-toggle-btn" onclick="toggleFilter()" id="filterToggle">
                    <iconify-icon icon="solar:alt-arrow-down-bold"></iconify-icon>
                </button>
            </div>
            <div class="filter-body" id="filterBody">
                <div class="filter-scroll">
                    <div class="filter-pills">
                        <a href="?period=today" class="filter-pill <?php echo $period === 'today' ? 'active' : ''; ?>">
                            <iconify-icon icon="solar:calendar-minimalistic-bold"></iconify-icon> Hoje
                        </a>
                        <a href="?period=yesterday" class="filter-pill <?php echo $period === 'yesterday' ? 'active' : ''; ?>">
                            <iconify-icon icon="solar:calendar-bold"></iconify-icon> Ontem
                        </a>
                        <a href="?period=week" class="filter-pill <?php echo $period === 'week' ? 'active' : ''; ?>">
                            <iconify-icon icon="solar:calendar-mark-bold"></iconify-icon> Semana
                        </a>
                        <a href="?period=month" class="filter-pill <?php echo $period === 'month' ? 'active' : ''; ?>">
                            <iconify-icon icon="solar:calendar-date-bold"></iconify-icon> Mês
                        </a>
                        <a href="?period=last_month" class="filter-pill <?php echo $period === 'last_month' ? 'active' : ''; ?>">
                            <iconify-icon icon="solar:history-bold"></iconify-icon> Mês Passado
                        </a>
                        <a href="?period=year" class="filter-pill <?php echo $period === 'year' ? 'active' : ''; ?>">
                            <iconify-icon icon="solar:calendar-search-bold"></iconify-icon> Ano
                        </a>
                    </div>
                </div>
                <div class="filter-sep"></div>
                <form method="GET" class="filter-dates">
                    <input type="hidden" name="period" value="custom">
                    <input type="date" name="from" value="<?php echo $dateFrom; ?>" title="Data inicial">
                    <span class="sep">até</span>
                    <input type="date" name="to" value="<?php echo $dateTo; ?>" title="Data final">
                    <button type="submit" class="btn-apply" title="Aplicar período personalizado">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    </button>
                </form>
            </div>
        </div>

        <script>
        function toggleFilter() {
            const body = document.getElementById('filterBody');
            const btn = document.getElementById('filterToggle');
            body.classList.toggle('show');
            btn.classList.toggle('active');
            const icon = btn.querySelector('iconify-icon');
            icon.setAttribute('icon', body.classList.contains('show') ? 'solar:alt-arrow-up-bold' : 'solar:alt-arrow-down-bold');
        }
        // Auto-show on desktop
        if (window.innerWidth > 768) {
            document.getElementById('filterBody').classList.add('show');
        }
        </script>

        
        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(34, 197, 94, 0.1); color: #22C55E;">
                    <iconify-icon icon="solar:arrow-up-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value" style="color: #22C55E;">R$ <?php echo number_format($income, 2, ',', '.'); ?></span>
                    <span class="stat-label">Receitas</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:arrow-down-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value" style="color: #EF4444;">R$ <?php echo number_format($expense, 2, ',', '.'); ?></span>
                    <span class="stat-label">Despesas</span>
                </div>
            </div>
            <div class="stat-card balance-card <?php echo $balance >= 0 ? 'positive' : 'negative'; ?>">
                <div class="stat-icon" style="background: rgba(<?php echo $balance >= 0 ? '34, 197, 94' : '239, 68, 68'; ?>, 0.1); color: <?php echo $balance >= 0 ? '#22C55E' : '#EF4444'; ?>;"><iconify-icon icon="solar:chart-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value" style="color: <?php echo $balance >= 0 ? '#22C55E' : '#EF4444'; ?>;">
                        <?php echo $balance >= 0 ? '+' : ''; ?>R$ <?php echo number_format($balance, 2, ',', '.'); ?>
                    </span>
                    <span class="stat-label">Saldo do Período</span>
                </div>
            </div>
        </div>
        
        <?php if (empty($transactions)): ?>
        <div class="empty-state">
            <iconify-icon icon="solar:wallet-money-bold"></iconify-icon>
            <h3>Nenhuma transação encontrada</h3>
            <p>Não há transações registradas neste período.</p>
            <div style="display: flex; gap: 1rem; justify-content: center; margin-top: 1rem; flex-wrap: wrap;">
                <button class="btn btn-primary" onclick="openModal('income')">
                    <iconify-icon icon="solar:arrow-up-bold"></iconify-icon>
                    Registrar Receita
                </button>
                <button class="btn btn-secondary" onclick="openModal('expense')">
                    <iconify-icon icon="solar:arrow-down-bold"></iconify-icon>
                    Registrar Despesa
                </button>
            </div>
        </div>
        <?php else: ?>
        
        <!-- Versão Cards (Mobile) -->
        <div class="mobile-cards">
            <?php foreach ($transactions as $t): ?>
            <div class="mobile-card">
                <div class="mobile-card-header">
                    <div style="flex: 1;">
                        <div class="mobile-card-title">
                            <?php echo htmlspecialchars($t['category']); ?>
                            <?php if (isset($t['source']) && $t['source'] === 'online'): ?>
                            <iconify-icon icon="solar:shop-bold" style="color: #6366F1; margin-left: 0.25rem;" title="Venda da Loja Online"></iconify-icon>
                            <?php endif; ?>
                        </div>
                        <div class="mobile-card-subtitle">
                            <?php echo date('d/m/Y', strtotime($t['transaction_date'])); ?>
                            <?php if ($t['description']): ?>
                            • <?php echo htmlspecialchars($t['description']); ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    <span class="<?php echo $t['type'] === 'income' ? 'amount-income' : 'amount-expense'; ?>" style="font-size: 1.1rem;">
                        <?php echo $t['type'] === 'income' ? '+' : '-'; ?>R$ <?php echo number_format($t['amount'], 2, ',', '.'); ?>
                    </span>
                </div>
                
                <div class="mobile-card-info">
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Tipo</div>
                        <span class="transaction-type <?php echo $t['type']; ?>">
                            <?php echo $t['type'] === 'income' ? 'Receita' : 'Despesa'; ?>
                        </span>
                    </div>
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Origem</div>
                        <?php if (isset($t['source']) && $t['source'] === 'online'): ?>
                        <span class="source-badge online">
                            <iconify-icon icon="solar:shop-bold"></iconify-icon>
                            Loja Online
                        </span>
                        <?php else: ?>
                        <span class="source-badge manual">
                            <iconify-icon icon="solar:pen-bold"></iconify-icon>
                            Manual
                        </span>
                        <?php endif; ?>
                    </div>
                    <?php if ($t['payment_method']): ?>
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Pagamento</div>
                        <div class="mobile-card-info-value">
                            <?php
                            $paymentLabels = [
                                'money' => 'Dinheiro',
                                'pix' => 'PIX',
                                'credit_card' => 'Cartão Crédito',
                                'debit_card' => 'Cartão Débito',
                                'transfer' => 'Transferência',
                                'whatsapp' => 'WhatsApp'
                            ];
                            echo $paymentLabels[$t['payment_method']] ?? $t['payment_method'];
                            ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <?php if (!isset($t['source']) || $t['source'] !== 'online'): ?>
                <div class="mobile-card-actions">
                    <form method="POST" onsubmit="return confirm('Remover esta transação?');" style="flex: 1;">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?php echo $t['id']; ?>">
                        <button type="submit" class="btn btn-secondary btn-sm" style="width: 100%; color: var(--error);">
                            <iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>
                            Remover
                        </button>
                    </form>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Versão Tabela (Desktop) -->
        <div class="card desktop-table">
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Data</th>
                            <th>Tipo</th>
                            <th>Origem</th>
                            <th>Categoria</th>
                            <th>Descrição</th>
                            <th>Pagamento</th>
                            <th>Valor</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($transactions as $t): ?>
                        <tr>
                            <td><?php echo date('d/m/Y', strtotime($t['transaction_date'])); ?></td>
                            <td>
                                <span class="transaction-type <?php echo $t['type']; ?>">
                                    <?php echo $t['type'] === 'income' ? 'Receita' : 'Despesa'; ?>
                                </span>
                            </td>
                            <td>
                                <?php if (isset($t['source']) && $t['source'] === 'online'): ?>
                                <span class="source-badge online">
                                    <iconify-icon icon="solar:shop-bold"></iconify-icon>
                                    Loja Online
                                </span>
                                <?php else: ?>
                                <span class="source-badge manual">
                                    <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                    Manual
                                </span>
                                <?php endif; ?>
                            </td>
                            <td style="font-weight: 600;"><?php echo htmlspecialchars($t['category']); ?></td>
                            <td><?php echo htmlspecialchars($t['description'] ?: '-'); ?></td>
                            <td>
                                <?php
                                $paymentLabels = [
                                    'money' => 'Dinheiro',
                                    'pix' => 'PIX',
                                    'credit_card' => 'Cartão Crédito',
                                    'debit_card' => 'Cartão Débito',
                                    'transfer' => 'Transferência',
                                'whatsapp' => 'WhatsApp'
                                ];
                                echo $paymentLabels[$t['payment_method'] ?? ''] ?? '-';
                                ?>
                            </td>
                            <td class="<?php echo $t['type'] === 'income' ? 'amount-income' : 'amount-expense'; ?>">
                                <?php echo $t['type'] === 'income' ? '+' : '-'; ?>R$ <?php echo number_format($t['amount'], 2, ',', '.'); ?>
                            </td>
                            <td>
                                <?php if (!isset($t['source']) || $t['source'] !== 'online'): ?>
                                <form method="POST" style="display: inline;" onsubmit="return confirm('Remover esta transação?');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?php echo $t['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>
                                <?php else: ?>
                                <span style="color: var(--text-muted); font-size: 0.8rem;">Auto</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </main>
    
    <!-- Modal Nova Transação -->
    <div id="transactionModal" 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;">Nova Transação</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="add">
                <input type="hidden" name="type" id="transactionType" value="income">
                
                <div class="form-grid-2">
                    <div class="form-group">
                        <label class="form-label">Valor (R$) *</label>
                        <input type="number" name="amount" class="form-input" placeholder="0.00" step="0.01" min="0.01" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Data</label>
                        <input type="date" name="date" class="form-input" value="<?php echo date('Y-m-d'); ?>">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Categoria *</label>
                    <select name="category" class="form-input" id="categorySelect" required>
                        <option value="">Selecione</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Forma de Pagamento</label>
                    <select name="payment_method" class="form-input">
                        <option value="">Selecione</option>
                        <option value="money">Dinheiro</option>
                        <option value="pix">PIX</option>
                        <option value="credit_card">Cartão de Crédito</option>
                        <option value="debit_card">Cartão de Débito</option>
                        <option value="transfer">Transferência</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Descrição</label>
                    <input type="text" name="description" class="form-input" placeholder="Descrição opcional">
                </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" id="submitBtn">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        Registrar
                    </button>
                </div>
            </form>
        </div>
    </div>

<script>
const incomeCategories = ['Vendas', 'Serviços', 'Comissões', 'Outros'];
const expenseCategories = ['Aluguel', 'Salários', 'Fornecedores', 'Energia', 'Água', 'Internet', 'Marketing', 'Manutenção', 'Impostos', 'Outros'];

function openModal(type) {
    document.getElementById('transactionType').value = type;
    document.getElementById('modalTitle').textContent = type === 'income' ? 'Nova Receita' : 'Nova Despesa';
    document.getElementById('submitBtn').style.background = type === 'income' ? '#22C55E' : '#EF4444';
    
    const select = document.getElementById('categorySelect');
    select.innerHTML = '<option value="">Selecione</option>';
    const categories = type === 'income' ? incomeCategories : expenseCategories;
    categories.forEach(cat => {
        select.innerHTML += `<option value="${cat}">${cat}</option>`;
    });
    
    document.getElementById('transactionModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

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

document.getElementById('transactionModal').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'; ?>
