<?php
require_once '../../config/db.php';
require_once '../../app/Controllers/sessions.php';
ini_set('display_errors', 0);

$adminUser = $_SESSION['admin_session'];
session_start();
if (!isset($_SESSION['admin_session']) || !isset($_SESSION['user'])) {
    header('Location: ../login.php');
    exit;
}

// Consultando Total de faturamento
$stmtTransactions = $pdo->prepare("SELECT SUM(value) AS total_paids FROM transactions WHERE status = 'paid'");
$stmtTransactions->execute();
$resultTransactionsPaid = $stmtTransactions->fetch(PDO::FETCH_ASSOC);
$faturament = $resultTransactionsPaid['total_paids'];

// Gerar dados dos últimos 7 dias (grafico)
$labels = [];
$values = [];

// Buscar últimos 10 registros do histórico
$stmtHistory = $pdo->query("SELECT * FROM history ORDER BY created_at DESC LIMIT 10");
$history = $stmtHistory->fetchAll(PDO::FETCH_ASSOC);

for ($i = 6; $i >= 0; $i--) {
    $data = date('Y-m-d', strtotime("-$i days"));
    $labels[] = date('d/m', strtotime($data));

    $stmt = $pdo->prepare("SELECT SUM(value) as total FROM transactions WHERE status = 'paid' AND DATE(created_at) = :data");
    $stmt->execute([':data' => $data]);
    $total = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    $values[] = floatval($total);
}

// Transforma arrays em JSON
$jsonLabels = json_encode($labels);
$jsonValues = json_encode($values);


// Consultando Total de transacoes pendentes
$stmtTransactionsPending = $pdo->prepare("SELECT SUM(value) AS total_awaiting FROM transactions WHERE status = 'awaiting'");
$stmtTransactionsPending->execute();
$resultTransactionsPending = $stmtTransactionsPending->fetch(PDO::FETCH_ASSOC);
$transactionsPending = $resultTransactionsPending['total_awaiting'];

// Consultando detalhes dos usuarios
$stmtUsers = $pdo->prepare("SELECT * FROM users");
$stmtUsers->execute();
$resultUsers = $stmtUsers->fetchAll(PDO::FETCH_ASSOC);

// Consultando todas visitas
$stmtVisitors = $pdo->prepare("SELECT COUNT(*) AS total_visitas FROM visitors");
$stmtVisitors->execute();
$resultVisitors = $stmtVisitors->fetch(PDO::FETCH_ASSOC);

// Consultando detalhes do admin logado
$stmtAdminUser = $pdo->prepare("SELECT * FROM admin_users WHERE phone = :phone");
$stmtAdminUser->execute([
    ':phone' => $adminUser
]);
$resultAdminUser = $stmtAdminUser->fetch(PDO::FETCH_ASSOC);

// Consultando total produtos
$stmtTotalProducts = $pdo->prepare("SELECT * FROM investment_products");
$stmtTotalProducts->execute();
$resultTotalProducts = $stmtTotalProducts->fetchAll(PDO::FETCH_ASSOC);

// Consultando total produtos ativos
$stmtTotalProductsActive = $pdo->prepare("SELECT * FROM investment_products WHERE is_active = '1'");
$stmtTotalProductsActive->execute();
$resultTotalProductsActive = $stmtTotalProductsActive->fetchAll(PDO::FETCH_ASSOC);

// Consultando Cupons
$stmtTotalCupons = $pdo->prepare("SELECT * FROM cupons");
$stmtTotalCupons->execute();
$resultTotalCupons = $stmtTotalCupons->fetchAll(PDO::FETCH_ASSOC);

// Consultar configs da plataforma
$stmtConfigs = $pdo->prepare("SELECT * FROM configs");
$stmtConfigs->execute();
$resultConfigs = $stmtConfigs->fetch(PDO::FETCH_ASSOC);

// Consultar Retiradas pendentes
$stmtWithdrawalPending = $pdo->prepare("SELECT * FROM withdrawal WHERE status = 'pending'");
$stmtWithdrawalPending->execute();
$resultWithdrawalPending = $stmtWithdrawalPending->fetchAll(PDO::FETCH_ASSOC);

// Consultar total de comissoes pagas afilliados
$stmtComissionsPaids = $pdo->prepare("SELECT SUM(liquid_affiliate) AS total_comissions FROM comission_affiliates");
$stmtComissionsPaids->execute();
$stmtComissionsPaidsFetch = $stmtComissionsPaids->fetch(PDO::FETCH_ASSOC);
$totalComissions = $stmtComissionsPaidsFetch['total_comissions'];

// Consultar valor total de retiradas pagas
$stmtWithdrawalPaids = $pdo->prepare("SELECT SUM(value) AS total_withdrawal_paid FROM withdrawal WHERE status = 'approved'");
$stmtWithdrawalPaids->execute();
$stmtWithdrawalPaidsFetch = $stmtWithdrawalPaids->fetch(PDO::FETCH_ASSOC);
$totalWithdrawalApproved = $stmtWithdrawalPaidsFetch['total_withdrawal_paid'];

// Consultar valor liquido total de retiradas pagas
$stmtWithdrawalLiquidPaids = $pdo->prepare("SELECT SUM(with_liquid) AS total_withliquid_paid FROM withdrawal WHERE status = 'approved'");
$stmtWithdrawalLiquidPaids->execute();
$stmtWithdrawalLiquidPaidsFetch = $stmtWithdrawalLiquidPaids->fetch(PDO::FETCH_ASSOC);
$totalWithdrawalLiquidApproved = $stmtWithdrawalLiquidPaidsFetch['total_withliquid_paid'];

$sumTaxasSaqs = $totalWithdrawalApproved - $totalWithdrawalLiquidApproved;

// Consultar total de taxas de saques recebidas
$stmtWithdrawalTaxaPaids = $pdo->prepare("SELECT COALESCE(SUM(value), 0) AS total_withdrawal_taxa_paid, COALESCE(SUM(with_liquid), 0) AS total_taxas FROM withdrawal WHERE status = 'approved'");
$stmtWithdrawalTaxaPaids->execute();
$stmtWithdrawalTaxaPaidsFetch = $stmtWithdrawalTaxaPaids->fetch(PDO::FETCH_ASSOC);
$totalWithdrawalApprovedTaxas = $stmtWithdrawalTaxaPaidsFetch['total_withdrawal_taxa_paid'];
$totalWithdrawalApprovedTaxasLiquid = $stmtWithdrawalTaxaPaidsFetch['total_taxas'];
$taxasLiquida = $totalWithdrawalApprovedTaxas - $totalWithdrawalApprovedTaxasLiquid;


