<?php
namespace App\Http\Controllers;
use DB;
use Session;
use PDF;
use Redirect;
use Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Storage;

class AuthController extends Controller
{
    public function getIp(){
        foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
            if (array_key_exists($key, $_SERVER) === true){
                foreach (explode(',', $_SERVER[$key]) as $ip){
                    $ip = trim($ip); // just to be safe
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                        return $ip;
                    }
                }
            }
        }
    }

    public function login(Request $request)
    {
        $token = $request->get('token');
        $ip = $this->getIp();
        Session::put('redirectUrl', $request->get('redirectUrl'));
        $user = $user1 = $user2 = '';
        /*$verify = DB::connection('africawebstudent_universite')->table('connexion')
                ->where(['username'=> $username, 'token'=> $token])->get();*/
        $verify = DB::connection('africawebstudent_universite')->table('connexion')
                ->where(['token'=> $token, 'ip'=> $ip])->get();
        $username = '';
        if(sizeof($verify) != 0) { 
            $username = $verify[0]->username;
            $user1 = DB::connection('africawebstudent_universite')->table('users')
                    ->join('geststudent_r', ['geststudent_r.matricule'=> 'users.matricule'] )
                    ->where(['username'=> $username])->get();
        }else{
            return Redirect::to('https://progiciel.geststudent.net/');
        }

        if( sizeof($user1) ==0){
        $message = "Erreur d'identifiant ou de mot de passe";
        return redirect()->back()->with('error', $message);
      }
      $id = 0;
      $dbname = '';
      if( sizeof($user1) !=0){
          $id = $user1[0]->idEtablissement;
          $user = $user1;
          $dbname = DB::connection('africawebstudent_universite')->table('etablissement')
                  ->where(['idEtablissement'=> $id])->value("namebase");
          $name = "africawebstudent_".$dbname;  
          
          session::put('cheminPhoto', 'https://progiciel.geststudent.net/Admin/'.$user1[0]->cheminPhoto);
          session::put('gestjury_database', $name);
      }
      
    $universite_html = '';
    $universite_logo = '';
    $universite = DB::connection(session::get('gestjury_database'))->table('universite')->get();
    if( sizeof($universite)!= 0 )
    {
        $universite_html = $universite[0]->sigleuni;
        $universite_logo = $universite[0]->nameimguni;
        session::put('universite_logo', 'https://progiciel.geststudent.net/Admin/'.$universite_logo);
        session::put('universite_html', $universite_html);
    }
   
      $user_type = '';
      $type_user=$user[0]->type_user;
      if( $type_user==3 || $type_user==2 || $type_user==4) $user_type = 'admin';
      else return redirect()->back()->with(['error'=> "Droit insuffisant !", 'success'=>false]);
      
      session::put('type_'.$user[0]->matricule, $user_type );
      session::put('utilisateur', $user);
      session::put('token_'.$user[0]->matricule, csrf_token() );
      //dd($request->input('_token'));
      //DB::connection(session::get('gestjury_database'))->table('geststock_action')->insert(['name' => 'Connexion', 'user' => $user[0]->username.' '.$user[0]->email, 'matricule'=>$user[0]->matricule, 'annee_acad'=> app('App\Http\Controllers\AuthController')->current_annee_acad()]);
      
      return redirect('admin/jury');
    }

    public function logout(Request $request){ 
        session::put('code_'.$request->mat, '');
        session::put('token_'.$request->mat, '');
        session::put('type_'.$request->mat, '');
        session::put('utilisateur', '');
        session::put('gestjury_database', '');
        session::put('database_is_selected', false);
        //return redirect()->route('index');  
        return Redirect::to('https://progiciel.geststudent.net/logout.php');
    }

    public function current_annee_academic() {
      $yes = 'YES';
      $academic =  DB::connection(session::get('gestjury_database'))->table('periodeinscription')
      ->where(['affiche'=> $yes])
      ->get();
      if (sizeOf($academic) != 0) {
        return $academic[0]->annee_acad;
      }
    }
}