<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Patients;
use App\Models\Appointments;
use Throwable;
use App\Exceptions\GlobalException;
use Illuminate\Support\Facades\Auth;
use LaravelDaily\LaravelCharts\Classes\LaravelChart;
use Illuminate\Support\Carbon;
use App\Models\PatientsByDoctor;
use Exception;
use App\Models\Payments;
use App\Models\Currencies;

class DashboardController extends Controller
{
    // Paleta de colores médicos
    const PRIMARY_COLOR = '42, 78, 109';       // #2A4E6D
    const SECONDARY_COLOR = '59, 110, 165';    // #3B6EA5
    const ACCENT_COLOR = '74, 144, 226';       // #4A90E2
    const LIGHT_COLOR = '227, 242, 253';       // #E3F2FD

    public function view(Request $request)
    {
        try {
            $data = $request->all();
            $user = Auth::user();

            // Obtener totales de pagos por moneda
            $payments = Payments::where('active', 1)->get();
            $paymentTotals = [];
            
            if($payments->isNotEmpty()) {
                $groupedPayments = $payments->groupBy('currencies_id');
                
                foreach($groupedPayments as $currencyId => $currencyPayments) {
                    $currency = Currencies::find($currencyId);
                    if(!$currency) continue;
                    
                    $paymentTotals[] = [
                        'currency' => $currency->title,
                        'total' => $currencyPayments->sum('amount')
                    ];
                }
            }

            if(isset($data["myData"]) && $data["myData"] == 1) {
                // Gráfico principal de citas (Azul destacado)
                $chart1 = $this->createChart(
                    title: __('dashboard.graphAppointment'),
                    model: 'App\Models\Appointments',
                    type: 'bar',
                    color: self::ACCENT_COLOR,
                    filter: "users_id=".$user->id
                );

                // Gráficos para datos personales
                $chart2 = $this->createChart(
                    title: __('dashboard.graphAdultPatient'),
                    model: 'App\Models\PatientsByDoctor',
                    type: 'line',
                    color: self::PRIMARY_COLOR,
                    filter: "age>17 AND user_id=".$user->id
                );

                $chart3 = $this->createChart(
                    title: __('dashboard.graphPediatricPatient'),
                    model: 'App\Models\PatientsByDoctor',
                    type: 'line',
                    color: self::SECONDARY_COLOR,
                    filter: "age<18 AND user_id=".$user->id
                );

                // Datos específicos del usuario
                $stats = $this->getUserStats($user->id);
            } else {
                // Gráficos generales
                $chart1 = $this->createChart(
                    title: __('dashboard.graphAppointment'),
                    model: 'App\Models\Appointments',
                    type: 'bar',
                    color: self::ACCENT_COLOR
                );


                $chart2 = $this->createChart(
                    title: __('dashboard.graphAdultPatient'),
                    model: 'App\Models\Patients',
                    type: 'line',
                    color: self::PRIMARY_COLOR,
                    filter: "CAST(age AS INTEGER) > 17"
                );

                $chart3 = $this->createChart(
                    title: __('dashboard.graphPediatricPatient'),
                    model: 'App\Models\Patients',
                    type: 'line',
                    color: self::SECONDARY_COLOR,
                    filter: "CAST(age AS INTEGER) < 18"
                );

                // Datos globales
                $stats = $this->getGlobalStats();
            }

            return view("dashboard", array_merge($stats, [
                "chart1" => $chart1,
                "chart2" => $chart2,
                "chart3" => $chart3,
                "paymentTotals" => $paymentTotals
            ]));
        } catch(Exception $th) {
            throw $th;   //new GlobalException($th->getMessage());
        }
    }

    private function createChart(string $title, string $model, string $type, string $color, ?string $filter = null): LaravelChart
    {
        $options = [
            'chart_title' => $title,
            'report_type' => 'group_by_date',
            'model' => $model,
            'group_by_field' => 'date',
            'group_by_period' => 'day',
            'chart_type' => $type,
            'style_class' => 'medical-chart',
            'chart_color' => $color,
            'chart_height' => '400',
            'filter_day' => 30,
            'transparent' => true,
            'background' => '#FFFFFF',
            'border' => '1px solid #'.self::PRIMARY_COLOR
        ];


        if ($filter) {
            $options['where_raw'] = $filter;
        }


        return new LaravelChart($options);
    }

    private function getUserStats(int $userId): array
    {
        return [
            "patientsMinorThat18" => PatientsByDoctor::getPatientsMinorThat18($userId)->count(),
            "patientsMajorThat18" => PatientsByDoctor::getPatientsMajorThat18($userId)->count(),
            "appointmentsViews" => Appointments::where("active","0")
                ->where("users_id", $userId)
                ->count(),
            "appointmentsToday" => Appointments::where("active","1")
                ->where("users_id", $userId)
                ->whereDate('date', Carbon::today())
                ->count()
        ];
    }

    private function getGlobalStats(): array
    {
        return [
            "patientsMinorThat18" => Patients::getPatientsMinorThat18()->count(),
            "patientsMajorThat18" => Patients::getPatientsMajorThat18()->count(),
            "appointmentsViews" => Appointments::where("active","0")->count(),
            "appointmentsToday" => Appointments::where("active","1")
                ->whereDate('date', Carbon::today())
                ->count()
        ];
    }

    public function notAuthorized(Request $request)
    {
        try {
            return view("errors.not-authorized", [
                "message" => __("not-authorized.message")
            ]);
        } catch(Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
}