<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Usergroup;
use App\Models\Programme;
use App\Models\Structure;
use App\Models\ResponsableStructure;
use App\Models\ResponsableProgramme;
use App\Models\Pointfocal;
use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function index() { 
	/*	$users = User::with('usergroup')->get();
        return view('users.index', compact('users')); */
        try {
            $users = User::with('usergroup')->get();
            return view('users.index', compact('users'));
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Erreur lors du chargement des utilisateurs : ' . $e->getMessage());
        }
	}
  public function create()
    {
 /*$usergroups = Usergroup::all(); 
    return view('users.create', compact('usergroups'));
        return view('users.create');*/
         try {
            $usergroups = Usergroup::all();
            return view('users.create', compact('usergroups'));
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Erreur lors du chargement du formulaire de création : ' . $e->getMessage());
        }
    }


     public function show($id)
    {
        $user = User::with('usergroup')->findOrFail($id);
        return view('users.show', compact('user'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
            'usergroup_id' => 'required|integer|exists:usergroups,id',
        ]);
        /*$data['password'] = bcrypt($data['password']);
         User::create($data);
 return redirect()->route('users.index')->with('success', 'Utilisateur ajouté avec succès.');*/
 


        try {
            $validated['password'] = bcrypt($validated['password']);
            $user = new User($validated);
            if ($user->save()) {
                return redirect()->route('users.index')->with('success', 'Utilisateur ajouté avec succès.');
            } else {
                return redirect()->back()->with('error', 'Échec de l’ajout de l’utilisateur.');
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return redirect()->back()->withErrors($e->validator)->withInput();
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Erreur lors de l’ajout de l’utilisateur : ' . $e->getMessage());
        }
    }

    public function update(Request $request, $id)
    {
        $user = User::findOrFail($id);

            $validated = $request->validate([
                'name' => 'sometimes|string|max:255',
                'email' => 'sometimes|email|unique:users,email,' . $id,
                'password' => 'nullable|string|min:6',
                'usergroup_id' => 'sometimes|integer|exists:usergroups,id',
            ]);
            
       /* if(isset($data['password'])) { $data['password'] = bcrypt($data['password']); }
        $user->update($data);
         return redirect()->route('users.index')->with('success', 'Utilisateur modifié avec succès.');*/
         
          try {
           

            if (isset($validated['password'])) {
                $validated['password'] = bcrypt($validated['password']);
            }

            if ($user->update($validated)) {
                return redirect()->route('users.index')->with('success', 'Utilisateur modifié avec succès.');
            } else {
                return redirect()->back()->with('error', 'Échec de la mise à jour de l’utilisateur.');
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return redirect()->back()->withErrors($e->validator)->withInput();
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return redirect()->route('users.index')->with('error', 'Utilisateur introuvable.');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Erreur lors de la mise à jour : ' . $e->getMessage());
        }
    }
	public function edit($id)
    {
      /* $user = User::findOrFail($id);
    $usergroups = Usergroup::all();
    return view('users.edit', compact('user', 'usergroups'));*/
    try {
            $user = User::findOrFail($id);
            $usergroups = Usergroup::all();
            return view('users.edit', compact('user', 'usergroups'));
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return redirect()->route('users.index')->with('error', 'Utilisateur introuvable.');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Erreur lors du chargement du formulaire d’édition : ' . $e->getMessage());
        }
        
    }

    public function destroy($id) { 
	/*User::findOrFail($id)->delete(); 
	 return redirect()->route('users.index')->with('success', 'Utilisateur supprimé avec succès.');*/
   
    try {
            $user = User::findOrFail($id);
            if ($user->delete()) {
                return redirect()->route('users.index')->with('success', 'Utilisateur supprimé avec succès.');
            } else {
                return redirect()->back()->with('error', 'Échec de la suppression de l’utilisateur.');
            }
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return redirect()->route('users.index')->with('error', 'Utilisateur introuvable.');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Erreur lors de la suppression : ' . $e->getMessage());
        }
	 }
	public function actif($id)
    {
       /* $user = User::findOrFail($id);
        $user->is_active = !$user->is_active;
        $user->save();

        return redirect()->route('users.index')->with('success', 'État de l\'utilisateur mis à jour.');*/
        
        try {
            $user = User::findOrFail($id);
            $user->is_active = !$user->is_active;
            $user->save();

            return redirect()->route('users.index')->with('success', 'État de l’utilisateur mis à jour.');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return redirect()->route('users.index')->with('error', 'Utilisateur introuvable.');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Erreur lors de la mise à jour de l’état : ' . $e->getMessage());
        }
        
        
    }
	public function rpcreate($level, $id)
    {
        //$users = User::with('usergroup')->get();
		
		if($level == "program"){
			$users = User::whereHas('usergroup', function ($query) {$query->where('code', 'RP');})->where('is_rp', false)->with('usergroup')->get();
			//dd("PR"); die();
			return view('users.rpcreate', compact('users', 'level', 'id'));
		}
		if($level == "respstruct"){
			$users = User::whereHas('usergroup', function ($query) {$query->where('code', 'RS');})->where('is_rs', false)->with('usergroup')->get();
			//dd("RS"); die();
			return view('users.rpcreate', compact('users', 'level', 'id'));
		}
		if($level == "ptfocal"){
			$users = User::whereHas('usergroup', function ($query) {$query->where('code', 'PF');})->where('is_pf', false)->with('usergroup')->get();
			//dd($level); die();
			return view('users.rpcreate', compact('users', 'level', 'id'));
		}
    }
	
	public function rpadd($level, $levelid, $userid)
    {
		if($level == "program"){
			$programme = Programme::with('user')->findOrFail($levelid);
			$oldrp = $programme->user_id;
			if($oldrp == $userid){
				return redirect()->route('programmes.show', $levelid)->with('success', 'Mise à jour effectuée.');
			}
			$programme->user_id = $userid;
			$resprog = ResponsableProgramme::where('programme_id', $levelid)->orderBy('id', 'desc')->first();
			
			if($programme->save()){
				//mettre fin au mandat de l'ancien
				if(isset($resprog)){
					$resprog->datefin = now();
					$resprog->save();
					
					$user = User::find($resprog->user_id);
					$user->is_rp = false;
					$user->save();
				}
				// enregistrer le nouveau
				$programme = Programme::with('user')->findOrFail($levelid);
				$resprog = new ResponsableProgramme();
				$resprog->programme_id = $levelid;
				$resprog->user_id = $userid;
				$resprog->programme = $programme->code.' : '.$programme->nom;
				$resprog->user = $programme->user->name.' ('. $programme->user->email. ')';
				$resprog->datedebut = now();
				$resprog->save();
				
				$user = User::find($userid);
				$user->is_rp = true;
				$user->save();
			};
			
			return redirect()->route('programmes.show', $levelid)->with('success', 'Mise à jour effectuée.');
		}
		
		if($level == "respstruct"){
			$structure = Structure::with('responsable')->findOrFail($levelid);
			$oldrespstruct = $structure->responsablestructure_id;
			if($oldrespstruct == $userid){
				return redirect()->route('structures.show', $levelid)->with('success', 'Mise à jour effectuée.');
			}
			$structure->responsablestructure_id = $userid;
			//$resprog = ResponsableProgramme::where('programme_id', $levelid)->orderBy('id', 'desc')->first();
			$respstructure = ResponsableStructure::where('structure_id', $levelid)->orderBy('id', 'desc')->first();
			
			if($structure->save()){
				//mettre fin au mandat de l'ancien
				if(isset($respstructure)){
					$respstructure->datefin = now();
					$respstructure->save();
					
					$user = User::find($respstructure->user_id);
					$user->is_rs = false;
					$user->save();
				}
				// enregistrer le nouveau
				$structure = Structure::with('responsable')->findOrFail($levelid);
				$respstructure = new ResponsableStructure();
				$respstructure->structure_id = $levelid;
				$respstructure->user_id = $userid;
				$respstructure->structure = $structure->code.' : '.$structure->nom;
				$respstructure->responsable = $structure->responsable->name.' ('. $structure->responsable->email. ')';
				$respstructure->datedebut = now();
				$respstructure->save();
				
				$user = User::find($userid);
				$user->is_rs = true;
				$user->save();
			};
			
			return redirect()->route('structures.show', $levelid)->with('success', 'Mise à jour effectuée.');
		}
		
		if($level == "ptfocal"){
			$structure = Structure::with('pointfocal')->findOrFail($levelid);
			$oldpf = $structure->pointfocal_id;
			if($oldpf == $userid){
				return redirect()->route('structures.show', $levelid)->with('success', 'Mise à jour effectuée.');
			}
			$structure->pointfocal_id = $userid;
			$pf = Pointfocal::where('structure_id', $levelid)->orderBy('id', 'desc')->first();
			
			if($structure->save()){
				//mettre fin au mandat de l'ancien
				if(isset($pf)){
					$pf->datefin = now();
					$pf->save();
					
					$user = User::find($pf->user_id);
					$user->is_pf = false;
					$user->save();
				}
				// enregistrer le nouveau
				$structure = Structure::with('pointfocal')->findOrFail($levelid);
				$pf = new Pointfocal();
				$pf->structure_id = $levelid;
				$pf->user_id = $userid;
				$pf->structure = $structure->code.' : '.$structure->nom;
				$pf->pointfocal = $structure->pointfocal->name.' ('. $structure->pointfocal->email. ')';
				$pf->datedebut = now();
				$pf->save();
				
				$user = User::find($userid);
				$user->is_rs = true;
				$user->save();
			};
			
			return redirect()->route('structures.show', $levelid)->with('success', 'Mise à jour effectuée.');
		}
    }
}

