<?php

namespace App\Http\Controllers;

use App\Models\Granja;
use App\Models\Scawatt;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminScawattsController extends Controller
{
    public function index(Request $request)
    {
        $estado = $request->query('estado', 'todos');
        $granjaId = $request->query('granja', 'todas');
        $tipo = $request->query('tipo', 'todos');
        $orden = $request->query('orden', 'recientes');
        $busqueda = trim((string) $request->query('q', ''));
        $porPagina = (int) $request->query('por_pagina', 25);
        $porPagina = $porPagina > 0 ? min($porPagina, 100) : 25;

        $scawattsQuery = Scawatt::query()
            ->with([
                'usuario:id,nombre,email',
                'granja:id,nombre,departamento,municipio,estado',
            ]);

        if ($estado !== 'todos') {
            $scawattsQuery->where('estado', $estado);
        }

        if ($granjaId !== 'todas' && $granjaId !== null) {
            $scawattsQuery->where('granja_id', $granjaId);
        }

        if ($tipo !== 'todos') {
            $scawattsQuery->where('tipo', $tipo);
        }

        if ($busqueda !== '') {
            $scawattsQuery->where(function (Builder $query) use ($busqueda) {
                $query->where('scawatt_id', 'like', "%{$busqueda}%")
                      ->orWhereHas('usuario', function (Builder $subQuery) use ($busqueda) {
                          $subQuery->where('nombre', 'like', "%{$busqueda}%")
                                   ->orWhere('email', 'like', "%{$busqueda}%");
                      });
            });
        }

        $scawattsQuery->when($orden, function (Builder $query) use ($orden) {
            return match ($orden) {
                'valor_desc' => $query->orderByDesc('valor_actual'),
                'valor_asc' => $query->orderBy('valor_actual'),
                'kwh_desc' => $query->orderByDesc('kwh_asignados'),
                'kwh_asc' => $query->orderBy('kwh_asignados'),
                'valorizacion' => $query->orderByDesc(DB::raw('valor_actual - valor_inicial')),
                default => $query->orderByDesc('created_at'),
            };
        });

        $scawatts = $scawattsQuery->paginate($porPagina)->withQueryString();

        $stats = [
            'total' => Scawatt::count(),
            'activos' => Scawatt::where('estado', 'activo')->count(),
            'marketplace' => Scawatt::where('estado', 'marketplace')->count(),
            'valor_actual' => $this->formatCurrency(Scawatt::sum('valor_actual')),
            'valor_inicial' => $this->formatCurrency(Scawatt::sum('valor_inicial')),
            'valorizacion' => $this->formatCurrency(
                Scawatt::selectRaw('SUM(valor_actual - valor_inicial) as total')->value('total')
            ),
            'kwh_total' => $this->formatNumber(Scawatt::sum('kwh_asignados')),
        ];

        $porEstado = Scawatt::select('estado',
                DB::raw('COUNT(*) as total'),
                DB::raw('SUM(valor_actual) as valor_actual')
            )
            ->groupBy('estado')
            ->orderByDesc('total')
            ->get()
            ->map(function ($row) {
                return [
                    'estado' => $row->estado ?? 'sin_estado',
                    'total' => (int) $row->total,
                    'valor' => $this->formatCurrency($row->valor_actual),
                ];
            });

        $porTipo = Scawatt::select('tipo', DB::raw('COUNT(*) as total'))
            ->groupBy('tipo')
            ->orderByDesc('total')
            ->get();

        $granjas = Granja::select('id', 'nombre')->orderBy('nombre')->get();

        $topGranjas = Granja::select('granjas.id', 'granjas.nombre')
            ->withCount('scawatts')
            ->withSum('scawatts', 'valor_actual')
            ->orderByDesc('scawatts_count')
            ->limit(5)
            ->get();

        return view('admin.scawatts.index', [
            'scawatts' => $scawatts,
            'stats' => $stats,
            'porEstado' => $porEstado,
            'porTipo' => $porTipo,
            'granjas' => $granjas,
            'topGranjas' => $topGranjas,
            'filtros' => [
                'estado' => $estado,
                'granja' => $granjaId,
                'tipo' => $tipo,
                'orden' => $orden,
                'q' => $busqueda,
                'por_pagina' => $porPagina,
            ],
        ]);
    }

    private function formatCurrency($value): string
    {
        $numeric = $value !== null ? (float) $value : 0.0;
        return '$' . number_format($numeric, 0, ',', '.');
    }

    private function formatNumber($value): string
    {
        $numeric = $value !== null ? (float) $value : 0.0;
        return number_format($numeric, 2, ',', '.');
    }
}
