<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
use App\Models\UserStudent;
use Exception;

class ExtraController extends Controller
{
    //

    public function studentsList(){

        try {
            $etudiants =
                DB::connection('tenant')
                ->table('tabetudiant')
                ->join('tabinscription','tabetudiant.matricule','=','tabinscription.matricule')
                ->where('tabinscription.annee_acad', session('annee_acad') )
                ->join('filieres','tabinscription.idFiliere','=','filieres.idFiliere')
                // ->whereIn('filieres.idDepartement',$idDepartements)
                ->whereIn('filieres.idFiliere', explode(',', session('filieres')))
                ->select('idDossier', 'cheminPhoto', 'tabetudiant.matricule', 'tabetudiant.pays', 'nom', 'prenom', 'sigleFilieres', 'adresse', 'date_nais', 'lieu_nais', 'tabinscription.idFiliere', 'sexe', 'nationalite', 'niveauFormation', 'annee', 'statut', 'resultat', 'nombreUErestant', 'pourcentageCredit',  'moyennePonderee', 'dateValidation')
                ->orderBy('nom', 'asc')
                ->limit (20)
                ->get();

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

            $status = $this->getStatus();

            // dd($etudiants);

            return view('operations.liste-etudiants', ["etudiants" => $etudiants, "status" => $status ]);

        } catch (Exception $e) {
            return redirect()->back()->with([
                'success' => false,
                'msg' => 'Nous rencontrons un probleme. Veuillez reessayez !'
            ]);
        }
    }

    //Show print form
    // public function filteredList(Request $request){

    //     try {

    //         $filieres = getUserFilieres();
    //         $cartes = ["Carte non imprimée","Carte imprimée"];

    //         // dd($filieres);
    //         $minYear = DB::connection('tenant')->table('tabinscription')
    //             ->select(DB::raw('MIN(annee_acad) as annee'))
    //             ->first();

    //             // $annee_acad = session( 'annee_acad' );

    //             // dd('annee_acad', $annee_acad);

    //         $minYear = json_decode(json_encode($minYear->annee), true);

    //         $maxYear = DB::connection('tenant')->table('tabinscription')
    //             ->select(DB::raw('MAX(annee_acad) as annee'))
    //             ->first();

    //         // $maxYear = json_decode(json_encode($maxYear->annee), true);
    //         $maxYear = intval(session('annee_acad'));

    //         // dd($minYear);

    //         $data = [
    //             'minYear' => $minYear,
    //             'maxYear' => $maxYear,
    //             'filieres' => $filieres,
    //             'cartes' => $cartes,
    //         ];

    //         // dd ($data);

    //         return view('operations.formulaire-impression', ['data' => $data]);


    //     } catch (Exception $e) {
    //         return redirect()->back()->with([
    //             'success' => false,
    //             'msg' => 'Nous rencontrons un probleme. Veuillez reessayez !'
    //         ]);
    //     }
    // }

    public function filteredList(Request $request)
{
    try {
        $idEtablissement = session('idEtablissement');


        $filieres = getUserFilieres();
        $cartes = ["Carte non imprimée", "Carte imprimée"];

        $minYear = DB::connection('tenant')
            ->table('tabinscription')
            ->select(DB::raw('MIN(annee_acad) as annee'))
            ->first();

        $minYear = json_decode(json_encode($minYear->annee), true);
        $maxYear = intval(session('annee_acad'));

        $data = [
            'minYear' => $minYear,
            'maxYear' => $maxYear,
            'filieres' => $filieres,
            'cartes' => $cartes,
            'idEtablissement' => $idEtablissement,
        ];

        return view('operations.formulaire-impression', ['data' => $data]);
    } catch (Exception $e) {
        return redirect()->back()->withErrors([
            'success' => false,
            'msg' => 'Nous rencontrons un problème. Veuillez réessayer !'
        ]);
    }
}


    //Show list of students according to filter done
    public function showFilteredList(Request $request){

        try {
            $req = $request->all();


            $anneeAcad = $request->input('annee_acad');
            
            // dump(Session::all());

            
            // $date_validation = '2024-10-08 ' ;


            $date_validation = '0001-01-01 00:00:00';
            $etat_carte = $req["type"];
            $annee_acad = $req["annee_acad"] ? $req["annee_acad"] : session('annee_acad');
            $annee_etude = ($req["annee_etude"] == "ALL")  ? session('annee') : [$req["annee_etude"]];
            $niveau = ($req["niveau"] == "ALL")  ? session('annee') : [$req["niveau"]];
            $filiere = ($req["filiere"] == "ALL") ? explode(',', session('filieres')) : [$req["filiere"]];


            // if ($date_validation === '0001-01-01 00:00:00') {
            //     throw new Exception('La date de validation fournie est invalide.');
            // }
            // dd($annee_acad);
            $etudiants =
                DB::connection('tenant')
                ->table('tabetudiant')
                ->join('tabinscription','tabetudiant.matricule','=','tabinscription.matricule')
                ->where([
                    // 'tabinscription.dateValidation' => $date_validation,
                    'tabinscription.annee_acad' => $annee_acad,
                ])
                ->whereIn('tabinscription.niveauFormation', $niveau)
                ->whereIn('tabinscription.annee', $annee_etude)
                ->join('filieres','tabinscription.idFiliere','=','filieres.idFiliere')
                ->whereIn('filieres.idFiliere', $filiere)
                ->select('idDossier', 'cheminPhoto', 'tabetudiant.matricule', 'tabetudiant.pays', 'nom', 'prenom', 'sigleFilieres', 'adresse', 'date_nais', 'lieu_nais', 'tabinscription.idFiliere', 'sexe', 'nationalite', 'niveauFormation', 'annee', 'statut', 'resultat', 'nombreUErestant', 'pourcentageCredit',  'moyennePonderee', 'dateValidation', 'dateInscription')
                ->orderBy('nom', 'asc')
                ->get();


                // dd($etudiants);

                // $etudiant = DB::connection('tenant')->table('tabetudiant')->join('tabinscription','tabetudiant.matricule','=','tabinscription.matricule')->where([
                //     'tabinscription.annee_acad' => $annee_acad,
                // ])->limit(10)->get();


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

            // dd ($etudiants);

            $matricules = array_column($etudiants, 'matricule');

            $hasCarte =
                DB::connection('tenant')
                    ->table('tabetudiant')
                    ->join('tabcarte','tabcarte.matricule', '=', 'tabetudiant.matricule')
                    ->get()
                    ->pluck('etat_carte', 'matricule');

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

            if ($etat_carte != "ALL") {
                $etudiants =  array_filter($etudiants, function ($etudiant) use ($hasCarte, $etat_carte) {
                    $condition = (($etat_carte == "1") && ( is_int( array_search($etudiant['matricule'], array_keys($hasCarte)) ) )) ||
                                 (($etat_carte == "0") && ( !is_int( array_search($etudiant['matricule'], array_keys($hasCarte)) ) )) ;

                    if ($condition) {
                        return $etudiant;
                    }
                });

                $etudiants = array_values($etudiants);
            }

            $status = $this->getStatus();

            session(['user_valid' => $matricules]); //Get user on which update and print operation can be made
            session(['print_year' => $annee_acad]); //Get selected year from filter

            $data = [
                'etat_carte' => $etat_carte,
                'etudiants' => $etudiants,
                'hasCarte' => $hasCarte,
                'status' => $status,
                'annee_acad' => $annee_acad
            ];

            // dd ($data);

            return view('operations.impression-carte', ["data" => $data ]);

        } catch (Exception $e) {
            return redirect()->back()->with([
                'success' => false,
                'msg' => 'Nous rencontrons un probleme. Veuillez reessayez !'
            ]);
        }
    }

    //Show list of students according to filter done
    public function printCard(Request $request, $matricule){

        try {

            // $annee_acad = json_decode($request->input('annee_acad'), true); 
            $annee_acad = $request->input('annee_acad');
          
           
            // dump($request->all());
            date_default_timezone_set('Africa/Porto-Novo');
            

            if (session('type_user') != 3) {
                fermeture_progiciel( session('id_etablissement') );
            }

            if ( in_array($matricule, session('user_valid'))) {



                
                // Current connected school
                $school_infos = get_school( session('id_etablissement') );

                // dd ($school_infos);


                // University where current connected school is from
                $university = get_uni( session('id_etablissement') );


                $params = [
                    // 'dateDepart' => $school_infos['dateDepart'],
                    'sigle' => $school_infos['sigle'],
                    // 'dureeValidite' => $school_infos['dureeValideCarte'],
                    'choixTemp' => $school_infos['choixTemp'],
                    // 'annee_acad' => current_period()['annee_acad'],
                    'annee_acad' => $annee_acad,
                    'periode' => current_period()['periode'],
                    // 'nbCarteImp' => 0,
                    'dateAcca' => '',
                ];
              

                // Pre-used date informations
                // $startTime = strtotime(date('d-m-Y H:i:s'));

                
                // $startTime = strtotime($params['dateDepart']);

                // dd ($startTime);
                // $endTime = strtotime("+".$params['dureeValidite']." year", $startTime);
                // $yearPeriod = strtotime("+1 year", strtotime( $params['annee_acad'] ) );
                // $params['dateAcca'] = $yearPeriod;



                if (!empty($params['dateDepart']) && strtotime($params['dateDepart']) !== false) {
                    $startTime = strtotime($params['dateDepart']);
                } else {
                    $startTime = time();
                }

                if (!empty($params['dureeValidite']) && is_numeric($params['dureeValidite'])) {
                    $endTime = strtotime("+" . $params['dureeValidite'] . " year", $startTime);
                } else {
                    $endTime = strtotime("+1 year", $startTime);
                }

                if (!empty($params['annee_acad']) && strtotime($params['annee_acad']) !== false) {
                    $yearPeriod = strtotime("+1 year", strtotime($params['annee_acad']));
                    $params['dateAcca'] = $yearPeriod;
                } else {
                    $params['dateAcca'] = strtotime("+1 year", time());
                }

                


                // get student info
                $etudiant =
                    DB::connection('tenant')
                    ->table('tabetudiant')
                    ->where('tabetudiant.matricule', $matricule)
                    ->join('tabinscription','tabetudiant.matricule','=','tabinscription.matricule')
                    ->where('tabinscription.annee_acad', session('print_year') )
                    ->join('filieres','tabinscription.idFiliere','=','filieres.idFiliere')
                    ->select('idDossier', 'cheminPhoto', 'tabetudiant.matricule', 'tabetudiant.pays', 'nationalite', 'nom', 'prenom', 'sigleFilieres', 'adresse', 'date_nais', 'lieu_nais', 'tabinscription.idFiliere', 'sexe', 'nationalite', 'niveauFormation', 'annee', 'statut', 'resultat', 'nombreUErestant', 'pourcentageCredit',  'moyennePonderee', 'dateValidation')
                    ->first();

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

                // dd ($etudiant);

                // get QR Code informations
                $qrCode =
                    DB::connection('tenant')
                    ->table('qrcode')
                    ->where([
                        'matricule' => $matricule,
                        'idFiliere' => $etudiant['idFiliere'],
                        'annee_acad' => $params['annee_acad'],
                        'annee' => $etudiant['annee']
                    ])
                    ->value('codeQr');

                        // dd ($qrCode);

                $etudiant['qrCode'] = $qrCode;

                

                // $students = UserStudent::all();

                // dd($students->take(10)->toArray());



                // dd ($etudiant);

                // Set default value
                $etudiant["hasCarte"] = 0;
                $etudiant["duplique"] = false;
                $etudiant["etat_carte"] = "Imprimée";


                
                // get Values on table carte : Check if student is registered. In case of multiple data, get the last

                $stuCarte =
                    DB::connection('tenant')
                    ->table('tabcarte')
                    ->select('matricule', 'date_exp', 'date_imp', 'etat_carte', 'nbCarteImp', 'id_carte')
                    // ->where([
                    //     'matricule' => $etudiant['matricule'],
                    //     'annee' => $etudiant['annee'],
                    //     'niveau' => $etudiant['niveauFormation']
                    //     ])
                    // ->where('matricule', '=', $etudiant['matricule'])
                    
                    ->orderBy('id_carte', 'desc')
                    ->get();

                    // dd($stuCarte->take(10)->toArray());  
                    

                $stuCarte = json_decode(json_encode($stuCarte), true);
                $stuCarte = is_null($stuCarte) ? [] : $this->unique_multidim_array($stuCarte, 'matricule');



                // Update parameters values for case of duplicata or not
                
                if ( count($stuCarte) ) {
                    
                    $stuCarte = $stuCarte[0];
                    
                    $etudiant["etat_carte"] = "Duplicata";
                    $etudiant["hasCarte"] = 1;
                   

                    $etudiant["duplique"] = true;
                   
                }
                // dd('La condition est exécutée', $etudiant);

                


                // Formater les dates et heures
                $etudiant["date_imp"] = date("Y-m-d H:i:s", $startTime);
                $etudiant["date_exp"] = date("Y-m-d H:i:s", $endTime);

                // dd($etudiant);

                // $etudiant["date_imp"] = date("Y-m-d H:i:s", $startTime);                
                
                // $etudiant["date_exp"] = date("Y-m-d H:i:s", $endTime);

                


                //Get number of printed card
                $nbCarteImp =
                    DB::connection('tenant')
                    ->table('tabcarte')
                    ->select(\DB::raw('MAX(id_carte) as nbCarteImp'))
                    ->first();

                $nbCarteImp = json_decode(json_encode($nbCarteImp->nbCarteImp), true);

                $nbCarteImp = is_null($nbCarteImp) ? 0 : intval ($nbCarteImp);

                

                // if ( $nbCarteImp == 0 ) {
                //     $params['nbCarteImp'] = 1;
                    
                // } else {
                //     if (count($stuCarte)) {
                //         $params['nbCarteImp'] = $stuCarte['nbCarteImp'];
                //     } else {
                //         $params['nbCarteImp'] =  $nbCarteImp + 1;
                //     }
                // }


                if (count($stuCarte)) {
                    $params['nbCarteImp'] = $stuCarte['nbCarteImp'] + 1;
                } else {
                    $params['nbCarteImp'] = $nbCarteImp + 1;
                }


                // Update parameters values for case of duplicata or not

               


                $updateData = [
                    "matricule" => $etudiant["matricule"],
                    "date_imp" => $etudiant["date_imp"],
                    "date_exp" => $etudiant["date_exp"],
                    "etat_carte" => $etudiant["etat_carte"],
                    "idDoss" => $etudiant["idDossier"],
                    "nbCarteImp" => $params['nbCarteImp'],

                    // "annee" => $etudiant['annee'],
                    // "niveau" => findNiveau($etudiant['niveauFormation'])[0],
                ];


            
                
                DB::connection('tenant')
                    -> table('tabcarte')
                    ->upsert(
                        $updateData, //values to insert or update,
                        ['matricule'], //lists of the column(s) that uniquely identify record
                        ['date_imp', 'date_exp', 'nbCarteImp'] //array of columns that should be updated if a matching record already exist
                    );

                

                if ( (count($stuCarte) == 0) ||
                    (count($stuCarte)  && (mb_strtolower($stuCarte['etat_carte']) != "duplicata"))
                ) {
                    DB::connection('tenant')
                        -> table('tabcarte')
                        ->insert($updateData);
                }


                $data = [
                    "etudiant" => $etudiant,
                    "params" => $params,
                    "etablissement" => $school_infos,
                    "universite" => $university,
                    "updateData" => $updateData,
                   
                ];

                //  dd ($data);
                

                return view('operations.page-impression', ["data" => $data ]);
            } else {
                return view('errors.404');
            }

        } catch (Exception $e) {
            return redirect()->back()->with([
                'success' => false,
                'msg' => 'Nous rencontrons un probleme. Veuillez reessayez !'
            ]);
        }
    }

    public function showImgUpdateView(Request $request, $matricule){
        try {

            if ( in_array($matricule, session('user_valid'))) {
                $etudiant =
                    DB::connection('tenant')
                        ->table('tabetudiant')
                        ->where('tabetudiant.matricule', $matricule)
                        ->join('tabinscription','tabetudiant.matricule','=','tabinscription.matricule')
                        ->where('tabinscription.annee_acad', session('print_year') )
                        ->join('filieres','tabinscription.idFiliere','=','filieres.idFiliere')
                        ->select('idDossier', 'cheminPhoto', 'tabetudiant.matricule', 'tabetudiant.pays', 'nationalite', 'nom', 'prenom', 'sigleFilieres', 'adresse', 'date_nais', 'lieu_nais', 'tabinscription.idFiliere', 'sexe', 'nationalite', 'niveauFormation', 'annee', 'statut', 'resultat', 'nombreUErestant', 'pourcentageCredit',  'moyennePonderee', 'dateValidation')
                        ->first();


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

                // get Values on table carte : Check is student is registered
                $stuCarte =
                    DB::connection('tenant')
                    ->table('tabcarte')
                    ->select('matricule', 'date_exp', 'date_imp', 'etat_carte', 'nbCarteImp')
                    ->where('matricule', '=', $etudiant['matricule'])
                    ->orderBy('id_carte', 'desc')
                    ->get();

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

                $stuCarte = is_null($stuCarte) ? [] : $this->unique_multidim_array($stuCarte, 'matricule');

                $etudiant["etat_carte"] = "";

                // Update parameters values for case of duplicata or not
                if (count($stuCarte)) {
                    $stuCarte = $stuCarte[0];
                    $etudiant["etat_carte"] = $stuCarte['etat_carte'];
                }

                return view('operations.modification-image', ["etudiant" => $etudiant ]);
            } else {
                return view('errors.404');
            }

        } catch(Exception $e){
            return redirect()->back()->with([
                'success' => false,
                'msg' => 'Nous rencontrons un probleme. Veuillez reessayez !'
            ]);
        }

    }

    /** update a user's image */
    public function imageUpdate(Request $request, $matricule){
        try {
            $req = $request->all();

            $data = [];

            // $public_path = 'public';
            $public_path = 's3';

            $path = 'imageEtudiant/'.session('id_etablissement').'/'.$matricule;

            $isImageUpdated = false;

            $photo = $request->file('imageUpload');

            if ($photo) {

                // $photo_name = $this->checkFileExist($path,$photo_name);
                $photo_name = $photo->getClientOriginalName();
                $photo_path = $photo->getPathname();
                $extension_upload = $photo->getClientOriginalExtension();

                $studentPath = 'images/Inscription';
                $cheminPhoto = $path.'.'.$extension_upload;
                $photoPath = config('app.aws_url') . $cheminPhoto;
                // Storage::disk($public_path)->put($studentPath.$cheminPhoto, file_get_contents($photo->getRealPath()));
                // Storage::put($cheminPhoto, $this->file_get_contents_curl($photoPath));
                Storage::disk($public_path)->put($cheminPhoto, file_get_contents($photo->getRealPath()));

                $isImageUpdated = true;
            }

            if($isImageUpdated ){ // this mean we came from profile page

                DB::connection('tenant')->table('tabetudiant')->where('matricule', $matricule)->update(['cheminPhoto' => $cheminPhoto]);

                return redirect()->back()->with([
                    'success' => true,
                    'msg' => "La photo de profil a été modifiée avec succès!"
                ]);
            } else {
                return view('errors.404', ["page" => url()->previous() ]);
            }

        } catch(Exception $e){
            return redirect()->back()->with([
                'success' => false,
                'msg' => 'Nous rencontrons un probleme. Veuillez reessayez !'
            ]);
        }

    }

    protected function checkFileExist($path,$filename_sent) {

        $filename = $filename_sent;
        $words2 = explode('.',$filename_sent);
        $file_ext = $words2[count($words2)-1];

        while (true) {
            $filename = uniqid(rand(), true) . ".". $file_ext;
            if (!file_exists($path.$filename)) break;
        }

        return $filename;
    }

    public function getStatus() {
        $statuts =
            DB::connection('tenant')
            ->table('statuts')
            ->where('idEtablissement', '=', session('id_etablissement'))
            ->get()
            ->groupBy('idStatut');

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

        return $statuts;
    }

    public function unique_multidim_array($array, $key) {
        $temp_array = array();
        $i = 0;
        $key_array = array();

        foreach($array as $val) {
            if (!in_array($val[$key], $key_array)) {
                $key_array[$i] = $val[$key];
                $temp_array[$i] = $val;
            }
            $i++;
        }
        return $temp_array;
    }

    protected function file_get_contents_curl($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

}
