<?php
ini_set('display_errors', 0);
require '../../config/db.php';
require '../../app/Controllers/sessions.php';
require '../../app/Controllers/security_admin.php';
require '../../app/Controllers/adminInfos.php';
require 'with.php';

// Processar ações via POST
$action = $_POST['action'] ?? $_GET['action'] ?? '';

// Processar exclusão de investimento
if ($action === 'delete_investment' && isset($_POST['investment_id'])) {
    $investmentId = intval($_POST['investment_id']);
    try {
        // Buscar dados do investimento
        $stmt = $pdo->prepare("SELECT * FROM investments WHERE id = :id");
        $stmt->execute([':id' => $investmentId]);
        $investment = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($investment) {
            // Reembolsar o valor investido ao usuário
            $stmt = $pdo->prepare("UPDATE users SET balance = balance + :amount WHERE id = :user_id");
            $stmt->execute([
                ':amount' => $investment['invested_amount'],
                ':user_id' => $investment['user_id']
            ]);
            
            // Excluir o investimento
            $stmt = $pdo->prepare("DELETE FROM investments WHERE id = :id");
            $stmt->execute([':id' => $investmentId]);
            
            $_SESSION['toast_message'] = 'Investimento excluído e valor reembolsado com sucesso!';
            $_SESSION['toast_type'] = 'success';
        }
    } catch (PDOException $e) {
        $_SESSION['toast_message'] = 'Erro ao excluir investimento: ' . $e->getMessage();
        $_SESSION['toast_type'] = 'error';
    }
    header('Location: admin.php?page=investments');
    exit;
}

// Processar adição manual de investimento
if ($action === 'add_investment' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = intval($_POST['user_id']);
    $productId = intval($_POST['product_id']);
    $investedAmount = floatval($_POST['invested_amount']);
    
    try {
        // Buscar dados do produto
        $stmt = $pdo->prepare("SELECT * FROM investment_products WHERE id = :id");
        $stmt->execute([':id' => $productId]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($product) {
            $totalReturn = ($investedAmount * $product['total_return']) / 100;
            $durationDays = $product['total_days'];
            $type = $product['type'];
            
            // Criar investimento
            $stmt = $pdo->prepare("INSERT INTO investments (name, img, user_id, product_id, invested_amount, total_return, duration_days, type, created_at, is_active) VALUES (:name, :img, :user_id, :product_id, :invested_amount, :total_return, :duration_days, :type, NOW(), 1)");
            $stmt->execute([
                ':name' => $product['name'],
                ':img' => $product['img'],
                ':user_id' => $userId,
                ':product_id' => $productId,
                ':invested_amount' => $investedAmount,
                ':total_return' => $totalReturn,
                ':duration_days' => $durationDays,
                ':type' => $type
            ]);
            
            $_SESSION['toast_message'] = 'Investimento adicionado com sucesso!';
            $_SESSION['toast_type'] = 'success';
        }
    } catch (PDOException $e) {
        $_SESSION['toast_message'] = 'Erro ao adicionar investimento: ' . $e->getMessage();
        $_SESSION['toast_type'] = 'error';
    }
    header('Location: admin.php?page=investments');
    exit;
}

// Processar atualização de saldo do usuário
if ($action === 'update_balance' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = intval($_POST['user_id']);
    $newBalance = floatval($_POST['balance']);
    
    try {
        $stmt = $pdo->prepare("UPDATE users SET balance = :balance WHERE id = :id");
        $stmt->execute([
            ':balance' => $newBalance,
            ':id' => $userId
        ]);
        
        $_SESSION['toast_message'] = 'Saldo atualizado com sucesso!';
        $_SESSION['toast_type'] = 'success';
    } catch (PDOException $e) {
        $_SESSION['toast_message'] = 'Erro ao atualizar saldo: ' . $e->getMessage();
        $_SESSION['toast_type'] = 'error';
    }
    header('Location: admin.php?page=users');
    exit;
}

// Processar exclusão de usuário
if ($action === 'delete_user' && isset($_POST['user_id'])) {
    $userId = intval($_POST['user_id']);
    try {
        // Excluir investimentos do usuário
        $stmt = $pdo->prepare("DELETE FROM investments WHERE user_id = :id");
        $stmt->execute([':id' => $userId]);
        
        // Excluir usuário
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
        $stmt->execute([':id' => $userId]);
        
        $_SESSION['toast_message'] = 'Usuário excluído com sucesso!';
        $_SESSION['toast_type'] = 'success';
    } catch (PDOException $e) {
        $_SESSION['toast_message'] = 'Erro ao excluir usuário: ' . $e->getMessage();
        $_SESSION['toast_type'] = 'error';
    }
    header('Location: admin.php?page=users');
    exit;
}

// Processar exclusão de produto
if ($action === 'delete_product' && isset($_POST['product_id'])) {
    $productId = intval($_POST['product_id']);
    try {
        $stmt = $pdo->prepare("DELETE FROM investment_products WHERE id = :id");
        $stmt->execute([':id' => $productId]);
        
        $_SESSION['toast_message'] = 'Produto excluído com sucesso!';
        $_SESSION['toast_type'] = 'success';
    } catch (PDOException $e) {
        $_SESSION['toast_message'] = 'Erro ao excluir produto: ' . $e->getMessage();
        $_SESSION['toast_type'] = 'error';
    }
    header('Location: admin.php?page=products');
    exit;
}

// Buscar usuário (AJAX)
if ($action === 'search_user' && isset($_GET['q'])) {
    $query = '%' . $_GET['q'] . '%';
    $stmt = $pdo->prepare("SELECT id, name, phone FROM users WHERE name LIKE :q OR phone LIKE :q OR CAST(id AS CHAR) LIKE :q LIMIT 10");
    $stmt->execute([':q' => $query]);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    header('Content-Type: application/json');
    echo json_encode($users);
    exit;
}

// Processar recusa de saque
if ($action === 'recuse_withdrawal' && isset($_POST['withdrawal_id'])) {
    $withdrawalId = intval($_POST['withdrawal_id']);
    try {
        // Buscar dados do saque
        $stmt = $pdo->prepare("SELECT * FROM withdrawal WHERE id = :id");
        $stmt->execute([':id' => $withdrawalId]);
        $withdrawal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($withdrawal && $withdrawal['status'] === 'pending') {
            // Reembolsar o valor ao usuário
            $stmt = $pdo->prepare("UPDATE users SET balance = balance + :amount WHERE id = :user_id");
            $stmt->execute([
                ':amount' => $withdrawal['value'],
                ':user_id' => $withdrawal['user_id']
            ]);
            
            // Atualizar status do saque
            $stmt = $pdo->prepare("UPDATE withdrawal SET status = 'recused' WHERE id = :id");
            $stmt->execute([':id' => $withdrawalId]);
            
            $_SESSION['toast_message'] = 'Saque recusado e valor reembolsado com sucesso!';
            $_SESSION['toast_type'] = 'success';
        }
    } catch (PDOException $e) {
        $_SESSION['toast_message'] = 'Erro ao recusar saque: ' . $e->getMessage();
        $_SESSION['toast_type'] = 'error';
    }
    header('Location: admin.php?page=withdrawals&status=pending');
    exit;
}

$toastMessage = $_SESSION['toast_message'] ?? null;
$toastType = $_SESSION['toast_type'] ?? null;
unset($_SESSION['toast_message'], $_SESSION['toast_type']);

$currentPage = $_GET['page'] ?? 'dashboard';

// Buscar dados para o dashboard
$totalUsers = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$totalProducts = $pdo->query("SELECT COUNT(*) FROM investment_products")->fetchColumn();
$totalInvestments = $pdo->query("SELECT COUNT(*) FROM investments WHERE is_active = 1")->fetchColumn();
$totalPendingWithdrawals = $pdo->query("SELECT COUNT(*) FROM withdrawal WHERE status = 'pending'")->fetchColumn();
$totalBalance = $pdo->query("SELECT SUM(balance) FROM users")->fetchColumn() ?? 0;
$totalInvested = $pdo->query("SELECT SUM(invested_amount) FROM investments WHERE is_active = 1")->fetchColumn() ?? 0;

// Buscar investimentos recentes
$recentInvestments = $pdo->query("SELECT i.*, u.name as user_name, u.phone as user_phone FROM investments i JOIN users u ON i.user_id = u.id ORDER BY i.created_at DESC LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);

// Buscar saques pendentes
$pendingWithdrawals = $pdo->query("SELECT w.*, u.name as user_name FROM withdrawal w JOIN users u ON w.user_id = u.id WHERE w.status = 'pending' ORDER BY w.created_at DESC LIMIT 10")->fetchAll(PDO::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>Painel Admin - Mobile KTV</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        @keyframes slideIn {
            from { transform: translateX(-100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        .slide-in { animation: slideIn 0.3s ease-out; }
        .sidebar { transition: transform 0.3s ease; }
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); }
            .sidebar.open { transform: translateX(0); }
        }
    </style>
</head>
<body class="bg-gray-100">
    <?php if ($toastMessage): ?>
        <div id="toast" class="fixed top-4 right-4 z-50 px-6 py-4 rounded-lg shadow-lg flex items-center gap-3 <?= $toastType === 'success' ? 'bg-green-500' : 'bg-red-500' ?> text-white slide-in">
            <i data-lucide="<?= $toastType === 'success' ? 'check-circle' : 'x-circle' ?>"></i>
            <span><?= htmlspecialchars($toastMessage) ?></span>
        </div>
        <script>
            setTimeout(() => document.getElementById('toast')?.remove(), 5000);
        </script>
    <?php endif; ?>

    <div class="flex h-screen overflow-hidden">
        <!-- Sidebar -->
        <aside class="sidebar bg-gradient-to-b from-indigo-900 via-purple-900 to-pink-900 text-white w-64 flex-shrink-0 overflow-y-auto">
            <div class="p-6">
                <h1 class="text-2xl font-bold mb-8 flex items-center gap-2">
                    <i data-lucide="shield"></i>
                    <span>Admin Panel</span>
                </h1>
                <nav class="space-y-2">
                    <a href="?page=dashboard" class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-white/10 transition <?= $currentPage === 'dashboard' ? 'bg-white/20' : '' ?>">
                        <i data-lucide="layout-dashboard"></i>
                        <span>Dashboard</span>
                    </a>
                    <a href="?page=users" class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-white/10 transition <?= $currentPage === 'users' ? 'bg-white/20' : '' ?>">
                        <i data-lucide="users"></i>
                        <span>Usuários</span>
                    </a>
                    <a href="?page=products" class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-white/10 transition <?= $currentPage === 'products' ? 'bg-white/20' : '' ?>">
                        <i data-lucide="package"></i>
                        <span>Produtos</span>
                    </a>
                    <a href="?page=investments" class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-white/10 transition <?= $currentPage === 'investments' ? 'bg-white/20' : '' ?>">
                        <i data-lucide="trending-up"></i>
                        <span>Investimentos</span>
                    </a>
                    <a href="?page=withdrawals" class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-white/10 transition <?= $currentPage === 'withdrawals' ? 'bg-white/20' : '' ?>">
                        <i data-lucide="dollar-sign"></i>
                        <span>Saques</span>
                        <?php if ($totalPendingWithdrawals > 0): ?>
                            <span class="ml-auto bg-red-500 text-white text-xs px-2 py-1 rounded-full"><?= $totalPendingWithdrawals ?></span>
                        <?php endif; ?>
                    </a>
                    <a href="?page=coupons" class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-white/10 transition <?= $currentPage === 'coupons' ? 'bg-white/20' : '' ?>">
                        <i data-lucide="ticket"></i>
                        <span>Cupons</span>
                    </a>
                    <a href="?page=settings" class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-white/10 transition <?= $currentPage === 'settings' ? 'bg-white/20' : '' ?>">
                        <i data-lucide="settings"></i>
                        <span>Configurações</span>
                    </a>
                    <a href="../logout.php" class="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-red-500/20 transition text-red-300">
                        <i data-lucide="log-out"></i>
                        <span>Sair</span>
                    </a>
                </nav>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="flex-1 overflow-y-auto">
            <!-- Header -->
            <header class="bg-white shadow-sm border-b border-gray-200 px-6 py-4">
                <div class="flex items-center justify-between">
                    <div>
                        <h2 class="text-2xl font-bold text-gray-800">
                            <?php
                            $titles = [
                                'dashboard' => 'Dashboard',
                                'users' => 'Usuários',
                                'products' => 'Produtos',
                                'investments' => 'Investimentos',
                                'withdrawals' => 'Saques',
                                'coupons' => 'Cupons',
                                'settings' => 'Configurações'
                            ];
                            echo $titles[$currentPage] ?? 'Dashboard';
                            ?>
                        </h2>
                        <p class="text-gray-500 text-sm">Bem-vindo, <?= htmlspecialchars($adminUser ?? 'Admin') ?></p>
                    </div>
                    <button id="sidebarToggle" class="lg:hidden p-2 rounded-lg hover:bg-gray-100">
                        <i data-lucide="menu"></i>
                    </button>
                </div>
            </header>

            <!-- Page Content -->
            <div class="p-6">
                <?php if ($currentPage === 'dashboard'): ?>
                    <?php include 'pages/dashboard.php'; ?>
                <?php elseif ($currentPage === 'users'): ?>
                    <?php include 'pages/users.php'; ?>
                <?php elseif ($currentPage === 'products'): ?>
                    <?php include 'pages/products.php'; ?>
                <?php elseif ($currentPage === 'investments'): ?>
                    <?php include 'pages/investments.php'; ?>
                <?php elseif ($currentPage === 'withdrawals'): ?>
                    <?php include 'pages/withdrawals.php'; ?>
                <?php elseif ($currentPage === 'coupons'): ?>
                    <?php include 'pages/coupons.php'; ?>
                <?php elseif ($currentPage === 'settings'): ?>
                    <?php include 'pages/settings.php'; ?>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <script>
        lucide.createIcons();
        
        // Sidebar toggle
        document.getElementById('sidebarToggle')?.addEventListener('click', () => {
            document.querySelector('.sidebar').classList.toggle('open');
        });
        
        // Auto-hide toast
        setTimeout(() => {
            document.getElementById('toast')?.remove();
        }, 5000);
    </script>
</body>
</html>
