<?php

namespace App\Http\Controllers;

use App\Models\View;
use App\Models\CountryView;
use Illuminate\Http\Request;
use App\Models\Mensaje;
use App\Models\Team;
use App\Models\Header;
use App\Models\Comentario;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;

class ViewController extends Controller
{
    public function updateViewData(Request $request, $viewName)
    {
        $today = Carbon::now('America/Lima')->toDateString();

        // Obtener o crear el registro específico para el día de hoy
        $view = View::firstOrCreate(
            ['fecha' => $today],
            [
                'total_visitas'    => 0,
                'total_clicks'     => 0,
                'public_rebote'    => 0,
                'public_retention' => 0,
            ]
        );

        $view->total_visitas += 1;

        if ($request->boolean('clicked')) {
            $view->total_clicks += 1;
        }

        if ($view->total_visitas > 0) {
            $view->public_rebote = (($view->total_visitas - $view->total_clicks) / $view->total_visitas) * 100;
            $view->public_retention = ($view->total_clicks / $view->total_visitas) * 100;
        }

        $view->save();

        // --- REGISTRO DE PAÍS POR IP ---
        $ip = $request->ip();
        
        // IP de prueba para servidor local (Localhost)
        if ($ip === '127.0.0.1' || $ip === '::1') {
            $ip = '190.235.177.10'; // IP de Perú
        }

        try {
            $response = Http::timeout(3)->get("http://ip-api.com/json/{$ip}?fields=status,country,countryCode");
            
            if ($response->successful() && $response->json('status') === 'success') {
                $countryCode = $response->json('countryCode');
                $countryName = $response->json('country');

                $countryView = CountryView::firstOrCreate(
                    ['country_code' => $countryCode],
                    [
                        'country_name'  => $countryName,
                        'total_visitas' => 0
                    ]
                );

                $countryView->increment('total_visitas');
            }
        } catch (\Exception $e) {
            // Manejo silencioso en caso de falla de conexión
        }

        return response()->json([
            'total_visitas'    => $view->total_visitas,
            'total_clicks'     => $view->total_clicks,
            'public_rebote'    => $view->public_rebote,
            'public_retention' => $view->public_retention,
        ]);
    }

    public function getDashboardData()
    {
        $today = Carbon::now('America/Lima')->toDateString();

        // --- VISITAS Y CLICKS ---
        $viewToday = View::where('fecha', $today)->first();
        $totalVisitasHoy = $viewToday->total_visitas ?? 0;
        $totalClicksHoy = $viewToday->total_clicks ?? 0;

        // Totales históricos de visitas y clicks
        $totalVisitasHistorico = View::sum('total_visitas');
        $totalClicksHistorico = View::sum('total_clicks');

        // --- RETENCIÓN ---
        $retencionHoy = $totalVisitasHoy > 0 
            ? round(($totalClicksHoy / $totalVisitasHoy) * 100, 2) 
            : 0;

        $retencionHistorica = $totalVisitasHistorico > 0 
            ? round(($totalClicksHistorico / $totalVisitasHistorico) * 100, 2) 
            : 0;

        // --- REBOTE ---
        $reboteHoy = $totalVisitasHoy > 0 
            ? round((($totalVisitasHoy - $totalClicksHoy) / $totalVisitasHoy) * 100, 2) 
            : 0;

        $reboteHistorico = $totalVisitasHistorico > 0 
            ? round((($totalVisitasHistorico - $totalClicksHistorico) / $totalVisitasHistorico) * 100, 2) 
            : 0;

        // --- UBICACIONES GEOGRÁFICAS ---
        $topCountries = CountryView::orderBy('total_visitas', 'desc')->take(4)->get();
        $totalVisitasPaises = CountryView::sum('total_visitas');

        $paisesData = $topCountries->map(function ($item) use ($totalVisitasPaises) {
            $porcentaje = $totalVisitasPaises > 0 ? round(($item->total_visitas / $totalVisitasPaises) * 100) : 0;
            return [
                'name'       => $item->country_name,
                'code'       => strtolower($item->country_code),
                'porcentaje' => $porcentaje,
            ];
        });

        $teams = Team::all(); 
        $headers = Header::all();

        // --- MENSAJES ---
        $mensajes = Mensaje::whereDate('created_at', $today)->get();
        $totalMensajes = $mensajes->count();
        $totalHistoricoMensajes = Mensaje::count();

        // --- COMENTARIOS ---
        $comentarios = Comentario::whereDate('created_at', $today)->get();
        $totalComentarios = $comentarios->count();
        $totalHistoricoComentarios = Comentario::count();

        $totalTeams = $teams->count();
        $ctd = $totalTeams === 1 ? 'Miembro' : 'Miembros';  

        return view('dashboard', [
            'total_visitas_hoy'           => $totalVisitasHoy,
            'total_visitas'               => $totalVisitasHistorico,
            'total_clicks'                => $totalClicksHistorico,
            'retencion_hoy'               => $retencionHoy,
            'retencion_historica'         => $retencionHistorica,
            'rebote_hoy'                  => $reboteHoy,
            'rebote_historico'            => $reboteHistorico,
            'paisesData'                  => $paisesData,
            'teams'                       => $teams,
            'headers'                     => $headers,
            'mensajes'                    => $mensajes,
            'comentarios'                 => $comentarios,
            'total_teams'                 => $totalTeams,
            'total_mensajes'              => $totalMensajes,
            'total_historico_mensajes'    => $totalHistoricoMensajes,
            'total_comentarios'           => $totalComentarios,
            'total_historico_comentarios' => $totalHistoricoComentarios,
            'ctd'                         => $ctd,
        ]);
    }
}