<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

use App\Models\User;
use App\Models\Etablissement;
use App\Models\Academique;
use App\Models\TabEtudiant;

use Exception;

class AuthController extends Controller
{

    public function login() {
        return view('pages.connexion');
    }

    public function customLogin(Request $request){

        try {

            $message = [
                'required' => 'Tous les champs doivent être remplis.',
                'text' => 'This must be a string',
            ];

            $user = null;

            if ($request->exists('token') && $request->exists('redirectUrl')) {

                $device = get_device();
                $os = get_os();
                $browser = get_browsers();

                $user = DB::table('connexion')->where([
                    'token' => $request->token,
                    // 'ip' => $request->ip(),
                    // 'device' => $device,
                    // 'os' => $os,
                    // 'browsers' => $browser,
                ])->first();

                session([
                    'redirectUrl' => $request->redirectUrl,
                    'token' => $request->token,
                ]);

            } else {
                /*
                    $credentials = $request->only('username','password');

                    $validator = Validator::make($credentials, [
                        'username' => 'required',
                        'password' => 'required'
                    ], $message);

                    if ($validator->fails()) {
                        return redirect()->back()
                                ->withErrors(['error' => 'Tous les champs doivent être remplis.']);
                    }

                    $user = User::where("username", $credentials['username'])->first();
                */
            }

            if(!$user) {
                return redirect()->back()->withErrors([
                    'error' => "Votre username ou mot de passe est incorrect ! Veuillez réessayer.",
                ]);
            }

            /*
                if(!Hash::check($credentials['password'], $check_user->password)){
                    return redirect(url('/'))->withErrors([
                        'error' => "Votre nom d'utilisateur ou mot de passe est incorrect ! Veuillez réessayer.",
                    ]);
                }

                if($check_user->updatepssword == 0){
                    return redirect()->route('profile')->withErrors([
                        'error' => "Votre n'est pas à jour. Veuillez mettre à jour votre mot de passe.",
                    ]);
                }
            */

            $idEtablissement =
                User::where('username', $user->username)
                    ->first()
                    ->gestStudentR
                    ->idEtablissement;


                  


            /*
            $etablissement =
                Etablissement::where('idEtablissement',$idEtablissement)
                    ->first();
            */

            $user_data =
                User::where('username', $user->username)
                    ->first();

            $user_data = json_decode(json_encode($user_data), true);

            // dd ($user_data);
            if (!($idEtablissement) || !($user_data)) {
                return redirect()->back()->withErrors([
                    'error' => "Vous n'êtes pas autorisé à vous connecter sur cette plateforme !",
                ]);
            }
            
            $etablissement = get_school( intval($idEtablissement));


            $type_user = intval ($user_data['type_user']);

            if ( in_array($type_user, [1, 4, 7]) ){

                return redirect()->back()->withErrors([
                    'error' => "Vous n'avez pas les privilèges requis pour vous connecter !",
                ]);
            }

            $user_infos =
                User::where('username',$user->username)
                    ->first()
                    ->gestStudentR;

            // dd($user_infos);

            $user_infos = json_decode(json_encode($user_infos), true);


            changeEnv(['database'  => $etablissement['namebase'] ]);

            $niveauFormation = findNiveau();

            $formationBase = DB::connection('tenant')
                ->table('etablissement')
                ->where('idEtablissement', $idEtablissement)
                ->value('formationbase');


                if ($formationBase) {
                    Session::put('formationBase', $formationBase);

                } else {
                    Session::forget('formationBase'); 
                }

            // if ($formationBase) {
            //     if (!empty($niveauFormation)) {
            //         $niveauFormation[0] = $formationBase;
            //     }

            //     Session::put('niveauFormationFusion', $niveauFormation);

            // } else {
            //     return redirect()->back()->withErrors([
            //         'error' => "La formation de base pour cet établissement n'a pas pu être récupérée.",
            //     ]);
            // }

            // dd ($formationBase);

            // dump($etablissement, $user_infos, $user_data);

            // $year = current_acad();
            $year = current_period();

            $params = [
                "annee_acad" => $year['annee_acad'],
                "periode" => $year['periode'],
            ];

            // dd($params);

            // Place nameBase in session
            session([
                'nameBase' => $etablissement['namebase'],
                'sigle' => $etablissement['sigle'],
                'description' => $etablissement['descreta'],
                'username' => $user_data['username'],
                'matricule' => $user_data['matricule'],
                'type_user' => $user_data['type_user'],
                'annee_acad' => $params["annee_acad"],
                'periode' => $params['periode'],
                'cheminPhoto' => $user_infos['cheminPhoto'],
                'email' => $user_data['email'],
                'annee' => getYear(),
                // 'annee' => [1, 2, 3],
                'filieres' => $user_infos['idFiliere'],
                'id_etablissement' => intval($etablissement['idEtablissement']),
                'mes_etablissement' => $user_infos['mesEtablissement'],
                'update_password' => $user_data['updatepssword'],
                'phone' => $user_data['phone'],
               
            ]);

            if (array_key_exists("couleur", $etablissement)) {
                session([
                    'couleurs' => [
                        //Main color
                        "firstColor" => $etablissement["couleur"],
                        "secondColor" => $etablissement["couleur2"],
                        "thirdColor" => $etablissement["couleur3"],
                        //Light color
                        "firstLight" => $etablissement["ecouleur"],
                        "secondLight" => $etablissement["ecouleur2"],
                        "thirdLight" => $etablissement["ecouleur3"],
                        //Text color
                        "textColor1" => textColor($etablissement["couleur"]),
                        "textColor2" => textColor($etablissement["couleur2"]),
                        "textColor3" => textColor($etablissement["couleur3"]),
                    ]
                ]);
                // dd(session('couleurs'));
            } else {

                if ($request->redirectUrl) {
                    return redirect()->away($request->redirectUrl);
                } else {
                    return redirect()->back()->with([
                        'success'  => false,
                        'msg'  => "Un problème est survenu lors de la connexion à votre établissement !",
                    ]);
                }
            }

            return redirect()->route('home');

        } catch (Exception $e) {
            return redirect()->back()
                ->withErrors(['error' =>
                    "Une erreur est survenue lors de votre connexion"
                ]);

        }
    }

    public function logout() {

        if (session()->has('token')) {
            $redirectUrl = session('redirectUrl');
            Session::flush();

            return redirect()->away($redirectUrl);
        }
        // Session::flush();

        // return redirect()->away('/');
    }
}
