<?php

namespace App\Livewire;

use Carbon\Carbon;
use App\Models\Code;
use Livewire\Component;
use Livewire\Attributes\On;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class CodeScanner extends Component
{

    #[On('qrLeido')]
    public function qrLeido($texto, $lat, $lng)
    {

        $dia = now()->translatedFormat('l');
        //dd($dia);

        $codigo = DB::table('area_code')
            ->where('name', $texto)
            ->first();

        if($codigo){

            $user = Auth::user();

            $planteles = $user->plantelUsuarios;

            $match=true;

            foreach($planteles as $plantel){

                $latCentro = $plantel->latitud;
                $lngCentro = $plantel->longitud;
                $radioPermitido = 100; // metros

                $distancia = $this->calcularDistancia($lat,$lng,$latCentro,$lngCentro);

                if($distancia <= $radioPermitido){
                    $match = false;
                    break;
                }

            }


            if($match){
                $this->dispatch('swal',
                    icon: 'error',
                    title: 'Error!',
                    text: 'Fuera del area permitida',
                    confirm: false,
                    closeModal: true,
                    reload: true,
                    timer: 5000
                );
                return;
            }

            $corps = DB::table('area_code')
            ->where('name', 'LIKE','%COR%')
            ->get();

            $cor=false;
            foreach($corps as $corp){

                if($corp->id == $user->code){
                    $cor = true;
                    break;
                }

            }

            if($cor){
                // dd("Ec un corpo el que esta checando");
            }else{
                if($user->code != $codigo->id){

                    $this->dispatch('swal',
                    icon: 'error',
                    title: 'Error!',
                    text: 'Este código no corresponde a tu area de trabajo',
                    confirm: false,
                    closeModal: true,
                    reload: true,
                    timer: 5000
                    );
                return;
                }
            }

            $hoy = Carbon::today();

            $asistenciasHoy = Code::where('user_id',$user->id)
                ->whereDate('registro',$hoy)
                ->orderBy('registro','desc')
                ->get();

            if($asistenciasHoy->count() >= 4){
                $this->dispatch('swal',
                icon: 'warning',
                title: 'Chequeos completos!',
                text: 'Límite de registros alcanzados',
                confirm: false,
                closeModal: true,
                );
                return;
            }


            if($asistenciasHoy->count() > 0){
                $ultima = Code::where('user_id',$user->id)
                        ->whereDate('registro', today())
                        ->latest('registro')
                        ->first();

                if($ultima->registro->diffInMinutes(now()) < 40){
                    $this->dispatch('swal',
                    icon: 'warning',
                    title: 'Espera!',
                    text: 'podrás checar 40 minutos despues de tu ultimo registro',
                    confirm: false,
                    closeModal: true,
                    );
                    return;
                }
            }

            Code::create([
                'user_id' => $user->id,
                'codigo' => $texto,
                'registro' => Carbon::now('America/Mexico_City')->format('d-m-Y H:i:s'),
                'latitud' => $lat,
                'longitud' => $lng,
            ]);

            $this->dispatch('swal',
                icon: 'success',
                title: 'Excelente!',
                text: 'asistencia registrada',
                confirm: false,
                closeModal: true,
                reload: true,
                timer: 3000
            );
            return;

        }else{
            $this->dispatch('swal',
                    icon: 'error',
                    title: 'Código inexistente',
                    text: 'Este codigo no es institucional',
                    confirm: false,
                    closeModal: true
            );
            return;
        }

    }

    private function calcularDistancia($lat1,$lon1,$lat2,$lon2)
    {
        $radioTierra = 6371000;

        $lat1 = (float)$lat1;
        $lon1 = (float)$lon1;
        $lat2 = (float)$lat2;
        $lon2 = (float)$lon2;

        $dLat = deg2rad($lat2 - $lat1);
        $dLon = deg2rad($lon2 - $lon1);

        $a = sin($dLat/2) * sin($dLat/2) +
            cos(deg2rad($lat1)) *
            cos(deg2rad($lat2)) *
            sin($dLon/2) * sin($dLon/2);

        $c = 2 * atan2(sqrt($a), sqrt(1-$a));

        return $radioTierra * $c;
    }

    public function render()
    {
        return view('livewire.code-scanner');
    }
}
