<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Project;
use App\Activity;
use App\Task;
use App\Equipe;
use App\User;
use App\Connexion;
use App\Jobs\CheckActivityStatusJob;
use App\Jobs\CheckProjectStatusJob;
use App\Jobs\CheckTaskStatusJob;
use Carbon\Carbon;
use DateTime;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use App\Mail\AssociateUser;
use App\Mail\RejectUser;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Validator;

class PagesController extends Controller
{


    public function profile (Request $request)
    {
        $user_connected_name = $request->session()->get('username');

        $user_connected = DB::table('users_student')->where('username', $user_connected_name)->first();
        $user_etudiant= DB::connection('tenant')->table('tabetudiant')->where('matricule', $user_connected->matricule)->first();
        $annee = DB::connection('tenant')->table('periodeinscription')
            ->where('affiche', 'YES')
            ->select('annee_acad')
            ->first()->annee_acad;
        $idFiliere = DB::connection('tenant')
            ->table('tabinscription')
            ->where('matricule','=',$user_etudiant->matricule)
            ->where('annee_acad',$annee)
            ->first()
            ->idFiliere;
        $filiere = DB::connection('tenant')->table('filieres')->where('idFiliere', $idFiliere)->first();
        // dd($user_connected, $idFiliere, $filiere);
        return view('profile-user')->with([
            'user_connected' => $user_connected,
            'user_etudiant' => $user_etudiant,
            'filiere' => $filiere,
            'photo' => $user_etudiant->cheminPhoto
        ]);
    }

    public function profile_update (Request $request)
    {
        dd($request);
        $this->validate($request, [
            'first_name' => 'required',
            'last_name' => 'required',
            'filière' => 'required',
            'email' => 'required|string|email',
            'password' => 'required|string|min:8'
        ]);

        $user_connected = $request->session()->get('user');
        $user_connected->update([
            'name' => $request->last_name,
            ''
        ]);
        return view('profile-user')->with([
            'user_connected' => $user_connected,
        ]);
    }

    public function assign(Request $request)
    {
        $project = Project::where('id', $request->project_id)->first();
        $tab =[];
        $verification = 0;
        $username = $request->session()->get('username');
        $the_user = new User();
        $the_user->setTable('users_student');
        $user_connected = $the_user->where('username', $username)->first();
        $project_users = DB::connection('tenant')
                                ->table('gesttask_projet_user')
                                ->join('gesttask_users', 'gesttask_projet_user.user_id', '=', 'gesttask_users.id')
                                ->where('projet_id', $project->id)
                                ->get();
        foreach($project_users as $user)
        {
            //$project->users()->detach($user->id);
            $tab []= $user->id;
        }
        foreach($request->membres as $membre)
        {
            $user = $the_user->find($membre);
            // $user = DB::table('users_student')->where('id', $membre)->first();

            if (!in_array($user->id, $tab)){
                // $project->users()->attach($user->id);
                DB::connection('tenant')->table('gesttask_projet_user')
                    ->insert([
                        'role' => 'reader',
                        'user_id' => $user->id,
                        'projet_id' => $project->id
                    ]);
                try {
                    Mail::to($user->email)->send(new AssociateUser($user, $project, $user_connected));

                } catch (\Throwable $th) {
                    return back()->with([
                        'success'=> false,
                        'message'=> trans(`${$th}`),
                    ]);
                }
                $verification++;
            }

            /* Mail::to($user->email)->send('emails.associatedUser',[
                'user' => $user,
                'project' => $project,
                'user_connected' => $request->session()->get('user')
            ],
            function ($message){
                $message->subject('Un utilisateur associé au projet');
            }); */
            //dd($request->session()->get('user'));

        }

        if ($verification == 0)
        {
            return back()->with([
                'success'=> false,
                'message'=> trans('Le/les utilisateur(s) sont déjà associé(s) au projet !'),
            ]);
        }
        return back()->with([
            'success'=> true,
            'message'=> trans('Le ou les utilisateurs ont été bien assignés au projet !'),
        ]);
    }

    public function reject(Request $request)
    {
        // dd($request);
        // $user = User::find($request->user_associated);
        $user = DB::table('users_student')->where('id', $request->user_associated)->first();
        $project = Project::where('id', $request->project_id)->first();
        if ($user)
        {
            // $project->users()->detach($user->id);
            $id_project_users = DB::connection('tenant')->table('gesttask_projet_user')->where([
                ['user_id', $user->id],
                ['projet_id', $project->id]
            ])->get();

            // dd($id_project_users);
            foreach($id_project_users as $id_project_user) {
                DB::connection('tenant')->table('gesttask_projet_user')->delete($id_project_user->id);
            }

            // Mail::to($user->email)->send(new RejectUser($user, $project, $request->session()->get('user')));
            return back()->with([
                'success'=> true,
                'message'=> trans('L\'utilisateur a bien été éjecté(e) du projet !'),
            ]);
        }
        else
        {
            return back()->with([
                'success'=> false,
                'message'=> trans('L\'utilisateur n\'a pas pu être éjecté(e) du projet !'),
            ]);
        }
    }

    public function associates_list(Request $request)
    {
        $username = $request->session()->get('username');
        $user_connected = DB::table('users_student')->where('username', $username)->first();

        $project = Project::where('id', $request->project_id)->first();

        $users = $this->getProjectUsers($project->id, $user_connected->idEtablissement);

        $project_users = DB::connection('tenant')->table('gesttask_projet_user')->where('projet_id', $project->id)->get();
        //dd(json_decode(json_encode($projet_users), true));
        //dd(array_column(json_decode(json_encode($projet_users), true), 'role', 'user_id'));
        $array_project_users = array_column(json_decode(json_encode($project_users), true), 'role', 'user_id');
        $default = "imageEtudiant/votrephoto.jpg";
        return view('associates-user', compact('users', 'default','project', 'user_connected','array_project_users'));
    }

    public function set_permission(Request $request)
    {
        //dd($request);

            DB::connection('tenant')->table('gesttask_projet_user')->where([
                ['projet_id', $request->project_id],
                ['user_id', $request->user_id]
            ])->update(['role' => $request->role]);
            //Mail::to($user->email)->send(new RejectUser($user, $project, $request->session()->get('user')));
            return back()->with([
                'success'=> true,
                'message'=> trans('Les droits ont bien étés attribués à l\'utilisateur !'),
            ]);

        /* else
        {
            return back()->with([
                'success'=> false,
                'message'=> trans('L\'utilisateur n\'a pas pu être éjecté(e) du projet !'),
            ]);
        } */

    }

    public function activities_list (Request $request)
    {
        // $activities = Activity::where('projet_id',$request->id)->get();
        $activities = DB::connection('tenant')->table('gesttask_activities')->where('projet_id',$request->id)->get();
        // $project = Project::find($request->id);
        $project = DB::connection('tenant')->table('gesttask_projets')->where('id', $request->id)->first();
        // $users = User::all();
        // $user_connected = $request->session()->get('user');
        $username = $request->session()->get('username');
        $user_connected = DB::table('users_student')->where('username', $username)->first();
        $users = DB::table('users_student')->where('idEtablissement', $user_connected->idEtablissement)->get();
        // dd($user_connected, $project);


        // $user = new User();
        // $user->setTable('users');
        // $user_connected = $user->where('username', $username)->first();
        // if (empty($user_connected)) {
        //     $user->setTable('users_student');
        //     $user_connected = $user->where('username', $username)->first();
        // }
        // $users = $user->all();
        // dd($activities);

        // dd(DB::connection('tenant')->table('gesttask_projet_user')->where('projet_id', $project->id)->get('role'));

        // dump($user_connected->id);
        $role = DB::connection('tenant')->table('gesttask_projet_user')->where([
            ['projet_id', $project->id],
            ['user_id', $user_connected->id]
        ])->get('role');
        // dd($role);
        //dd($role.toString());

        // $project_users = DB::connection('tenant')
        //                         ->table('gesttask_projet_user')
        //                         ->join('gesttask_users', 'gesttask_projet_user.user_id', '=', 'gesttask_users.id')
        //                         ->where('projet_id', $project->id)
        //                         ->get();

        // $_project_users = DB::connection('tenant')
        //                         ->table('gesttask_projet_user')
        //                         ->where('projet_id', $project->id)
        //                         ->get('user_id');
        // dd($_project_users);

        // $user_ids = [];
        // foreach ($_project_users as $_project_user) {
        //     $user_ids[] = $_project_user->user_id;
        // }

        // dd($user_ids);

        $project_users = $this->getProjectUsers($project->id, $user_connected->idEtablissement);
        // foreach ($users as $user) {
        //     if(in_array($user->id, $user_ids)) {
        //         $project_users[] = $user;
        //     }
        // }

        // dd($project_users);

        // foreach($activities as $activity) {
        //     $activity->start_date = $this->getDate(explode(' ', $activity->start_date)[0]);
        //     $activity->end_date = $this->getDate(explode(' ', $activity->end_date)[0]);
        // }
        // $project->start_date = $this->getDate(explode(' ', $project->start_date)[0]);
        // $project->end_date = $this->getdate(explode(' ', $project->end_date)[0]);

        $tasks_count = [];

        foreach ($activities as $activity) {
            $tasks_count[$activity->id] = DB::connection('tenant')
                                    ->table('gesttask_taches')
                                    ->where('activity_id', $activity->id)
                                    ->get()->count();
        }
        $project->start_date = (new DateTime($project->start_date))->format('Y-m-d H:i');
        $project_end_date = (new DateTime($project->end_date))->format('Y-m-d H:i');
        return view('list-activities-user', compact('activities','project', 'users', 'user_connected', 'role', 'project_users', 'tasks_count'));
    }

    public function activity_store(Request $request)
    {
        // dd($request);
        $project = Project::find($request->project_id);
        $validator = Validator::make($request->all(), [
            'titre' => 'required',
            'start_date' => ['date',  'after_or_equal:' .(new DateTime($project->start_date))->format('Y-m-d H:i') ],
            'end_date' => ['date', 'before_or_equal:' .(new DateTime($project->end_date))->format('Y-m-d H:i')],
        ]);

        if ($validator->fails()) {
            return redirect()->back()->with([
                'success'=> false,
                'message'=> trans('Les champs ne sont pas bien remplis !'),
            ])->withErrors($validator);
        }

        $activity=Activity::create([
            'name' => $request->titre,
            'projet_id' => $request->project_id,
            'percentage' => 0,
            'start_date' => (new \DateTime($request->start_date))->format('Y-m-d H:i'),
            'end_date' => (new \DateTime($request->end_date))->format('Y-m-d H:i'),
        ]);
        $activity->start_date = str_replace('T',' ', $activity->start_date) ;
        $activity->end_date = str_replace('T',' ', $activity->end_date) ;
        $activity->update([
            'statut' => $this->update_activity_status(0, $activity)
        ]);

        //CheckActivityStatusJob::dispatchNow();

        return redirect()->back()->with([
            'success'=> true,
            'message'=> trans('L\'activité a bien été créée!'),
        ]);
    }

    public function activity_destroy(Request $request)
    {
        $activity = Activity::find($request->activityid);
        // dd($activity);
        if ($activity->statut == 'new'){
            Activity::destroy($request->activityid);
            return redirect()->back()->with([
                'success'=> true,
                'message'=> trans('L\'activité a bien été supprimée!'),
            ]);
        }
        else {
            return redirect()->back()->with([
                'success'=> false,
                'message'=> trans('Vous ne pouvez pas supprimer cette activité !'),
            ]);
        }

    }

    public function activity_update(Request $request)
    {
        // dd($request);
        // $project= Project::find($request->project_id);
        $activity = Activity::where('id', $request->activity_id)->first();
        $project= Project::find($activity->projet_id);
        $validator = Validator::make($request->all(), [
            'title_modify' => 'required',
            'start_date' => ['required', 'date',  'after_or_equal:' .(new DateTime($project->start_date))->format('Y-m-d H:i'), 'before_or_equal:' .(new DateTime($project->end_date))->format('Y-m-d H:i') ],
            'end_date' => ['required', 'date', 'after:start_date', 'before_or_equal:' .(new DateTime($project->end_date))->format('Y-m-d H:i')],

        ]);
        if($validator->fails())
        {
            return redirect()->back()->with([
                'success'=> false,
                'message'=> trans('Les champs ne sont pas bien remplis !'),
            ])->withErrors($validator);
        }
        $activity->update([
            'name' => $request->title_modify,
            'start_date' =>$request->start_date,
            'end_date' =>$request->end_date,
        ]);
        return redirect()->back()->with([
            'success'=> true,
            'message'=> trans('L\'activité a bien été modifiée'),
        ]);
    }

    public function listTask (Request $request)
    {
        $project = Project::find($request->project_id);
        $activity = Activity::find($request->activity_id);
        $tasks = Task::orderBy('id', 'ASC')->where('activity_id', $activity->id)->get();
        // $tasks = DB::connection('tenant')->table('gesttask_taches')->where('activity_id', $activity->id)->get();
        // $tasks = $this->check_tasks_status($tasks, $activity);
        // $users = $project->users()->get();

        $username = $request->session()->get('username');
        $user_connected = DB::table('users_student')->where('username', $username)->first();
        // dd($user_connected);

        $users = $this->getProjectUsers($project->id, $user_connected->idEtablissement);

        $allUsers = DB::table('users_student')->where('idEtablissement', $user_connected->idEtablissement)->get();
        // dd($allUsers);

        $role = DB::connection('tenant')->table('gesttask_projet_user')->where([
            ['projet_id', $project->id],
            ['user_id', $user_connected->id]
        ])->get('role');



        $tasks_users = [];
        foreach ($tasks as $task) {
            $tasks_users[$task->id] = $this->getTaskUsers($task->id, $user_connected->idEtablissement);
        }


        // dd(explode(' ', $tasks[0]->start_date)[0]);

        $activity->start_date = (new DateTime($activity->start_date))->format('Y-m-d H:i') ;
        $activity->end_date = (new DateTime($activity->end_date))->format('Y-m-d H:i') ;


        return view('list-tasks-user', compact(['project', 'activity', 'tasks', 'users', 'user_connected', 'allUsers', 'role', 'tasks_users']));
    }

    public function inscription ()
    {
        return view('inscription-user');
    }

    public function logininterm(Request $request){
        $user = $request->session()->get('user');
        $userphoto = DB::table('geststudent_r')->where('matricule', $user->matricule)->first();
        if($userphoto == null){
            $userphoto = DB::connection('tenant')->table('tabetudiant')->where('matricule', $user->matricule)->first();
        }
        $request->session()->put('cheminPhoto', $userphoto->cheminPhoto);
        $request->session()->put('nom', $userphoto->nom);
        $request->session()->put('prenom', $userphoto->prenom);

        if ($user->type_user == 4 ) {
            // dd('Success');
            $redirectTo = '/admin-index';
        } else {
            // dd("success");
            $redirectTo = '/home/projects';
        }

        $request->session()->forget('user');
        // dd('success');
        return redirect($redirectTo)->with([
            'success'=> true,
            'message'=> trans('Connexion réussie !'),
        ]);
    }

    public function connexion (Request $request)
    {
        //dd($request);

        // $token = "ca18526c40a5eefe0a6e4d647062613abf88249c6d3f01a1c9204931a29f28dd";
        // $token = "8120b4fdb936c8f2aa67a076abac0759cc5dd7fad95b1a15f0bd13d49de72a10";
        // $ip = "41.79.219.36";
        // $os = "Windows 10";
        // $browsers = "Chrome";
        // $device = "Computer";
        // $ip = "41.85.185.106";

        // $yourname = 'dissou.dissou';
        // $yourname = 'freddy.agbangla';

        // $request->{'token'} = DB::table("login_history")->where("matricule",20912620)->first()->access_token;

        // $data = DB::table("login_history")->where("matricule", 19045018)->first();
        // $data = DB::table("connexion")->where('token', 'a331acf5511b9a7a3773862c2d048005')->first();
        // $data = DB::table("connexion")->get();
        // dd($data);


        //dd(getIPAddress());
        if ($request->token) {
            // dd($request);
            // $connexion = DB::table('gesttask_connexions')->where('token', $request->token)->first();
            // dd(DB::table('connexion')->where('id', 2));

            $connexion = DB::table('connexion')->where('token', $request->token)->first();

            $ip = $this->get_ip();
            $os = $this->get_os();
            $browsers = $this->get_browsers();
            $device = $this->get_device();

            //dd($os, $ip, $browser, $device);
            // dd($connexion);
            if($connexion && $connexion->ip == $ip && $connexion->os == $os && $connexion->browsers == $browsers && $connexion->device == $device) {
                // $user = User::where('name', $connexion->username)->first();
                $user = DB::table('users')->where('username', $connexion->username)->first();
                if (empty($user)) {
                    $user = DB::table('users_student')->where('username', $connexion->username)->first();
                    // $user = DB::table('users_student')->where('username', $yourname)->first();
                    if(empty($user)) {
                        return redirect()->back()->with([
                            'success'=> false,
                            'message'=> trans('Les informations de l\'utilisateur n\'ont pas été trouvées !'),
                        ]);
                    }
                    // dd($user);
                }
                // $request->session()->put('user', $user);
                // dd($user);

                // dd($userphoto->cheminPhoto);
                $request->session()->put('user',$user);
                $request->session()->put('token', $request->token);
                $request->session()->put('redirectUrl', $request->redirectUrl);
                $request->session()->put('username', $user->username);
                $request->session()->put('email', $user->email);

                // dd("success");
                // if ($user->type == 'admin') {
                return redirect('/logini');
            }
            else {
                if (session()->has('user')) {
                    $user = session()->get('user');
                    if ($user->type == 'admin') {
                        $redirectTo = '/admin-index';
                    } else {
                        $redirectTo = '/home/projects';
                    }
                    return redirect($redirectTo);
                } else {
                    return view('connexion-user');
                }
            }
        } else {
            return view('connexion-user');
        }
    }


    // public function projets (Request $request)
    // {
    //     CheckTaskStatusJob::dispatchNow()->delay(now()->addMinutes(1));
    //     CheckActivityStatusJob::dispatchNow()->delay(now()->addMinutes(1));
    //     CheckProjectStatusJob::dispatchNow()->delay(now()->addMinutes(1));
    //     $equipes = Equipe::all();
    //     // $projets = Projet::all();
    //     $projets = Projet::all()->paginate(9);
    //     $projetsrecents = Projet::all()->take(2);
    //     return view('project-change-user',compact('projets','projetsrecents','equipes'));
    // }

    //Opérations sur les tâches
    public function task_store(Request $request)
    {
        $activity = Activity::find($request->activity_id);

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'start_date' => ['required', 'date', 'after_or_equal:' .(new DateTime($activity->start_date))->format('Y-m-d H:i')],
            'end_date' => ['required', 'date',  'before_or_equal:' .(new \DateTime($activity->end_date))->format('Y-m-d H:i')],

        ]);

        if($validator->fails())
        {
            return redirect()->back()->with([
                'success'=> false,
                'message'=> trans('Les champs ne sont pas bien remplis !'),
            ])->withErrors($validator);
        }

        $task = Task::create([
            'name' => $request->name,
            'statut' => $this->update_task_status($request),
            'percentage' => (double) $request->percentage,
            'start_date' => (new \DateTime($request->start_date))->format('Y-m-d H:i'),
            'end_date' => (new \DateTime($request->end_date))->format('Y-m-d H:i'),
            'activity_id' => $request->activity_id
        ]);

        if($request->membres)
        {
            foreach ($request->membres as $membre) {
                $the_user = new User();
                $the_user->setTable('users_student');
                $user= $the_user->find($membre);
                DB::connection('tenant')->table('gesttask_tache_user')->insert([
                    'tache_id' => $task->id,
                    'user_id' => $user->id
                ]);
                // $task->users()->attach($user->id);
            }
        }


        $project = Project::find($request->project_id);
        $tasks = Task::orderBy('id', 'ASC')->where('activity_id', $activity->id)->get();
        // $users = $project->users()->get();

        $username = $request->session()->get('username');
        $user_connected = DB::table('users_student')->where('username', $username)->first();

        $users = $this->getProjectUsers($project->id, $user_connected->idEtablissement);

        $activity_percentage = $this->compute_activity_percentage($tasks);
        $activity->update([
            'percentage' => (double) $activity_percentage,
            'statut' => $this->update_activity_status($activity_percentage, $activity)
        ]);

        $project_percentage = $this->compute_project_percentage($project->id);
        $project->update([
            'percentage' => (double) $project_percentage,
            'statut' => $this->update_project_status($project_percentage, $project)
        ]);

        return redirect()->route('list-task', [
            'project_id' => $activity->projet_id,
            'activity_id' => $activity->id
        ])->with([
            // 'activity'=> $activity,
            // 'project'=> $project,
            // 'tasks' => $tasks,
            // 'users' => $users,
            // 'user_connected' => $user_connected,
            'success'=> true,
            'message'=> trans('La tâche a bien été créée !'),
            //'statut' => trans('La tâche a bien été créée !')
        ]);
    }

    public function task_destroy(Request $request)
    {
        $task = Task::find($request->taskid);
        if($task->statut == "todo"){
            Task::destroy($request->taskid);

            $activity = Activity::find($request->activity_id);
            $project = Project::find($request->project_id);
            $tasks = Task::orderBy('id', 'ASC')->where('activity_id', $activity->id)->get();
            // $users = $project->users()->get();
            $username = $request->session()->get('username');
            $user_connected = DB::table('users_student')->where('username', $username)->first();
            $users = $this->getProjectUsers($project->id, $user_connected->idEtablissement);

            $activity_percentage = $this->compute_activity_percentage($tasks);
            $activity->update([
                'percentage' => (double) $activity_percentage,
                'statut' => $this->update_activity_status($activity_percentage, $activity)
            ]);

            $project_percentage = $this->compute_project_percentage($project->id);
            $project->update([
                'percentage' => (double) $project_percentage,
                'statut' => $this->update_project_status($project_percentage, $project)
            ]);

            return redirect()->route('list-task', [
                'project_id' => $activity->projet_id,
                'activity_id' => $activity->id
            ])->with([
                // 'activity'=> $activity,
                // 'project'=> $project,
                // 'tasks' => $tasks,
                // 'users' => $users,
                // 'user_connected' => $user_connected,
                'success'=> true,
                'message'=> trans('La tâche a bien été supprimée !'),
                //'statut' => trans('La tâche a bien été supprimée !')
            ]);
        }
        else{
            return redirect()->back()->with([
                'success'=> false,
                'message'=> trans('Vous ne pouvez pas supprimer cette tâche !'),
            ]);
        }

    }

    public function task_update(Request $request)
    {
        $task = Task::find($request->task_id);
        $activity = Activity::find($request->activity_id);

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'percentage' => 'required|numeric|min:0|max:100',
            'start_date' => ['required', 'date',  'after_or_equal:' .(new \DateTime($activity->start_date))->format('Y-m-d H:i'), 'before_or_equal:' .(new \DateTime($activity->end_date))->format('Y-m-d H:i')],
            'end_date' => ['required', 'date', 'after:start_date', 'before_or_equal:' .(new \DateTime($activity->end_date))->format('Y-m-d H:i')],

        ]);

        if($validator->fails())
        {
            return redirect()->back()->with([
                'success'=> false,
                'message'=> trans('Les champs ne sont pas bien remplis !'),
            ])->withErrors($validator);
        }


        $username = $request->session()->get('username');
        $user_connected = DB::table('users_student')->where('username', $username)->first();

        $task_users = $this->getTaskUsers($task->id, $user_connected->idEtablissement);

        foreach($task_users as $user) {
            // $task->users()->detach($user->id);
            $id_task_users = DB::connection('tenant')->table('gesttask_tache_user')->where([
                ['user_id', $user->id],
                ['tache_id', $task->id]
            ])->get();

            foreach($id_task_users as $id_task_user) {
                DB::connection('tenant')->table('gesttask_tache_user')->delete($id_task_user->id);
            }
        }

        if($request->membres)
        {
            foreach ($request->membres as $membre) {
                $the_user = new User();
                $the_user->setTable('users_student');
                $user= $the_user->find($membre);
                DB::connection('tenant')->table('gesttask_tache_user')
                                        ->insert([
                                            'user_id' => $user->id,
                                            'tache_id' => $task->id
                                        ]);
                // $task->users()->attach($user->id);
            }
        }
        //$success = '';
        //$erreur = '';
        $success = true;
        $message = '';

        $nbr_task_users = DB::connection('tenant')->table('gesttask_tache_user')->where('tache_id', $task->id)->count();

        if($nbr_task_users != 0)
        {
            $task->update([
                'name' => $request->name,
                'percentage' => (double) $request->percentage,
                'statut' => $this->update_task_status($request),
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'activity_id' => $request->activity_id
            ]);
            $success =true;
            $message ='La tâche a bien été mise à jour !';
            // dump($task);
        }
        elseif($task->percentage == $request->percentage)
        {

            $task->update([
                'name' => $request->name,
                'start_date' =>$request->start_date,
                'end_date' =>$request->end_date,
                'activity_id' => $request->activity_id
            ]);
            $success =true;
            $message ='La tâche a bien été mise à jour !';
        }
        else
        {
            $success =false;
            $message ='Veuillez affecter des utilisateurs à la tâche avant modification de son statut';
        }

        // dump($task);


        $project = Project::find($request->project_id);
        $tasks = Task::orderBy('id', 'ASC')->where('activity_id', $activity->id)->get();

        // dd($tasks);


        $users = $this->getProjectUsers($project->id, $user_connected->idEtablissement);
        // $users = $project->users()->get();

        $activity_percentage = $this->compute_activity_percentage($tasks);
        $activity->update([
            'percentage' => (double) $activity_percentage,
            'statut' => $this->update_activity_status($activity_percentage, $activity)
        ]);

        $project_percentage = $this->compute_project_percentage($project->id);
        $project->update([
            'percentage' => (double) $project_percentage,
            'statut' => $this->update_project_status($project_percentage, $project)
        ]);

        // dd($tasks);

        return redirect()->route('list-task', [
            'project_id' => $activity->projet_id,
            'activity_id' => $activity->id
        ])->with([
            // 'activity'=> $activity,
            // 'project'=> $project,
            // 'tasks' => $tasks,
            // 'users' => $users,
            // 'user_connected' => $user_connected,
            'success'=> $success,
            'message'=> trans($message),
            //'statut' => $success,
            //'erreur' => $erreur
        ]);
    }

    //Opérations sur les projets
    public function project_store(Request $request)
    {
        // dd($request);
        $this->validate($request, [
            'name' => 'required',
            'description' => 'required',
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date'],
        ]);

        $username = $request->session()->get('username');
        $user = new User();
        $user->setTable('users');
        $user_connected = $user->where('username', $username)->first();
        if (empty($user_connected)) {
            // $user_connected = DB::table('users_student')->where('username', $username)->first();
            $user->setTable('users_student');
            $user_connected = $user->where('username', $username)->first();
            if(empty($user_connected)) {
                return redirect()->back()->with([
                    'success'=> false,
                    'message'=> trans('Les informations de l\'utilisateur n\'ont pas été trouvées !'),
                ]);
            }
        }

        // dd($user_connected);

        $project = Project::create([
            'name' => $request->name,
            'description' => $request->description,
            'statut' => 'new',
            'percentage' => 0.0,
            'start_date' => (new \DateTime($request->start_date))->format('Y-m-d H:i'),
            'end_date' => (new \DateTime($request->end_date))->format('Y-m-d H:i'),
            'user_id' => $user_connected->id
        ]);
        sleep(2);
        return redirect()->route('projects');
    }

    public function project_update (Request $request)
    {
        // dd($request);
        $project = Project::find($request->project_id);
        // dd($project);

        $this->validate($request, [
            'name' => 'required',
            'description' => 'required',
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date', 'after:start_date'],
        ]);

        $project->update([
            'name' => $request->name,
            'description' => $request->description,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date
        ]);

        return redirect()->route('projects');
    }

    public function project_destroy(Request $request)
    {
        Project::destroy($request->project_id);
        return redirect()->back()->with([
            'success'=> true,
            'message'=> trans('Le projet a été supprimé avec succès'),
        ]);

    }

    // public function evolution (Request $request)
    // {
    //     $project = Projet::find($request->id);
    //     return view('project-evolution',compact('projet'));
    // }

    // private function synchronise(Request $request)
    // {
    //     if ($request->percentage == 100)
    //     {
    //         $request->statut = 'done';
    //     }
    //     elseif ($request->percentage < 100 &&
    //         Carbon::createFromFormat('Y-m-d', $request->end_date)->lt(now()->format('Y-m-d')))
    //     {
    //         $request->statut = 'late';
    //     }
    //     elseif ($request->percentage == 0)
    //     {
    //         $request->statut = 'todo';
    //     }
    //     else
    //     {
    //         $request->statut = 'doing';
    //     }
    // }

    public function getDate($date){
        $months = [
            "Janvier",
            "Fevrier",
            "Mars",
            "Avril",
            "Mai",
            "Juin",
            "Juillet",
            "Août",
            "Septembre",
            "Octobre",
            "Novembre",
            "Décembre"
        ];

        $dateTable = explode('-', $date);

        return $dateTable[2] . ' ' . $months[(int)$dateTable[1] - 1] . ' ' . $dateTable[0];

    }

    private function getProjectUsers($project_id, $idEtablissement)
    {
        $users = DB::table('users_student')->where('idEtablissement', $idEtablissement)->get();
        $_project_users = DB::connection('tenant')
                                ->table('gesttask_projet_user')
                                ->where('projet_id', $project_id)
                                ->get('user_id');
        $user_ids = [];
        foreach ($_project_users as $_project_user) {
            $user_ids[] = $_project_user->user_id;
        }
        $project_users = [];
        foreach ($users as $user) {
            if(in_array($user->id, $user_ids)) {
                $user->photo = DB::connection('tenant')->table('tabetudiant')->where('matricule', $user->matricule)->first()->cheminPhoto;
                $project_users[] = $user;
            }
        }

        return $project_users;
    }

    private function getTaskUsers($task_id, $idEtablissement)
    {
        $users = DB::table('users_student')->where('idEtablissement', $idEtablissement)->get();
        $id_task_users = DB::connection('tenant')
                            ->table('gesttask_tache_user')
                            ->where('tache_id', $task_id)
                            ->get('user_id');
        $user_ids = [];
        foreach ($id_task_users as $id_task_user) {
            $user_ids[] = $id_task_user->user_id;
        }
        $task_users = [];
        foreach ($users as $user) {
            if(in_array($user->id, $user_ids)) {
                $user->photo = DB::connection('tenant')->table('tabetudiant')->where('matricule', $user->matricule)->first()->cheminPhoto;
                $task_users[] = $user;
            }
        }
        return $task_users;
    }

    private function compute_activity_percentage($tasks)
    {

        $activity_percentage = 0;
        $duration_sum = 0;

        foreach ($tasks as $task)
        {
            $date1 = new DateTime($task->start_date);
            $date2 = new DateTime($task->end_date);
            $diff = $date1->diff($date2);
            $duration = $diff->days * 24 + $diff->h + $diff->i/60;
            // $duration = (double) $date1->diff($date2)->format('%a');
            $duration_sum += $duration;
            $activity_percentage += $task->percentage * $duration;
        }

        if ($duration_sum == 0) {
            return $activity_percentage;
        } else {
            $activity_percentage = (int) round($activity_percentage / $duration_sum, 0);
            return $activity_percentage;
        }
    }

    private function compute_project_percentage($project_id)
    {

        $activities = Activity::where('projet_id',$project_id)->get();
        $project_percentage = 0;
        $duration_sum = 0;

        foreach ($activities as $activity)
        {
            $date1 = new DateTime($activity->start_date);
            $date2 = new DateTime($activity->end_date);
            $diff = $date1->diff($date2);
            $duration = $diff->days * 24 + $diff->h + $diff->i/60;
            // $duration = (double) $date1->diff($date2)->format('%a');
            $duration_sum += $duration;
            $project_percentage += $activity->percentage * $duration;
        }

        if ($duration_sum == 0) {
            return $project_percentage;
        } else {
            $project_percentage = (int) round($project_percentage / $duration_sum, 0);
            return $project_percentage;
        }
    }

    private function update_task_status(Request $request)
    {
        if ($request->percentage == 100)
        {
            return 'done';
        }
        elseif ($request->percentage < 100 &&
            Carbon::createFromFormat('Y-m-d', explode('T', $request->end_date)[0])->lt(now()->format('Y-m-d')))
        {
            return 'late';
        }
        elseif ($request->percentage == 0)
        {
            return 'todo';
        }
        else
        {
            return 'doing';
        }
    }

    private function update_activity_status($activity_percentage, $activity)
    {
        if ($activity_percentage == 100)
        {
            return 'ended';
        }
        elseif ($activity_percentage < 100 &&
            Carbon::createFromFormat('Y-m-d', explode(' ', $activity->end_date)[0])->lt(now()->format('Y-m-d')))
        {
            return 'late';
        }
        elseif ($activity->tasks()->count() > 0)
        {
            foreach ($activity->tasks as $task)
            {
                if ($task->statut == 'late')
                {
                    return 'late';
                }
            }
            if ($activity_percentage == 0)
            {
                return 'new';
            }
            else
            {
                return 'progress';
            }
        }
        else
        {
            return 'new';
        }
    }

    private function update_project_status($project_percentage, $project)
    {
        if ($project_percentage == 100)
        {
            return 'ended';
        }
        elseif ($project_percentage < 100 &&
            Carbon::createFromFormat('Y-m-d', explode(' ', $project->end_date)[0])->lt(now()->format('Y-m-d')))
        {
            return 'late';
        }
        elseif ($project->activities()->count() > 0)
        {
            foreach ($project->activities as $activity)
            {
                if ($activity->statut == 'late')
                {
                    return 'late';
                }
            }
            if ($project_percentage == 0)
            {
                return 'new';
            }
            else
            {
                return 'waiting';
            }
        }
        else
        {
            return 'new';
        }
    }


    private static function get_user_agent(){
        return $_SERVER['HTTP_USER_AGENT'];
    }

    protected static function get_ip(){

    $ipaddress = '';
       if (isset($_SERVER['HTTP_CLIENT_IP']))
           $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
       else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
           $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
       else if(isset($_SERVER['HTTP_X_FORWARDED']))
           $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
       else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
           $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
       else if(isset($_SERVER['HTTP_FORWARDED']))
           $ipaddress = $_SERVER['HTTP_FORWARDED'];
       else if(isset($_SERVER['REMOTE_ADDR']))
           $ipaddress = $_SERVER['REMOTE_ADDR'];
       else
           $ipaddress = 'UNKNOWN';
       return $ipaddress;

    }

    protected static function get_os(){

        $user_agent = self::get_user_agent();
        $os_platform = "Unknown OS Platform";
        $os_array = array(
            '/windows nt 10/i'  => 'Windows 10',
            '/windows nt 6.3/i'  => 'Windows 8.1',
            '/windows nt 6.2/i'  => 'Windows 8',
            '/windows nt 6.1/i'  => 'Windows 7',
            '/windows nt 6.0/i'  => 'Windows Vista',
            '/windows nt 5.2/i'  => 'Windows Server 2003/XP x64',
            '/windows nt 5.1/i'  => 'Windows XP',
            '/windows xp/i'  => 'Windows XP',
            '/windows nt 5.0/i'  => 'Windows 2000',
            '/windows me/i'  => 'Windows ME',
            '/win98/i'  => 'Windows 98',
            '/win95/i'  => 'Windows 95',
            '/win16/i'  => 'Windows 3.11',
            '/macintosh|mac os x/i' => 'Mac OS X',
            '/mac_powerpc/i'  => 'Mac OS 9',
            '/linux/i'  => 'Linux',
            '/ubuntu/i'  => 'Ubuntu',
            '/iphone/i'  => 'iPhone',
            '/ipod/i'  => 'iPod',
            '/ipad/i'  => 'iPad',
            '/android/i'  => 'Android',
            '/blackberry/i'  => 'BlackBerry',
            '/webos/i'  => 'Mobile',
        );

        foreach ($os_array as $regex => $value){
            if(preg_match($regex, $user_agent)){
                $os_platform = $value;
            }
        }
        return $os_platform;
    }

    protected static function get_browsers(){

        $user_agent= self::get_user_agent();

        $browser = "Unknown Browser";

        $browser_array = array(
            '/msie/i'  => 'Internet Explorer',
            '/Trident/i'  => 'Internet Explorer',
            '/firefox/i'  => 'Firefox',
            '/safari/i'  => 'Safari',
            '/chrome/i'  => 'Chrome',
            '/edge/i'  => 'Edge',
            '/opera/i'  => 'Opera',
            '/netscape/'  => 'Netscape',
            '/maxthon/i'  => 'Maxthon',
            '/knoqueror/i'  => 'Konqueror',
            '/ubrowser/i'  => 'UC Browser',
            '/mobile/i'  => 'Safari Browser',
        );

        foreach($browser_array as $regex => $value){
            if(preg_match($regex, $user_agent)){
                $browser = $value;
            }
        }
        return $browser;
    }

    protected static function get_device(){

        $tablet_browser = 0;
        $mobile_browser = 0;

        if(preg_match('/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i', strtolower($_SERVER['HTTP_USER_AGENT']))){
            $tablet_browser++;
        }

        if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile)/i', strtolower($_SERVER['HTTP_USER_AGENT']))){
            $mobile_browser++;
        }

        if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),
        'application/vnd.wap.xhtml+xml')> 0) or
            ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or
                isset($_SERVER['HTTP_PROFILE'])))){
                    $mobile_browser++;
        }

            $mobile_ua = strtolower(substr(self::get_user_agent(), 0, 4));
            $mobile_agents = array(
                'w3c','acs-','alav','alca','amoi','audi','avan','benq','bird','blac','blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
                'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-','maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',

                'newt','noki','palm','pana','pant','phil','play','port','prox','qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',

                'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-','tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
                'wapr','webc','winw','winw','xda','xda-');

                if(in_array($mobile_ua,$mobile_agents)){
                    $mobile_browser++;
                }

                if(strpos(strtolower(self::get_user_agent()),'opera mini') > 0){
                    $mobile_browser++;

                    //Check for tables on opera mini alternative headers

                    $stock_ua =
                    strtolower(isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA'])?
                    $_SERVER['HTTP_X_OPERAMINI_PHONE_UA']:
                    (isset($_SERVER['HTTP_DEVICE_STOCK_UA'])?
                    $_SERVER['HTTP_DEVICE_STOCK_UA']:''));

                    if(preg_match('/(tablet|ipad|playbook)|(android(?!.*mobile))/i', $stock_ua)){
                        $tablet_browser++;
                    }
                }

                if($tablet_browser > 0){
                    //do something for tablet devices

                    return 'Tablet';
                }
                else if($mobile_browser > 0){
                    //do something for mobile devices

                    return 'Mobile';
                }
                else{
                    //do something for everything else
                        return 'Computer';
                }

    }



}



