<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Resources\EgressoResource;
use App\Models\Egressos;
use App\Http\Requests\EgressoRequest;
use App\Imports\EgressoImport;
use App\Imports\EgressosImport;
use App\Mail\WelcomePassword;
use App\Models\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Keygen\Keygen;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Rap2hpoutre\FastExcel\FastExcel;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Validators\ValidationException;

class EgressoController extends Controller 
{
  //  protected array $failures;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        try{
            $perPage = $request->per_page ? intval($request->per_page) : 10;
            $page = $request->page ? intval($request->page) : 1;
            $orderBy = $request->orderBy ? strval($request->orderBy) : 'id';
            $orderDir = $request->orderDir ? strval($request->orderDir) : 'DESC';
            $term = $request->term ? strval($request->term) : "";
      
            $egresso = Egressos::SearchEgressos($perPage,$page,$orderBy,$orderDir,$term);

            return response()->json($egresso,200);

        }catch(\Exception $e){

            return response()->json(['errors' => ['message'=>[$e->getMessage()]]],404);
        }

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(EgressoRequest $request,User $user)
    {
        try{
            $egresso = Egressos::create($request->all());
          //  $user = $egresso->email;
            $this->sendPassword($user);

        }catch(\Exception $e){
            return response()->json($e->getMessage(),404);
        }



        return [
            'resposta' => response()->json('Registrado com sucesso!'),
         //   'email' => $this->sendPassword,
        ];

    }

    /**
     * Register a newly Egresso.
     *
     * @param  App\Http\Requests\EgressoRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function register(EgressoRequest $request)
    {
        try{
            DB::beginTransaction();

            $user = new User();
            $user->name = $request->email;
            $user->email = $request->email;
            $user->save();
            $user->assignRole('egresso');

            $egresso = new Egressos();
            $egresso->user_id = $user->id;
            $egresso->fill($request->all());

            $latitude = $request->lat;
            $longitude = $request->lng;
            if($latitude !== 0 && $longitude !== 0){
                $position = "ST_GeomFromText('POINT($latitude $longitude)')";
                $egresso->localization = DB::raw($position);
            }
            $egresso->save();

            if(!$this->sendPassword($user))
                throw new Exception('Não foi possível enviar o email de acesso.');

            DB::commit();

        }catch(\Exception $e){
            DB::rollBack();
            return response()->json(['error' => $e->getMessage()],404);
        }

        return response()->json(compact('user', 'egresso'),201);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        try{

         $data = Egressos::showegresso($id);


        return response()->json($data,200);

        }catch(\Exception $e){

            return response()->json($e->getMessage(),404);

        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(EgressoRequest $request,$id)
    {
        try{

            $egresso = Egressos::findOrfail($id);

            $latitude = $request->lat;
            $longitude = $request->lng;
            $position = "ST_GeomFromText('POINT($latitude $longitude)')";
            $egresso->localization = DB::raw($position);

            $egresso->update($request->all());

            // Retornando informações do Egresso
            $data = Egressos::showegresso($id);

            return response()->json($data,200);

        }catch(\Exception $e){

            return response()->json($e->getMessage(),404);

        }


    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {

        try{
            DB::beginTransaction();
            $egresso = Egressos::findOrfail($id);
            $egresso->user->delete();
            $egresso->delete();

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            return response()->json($e->getMessage(),404);

        }

        return response()->json("Registro excluído com sucesso!");
    }


    /**
   * Send email with password
   * @param User $user
   * @return Response
   */
    protected function sendPassword(User $user)
    {
        try {
            $password = Keygen::alphanum(8)->generate('strtolower');
            //$hashed_random_password = Hash::make($password);
            $user->password = $password;
            $user->save();
            Mail::to($user)->send(new WelcomePassword($password));
            Password::deleteToken($user);

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    // Mapa de Egressos
    public function map(Request $request)
    {
        try{
            $perPage = $request->per_page ? intval($request->per_page) : 10;
            $page = $request->page ? intval($request->page) : 1;

            $egresso = new EgressoResource(Egressos::paginate($perPage, ['*'],'page',$page));
            return response()->json($egresso,200);

        }catch(\Exception $e){

            return response()->json($e->getMessage(),404);
        }


    }
    // Importando dados utilizando Fast Excel - https://github.com/rap2hpoutre/fast-excel
    public function importEgresso(Request $request) 
    {
        try{

            (new FastExcel)->import($request->file('request_file'), function ($line) {

                $user = User::create([
                    'name' => $line['name'],
                    'email' => $line['email'],
                    
                ]);
                $user_id = $user->id;
                $user->password = $this->sendPassword($user);
                foreach($user as $egresso){
                    return Egressos::create([
                        'full_name' => $line['name'],
                        'email' => $line['email'],
                        'user_id' => $user_id,
                        'masters_degree_year'=> $line['masters_degree_year'],
                        'doctorate_degree_year' => $line['doctorate_degree_year'],
                        'job_area' => $line['job_area'],
                        'job_company' => $line['job_company'],
                        'job_state' => $line['job_state'],
                        'job_country' => $line['job_country'],
                        'allows_display_data_publicly' => $line['allows_display_data_publicly'],
                        'status' => $line['status'],
                        'is_retired' => $line['is_retired'],
                    ]);
                }
            });

        }catch(\Exception $ex){
            return response()->json(['error' => $ex->getMessage()],401);
        }
        

    }  

    //Importando dados através da Biblioteca Laravel Excel(Utilizado Atualmente) - https://docs.laravel-excel.com/
    public function EgressoImport() 
    {
        $import = new EgressoImport();
        $import->import(request()->file('egresso_file'));

        return response()->json('Importação de dados concluída',201);
    }

    public function me(EgressoRequest $request)
    {
        try{

            DB::beginTransaction();

            $id = Auth::user()->id;

         //   $egresso->assignRole('egresso');

            $latitude = $request->lat;
            $longitude = $request->lng;
            $position = "ST_GeomFromText('POINT($latitude $longitude)')";
            $egresso = Egressos::Where('user_id',$id)->update([
                'full_name' => $request->full_name,
                'email' => $request->email,
                'masters_degree_year' => $request->masters_degree_year,
                'doctorate_degree_year' => $request->doctorate_degree_year,
                'job_area' => $request->job_area,
                'job_company' => $request->job_company,
                'job_city' => $request->job_city,
                'job_state' => $request->job_state,
                'job_country' => $request->job_country,
                'allows_display_data_publicly' => $request->allows_display_data_publicly,
                'status' => $request->status,
                'is_retired' => $request->is_retired,
                'localization' => DB::raw($position)
            ]);

            $egresso_atualizado = Egressos::Where('user_id',$id)->get();

            // Retornando informações do Egresso

            DB::commit();
            return response()->json($egresso_atualizado,200);

        }catch(\Exception $e){
            DB::rollback();
            return response()->json($e->getMessage(),404);

        }
    }

}
