<?php

use App\Http\Livewire\Report;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('login');
})->name('login');

Route::post('/logout', function (Request $request) {
    Auth::logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
    return redirect('/');
});

Route::post('/login', function (Request $request) {
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required|string|min:6',
    ]);

    if (Auth::attempt($credentials)) {
        $request->session()->regenerate();
        return redirect()->intended('/reports');
    }
    return back()->withErrors([
        'message' => 'Dati di accesso errati',
    ]);
});

Route::group(['middleware' => 'auth'],function(){

    Route::get('/dashboard', \App\Http\Livewire\Dashboard::class);

    Route::get('/accertatore-grado', \App\Http\Livewire\AccertatoreGrado::class);
    Route::get('/ausilio-altri-enti', \App\Http\Livewire\AusilioAltriEnti::class);
    Route::get('/assicurazioni', \App\Http\Livewire\Compagnia::class);
    Route::get('/condizioni-strada', \App\Http\Livewire\CondizioneStrada::class);
    Route::get('/condizioni-atmosferiche', \App\Http\Livewire\CondizioniAtmosferiche::class);
    Route::get('/condizioni-luce', \App\Http\Livewire\CondizioniLuce::class);
    Route::get('/fondo-stradale', \App\Http\Livewire\FondoStradale::class);
    Route::get('/marche', \App\Http\Livewire\MarcaVeicolo::class);
    Route::get('/modelli', \App\Http\Livewire\ModelloVeicolo::class);
    Route::get('/materiale-recuperato', \App\Http\Livewire\MaterialeRecuperato::class);
    Route::get('/nomenclatura-strada', \App\Http\Livewire\NomenclaturaStrada::class);
    Route::get('/particolarita-strada', \App\Http\Livewire\ParticolaritaStrada::class);
    Route::get('/pavimentazione-strada', \App\Http\Livewire\PavimentazioneStrada::class);
    Route::get('/rilievi', \App\Http\Livewire\Rilievi::class);
    Route::get('/segnalazione-pervenuta-da', \App\Http\Livewire\SegnalazionePervenutaDa::class);
    Route::get('/segnalazione-verticale', \App\Http\Livewire\SegnalazioneVerticale::class);
    Route::get('/segnalazione-orizzontale', \App\Http\Livewire\SegnalazioneOrizzontale::class);
    Route::get('/stradario', \App\Http\Livewire\Stradario::class);
    Route::get('/tipo-segnalazione', \App\Http\Livewire\TipoSegnalazione::class);
    Route::get('/tipo-strada', \App\Http\Livewire\TipoStrada::class);
    Route::get('/entita-danno', \App\Http\Livewire\EntitaDanno::class);
    Route::get('/effetto-danno', \App\Http\Livewire\EffettoDanno::class);
    Route::get('/tipo-danno', \App\Http\Livewire\TipoDanno::class);
    Route::get('/tipo-urto', \App\Http\Livewire\TipoUrto::class);
    Route::get('/parte-macchina', \App\Http\Livewire\ParteMacchina::class);
    Route::get('/tipo-veicolo', \App\Http\Livewire\TipoVeicolo::class);
    Route::get('/users', \App\Http\Livewire\User::class);

    Route::get('/reports', \App\Http\Livewire\Report::class);
    Route::get('/istat', \App\Http\Livewire\Istat::class);

    Route::get('/print', Report::class);


    Route::get('/stradario_api', function(){
        if (isset($_GET["q"]))
            $stradario = \App\Models\Stradario::where('descrizione', 'like', '%' . $_GET["q"] . '%')->orderBy('descrizione')->get();
        else
            $stradario = \App\Models\Stradario::orderBy('descrizione')->get();
        $data = array();
        foreach($stradario as $s)
        {
            $data[] = array("id" => $s->id, "text" => $s->TOPONIMO . " " . $s->DESCRIZIONE);
        }
        return array("results" => $data);
    });

    Route::get('/anagrafica', function() {
        if (isset($_GET["q"])) {
            $anagrafica = \App\Models\Anagrafica::where('lastname', 'like', '%' . $_GET["q"] . '%')
                ->orWhere('firstname', 'like', '%' . $_GET["q"] . '%')
                ->orWhere('rag_soc', 'like', '%' . $_GET["q"] . '%')
                ->orderBy('lastname')
                ->orderBy('firstname')
                ->get();
        } else {
            $anagrafica = \App\Models\Anagrafica::orderBy('lastname')
                ->orderBy('firstname')
                ->get();
        }

        $data = [];
        foreach ($anagrafica as $a) {
            $text = (empty($a->lastname) && empty($a->firstname))
            ? $a->rag_soc // Use company name if names are empty
            : trim($a->lastname . ' ' . $a->firstname);

            $data[] = ["id" => $a->id, "text" => $text];
        }

        return ["results" => $data];
    });

    Route::get('/localita', function(){
        if (isset($_GET["q"]))
            $localita = \App\Models\LocationTown::where('title', 'like', '%' . $_GET["q"] . '%')->orderBy('title')->get();
        else
            $localita = \App\Models\LocationTown::orderBy('title')->get();
        $data = array();
        foreach($localita as $l)
        {
            $data[] = array("id" => $l->id, "text" => $l->title);
        }
        return array("results" => $data);
    });

    Route::get('/veicoli', function(){
        if (isset($_GET["q"]))
        {
            $value = $_GET["q"];
            $veicoli = \App\Models\Vehicle::with('marca')->with('modello')->whereHas('marca', function ($q) use ($value) {
                $q->where('name', "LIKE", '%' . $value . '%');
            })->orWhereHas('modello', function ($q) use ($value) {
                $q->where('name', "LIKE", '%' . $value . '%');
            })->get()->sortBy('marca.name',SORT_REGULAR,false);
        }
        else
            $veicoli = \App\Models\Vehicle::with('marca')->with('modello')->get()->sortBy('marca.name',SORT_REGULAR,false);
        $data = array();
        foreach($veicoli as $v)
        {
            $data[] = array("id" => $v->id, "text" => ($v->marca ? $v->marca->name : '') . " " . ($v->modello ? $v->modello->name : '') . " " . $v->targa);
        }
        return array("results" => $data);
    });

    Route::get('/accertatori', function(){
        if (isset($_GET["q"]))
        {
            $value = $_GET["q"];
            $accertatori =  DB::table('fcf_users')
                ->leftjoin('fcf_user_user_groups','fcf_user_user_groups.user_id','=','fcf_users.id')
                ->selectRaw('fcf_users.*')
                ->where('fcf_user_user_groups.group_id', 2)
                ->where(function ($query) {
                    $query->where('fcf_users.lastname', 'like', '%' . $_GET["q"] . '%')
                    ->orWhere('fcf_users.firstname', 'like', '%' . $_GET["q"] . '%');
                })
                ->orderBy('fcf_users.lastname')
            ->get();
        }
        else
            $accertatori =  DB::table('fcf_users')
                ->leftjoin('fcf_user_user_groups','fcf_user_user_groups.user_id','=','fcf_users.id')
                ->selectRaw('fcf_users.*')
                ->where('fcf_user_user_groups.group_id', 2)
                ->orderBy('fcf_users.lastname')
            ->get();
        $data = array();
        foreach($accertatori as $a)
        {
            $data[] = array("id" => $a->id, "text" => $a->lastname . " " . $a->firstname);
        }
        return array("results" => $data);
    });

    Route::get('/polizze', function(){
        if (isset($_GET["q"]))
        {
            $value = $_GET["q"];
            $polizze = \App\Models\Polizza::with('compagnia')->with('anagrafica')->where('agenzia', 'LIKE', '%' . $_GET["q"] . '%')
            ->orWhereHas('compagnia', function ($q) use ($value) {
                $q->where('name', "LIKE", '%' . $value . '%');
            })->orWhereHas('anagrafica', function ($q) use ($value) {
                $q->where('lastname', "LIKE", '%' . $value . '%')->orWhere('firstname', "LIKE", '%' . $value . '%');
            })->get()->sortBy('marca.name',SORT_REGULAR,false);
        }
        else
            $polizze = \App\Models\Polizza::with('compagnia')->with('anagrafica')->get()->sortBy('agenzia',SORT_REGULAR,false);
        $data = array();
        foreach($polizze as $p)
        {
            $data[] = array("id" => $p->id, "text" => $p->agenzia . " " . ($p->compagnia ? $p->compagnia->name : '') . " " . ($p->anagrafica ? ($p->anagrafica->lastname . " " . $p->anagrafica->firstname) : ''));
        }
        return array("results" => $data);
    });

});

Route::get('/test_targa/{targa}', function ($targa) {


    try
    {

        $wd = "dettaglioAutoveicoloBase";

        $wd = "datiCartaCircolazioneAutoveicoloProprietario";

        $url = 'https://www.ilportaledellautomobilista.it/Info-ws/services';
        $client = new \SoapClient($url . '/' . $wd . '/' . $wd . '.wsdl', array(
            'stream_context' => stream_context_create(array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
                )),
                'trace'=>1
        ));

        $utente = 'CMRM001301';
        $password = '2PMPM*86';

        $xml = '<wsse:Security
        xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
        SOAP-ENV:mustUnderstand="1">
        <wsse:UsernameToken
            xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
            wsu:Id="XWSSGID-1253605895203984534550">
            <wsse:Username>' . $utente . '</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $password . '</wsse:Password>
        </wsse:UsernameToken>
        </wsse:Security>';

        $header = new \SoapHeader('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd',
                    'Security',
                    new \SoapVar($xml, XSD_ANYXML),
                    true
                );
        $client->__setSoapHeaders($header);

        $classe = "dettaglioAutoveicoloBase";

        $classe = "dettaglioCartaCircolazioneProprietarioAutoveicolo";

        try
        {

            // Run the function
            $obj = $client->__soapCall($classe, array(
                $classe . "Request" => array(
                    "login" => array(

                    ),
                    //"dettaglioAutoveicoloBaseInput" => array(
                        "targa" => array("numeroTarga" => $targa),
                    //),
                    "pdf" => false
                )
            ));

            print "<pre>";
            print_r($obj);
            print "</pre>";

        }
        catch(\SoapFault $fault)
        {

            print $fault;
            // <xmp> tag displays xml output in html
            //echo 'Request : <br/><xmp>',
            //$client->__getLastRequest(),
            //'</xmp><br/><br/> Error Message : <br/>',
            //$fault->getMessage();
        }
    }
    catch(Exception $ex)
    {
        print "QUA5";
        print $ex;
    }

});
Route::get('/print-pdf/{id}', [Report::class, 'print'])->name('print.pdf');

Route::get('/countries', function() {
    $search = request()->get('search');

    $query = \App\Models\LocationCountry::query();

    if($search) {
        $query->where('name', 'like', "%{$search}%");
    }

    $countries = $query->get()->map(function($country) {
        return [
            'id' => $country->id,
            'text' => $country->name
        ];
    });

    return response()->json([
        'results' => $countries
    ]);
});

Route::get('/compagnie', function(){
    if (isset($_GET["q"]))
        $compagnie = \App\Models\Compagnia::where('name', 'like', '%' . $_GET["q"] . '%')->orderBy('name')->get();
    else
        $compagnie = \App\Models\Compagnia::orderBy('name')->get();

    $data = array();
    foreach($compagnie as $c)
    {
        $data[] = array("id" => $c->id, "text" => $c->name);
    }
    return array("results" => $data);
});

Route::get('/polizze/agenzie', function(Request $request) {
    $query = \App\Models\Polizza::query();

    if ($request->has('q')) {
        $query->where('agenzia', 'like', '%' . $request->q . '%');
    }

    // Get unique agenzie
    $agenzie = $query->distinct()
        ->whereNotNull('agenzia')
        ->where('agenzia', '!=', '')
        ->pluck('agenzia');

    return [
        'results' => $agenzie->map(function($agenzia) {
            return [
                'id' => $agenzia,
                'text' => $agenzia
            ];
        })
    ];
});
