<?php

namespace App\Http\Controllers\Parametres;

use App\Http\Controllers\Controller;
use App\Models\Action;
use App\Models\ActionUniteOeuvre;
use App\Models\Thematique;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RespSocEnvController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:see_parametre')->only(['index']);
        $this->middleware('permission:edit_parametre')->only(['update']);
    }

    /**
     * Retourne toutes les thématiques de la strcuture avec leurs actions
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function index()
    {
        $thematiques = Thematique::where('structure_id', Auth::user()->structure_id)->get();
        $actions_unite_oeuvre = ActionUniteOeuvre::all();
        $has_action = false;
        foreach ($thematiques as $t) {
            if (sizeof($t->actions) > 0) {
                $has_action = true;
                break;
            }
        }
        return view('parametres.resp-soc-env.index', [
            'thematiques' => $thematiques,
            'actions_unite_oeuvre' => $actions_unite_oeuvre,
            'has_action' => $has_action,
        ]);
    }

    /**
     * Permet de mettre à jour la visibilité des actions d'une structure
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request)
    {
        // On récupère tous les ids des actions qui ont été cochés dans le formulaire
        $action_id_checked = array_keys($request->except(['_token', '_method', '_structure_id']));
        $structure_id = Auth::user()->structure_id;

        //On maj toutes les actions qui ne sont pas checked pour les rendre non visibles
        // TODO Se rappeler que si on hide une action, on ne supprime pas cette action de la table Projets_actions_resp_soc_env
        Action::join('thematiques', 'actions.thematique_id', '=', 'thematiques.id')
                ->where('thematiques.structure_id', $structure_id)
                ->whereNotIn('actions.id', $action_id_checked)
                ->update(['visible' => 0]);

        //On maj toutes les actions qui sont checked pour les rendre visibles
        Action::join('thematiques', 'actions.thematique_id', '=', 'thematiques.id')
            ->where('thematiques.structure_id', $structure_id)
            ->whereIn('actions.id', $action_id_checked)
            ->update(['visible' => 1]);

        return redirect()->route('resp-soc-env.index')->with('success', 'Les modifications ont bien été prises en compte.');
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response
     */
    public function action_unite_oeuvre_create()
    {
        return view('parametres.resp-soc-env.action_unite_oeuvre.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function action_unite_oeuvre_store(Request $request)
    {
        $request->validate([
            'libelle' => 'required|string|max:255'
        ]);

        $action_unite_oeuvre = ActionUniteOeuvre::create([
            'libelle' => $request->libelle
        ]);

        if ($action_unite_oeuvre->id) {
            return redirect()->route('resp-soc-env.index')->with('success', 'Unité d\'oeuvre ajoutée avec succès.');
        } else {
            abort(500);
        }
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response
     */
    public function action_unite_oeuvre_edit($id)
    {
        $action_unite_oeuvre = ActionUniteOeuvre::find($id);
        if (isset($action_unite_oeuvre)) {
            return view('parametres.resp-soc-env.action_unite_oeuvre.edit', [
                'action_unite_oeuvre' => $action_unite_oeuvre
            ]);
        } else {
            abort(404);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function action_unite_oeuvre_update(Request $request, $id)
    {
        $request->validate([
            'libelle' => 'required|string|max:255'
        ]);

        $action_unite_oeuvre = ActionUniteOeuvre::find($id);
        if (isset($action_unite_oeuvre)) {
            $action_unite_oeuvre->update([
                'libelle' => $request->libelle
            ]);

            return redirect()->route('resp-soc-env.index')->with('success', 'Unité d\'oeuvre mise à jour avec succès.');
        } else {
            abort(404);
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function action_unite_oeuvre_destroy($id)
    {
        $action_unite_oeuvre = ActionUniteOeuvre::find($id);
        if (isset($action_unite_oeuvre)) {
            $action_unite_oeuvre->delete();
            return redirect()->route('resp-soc-env.index')->with('success', 'Unité d\'oeuvre supprimée avec succès.');
        } else {
            abort(404);
        }
    }
}
