<?php

namespace App\Controllers;

use App\Models\Groups;

class GroupController extends AdminController
{
    public function __construct()
    {
        parent::__construct();   
        // Assuming permission is being set from a session
        helper(['form', 'url']);
    }

    private $pageTitle = 'Groups';

    public function index()
    {
        $this->verifyRole('viewGroup');
        $data['page_title'] = $this->pageTitle;

        $Groups = new Groups();
        $data['groups_data'] = $Groups->getGroupData();

        return $this->render_template('groups/index', $data);
    }

    public function create()
    {
        $this->verifyRole('createGroup');
        $data['page_title'] = $this->pageTitle;

        $validation = \Config\Services::validation();

        // Set validation rules
        $validation->setRules([
            'group_name' => [
                'label' => 'Group name',
                'rules' => 'required',
                'errors' => [
                    'required' => 'The {field} field is required.'
                ]
            ]
        ]);

        // Check if form validation is successful
        if ($this->request->getMethod() == 'post') {

            if ($validation->withRequest($this->request)->run()) {

                $permission = serialize($this->request->getPost('permission'));
                $data = [
                    'group_name' => $this->request->getPost('group_name'),
                    'permission' => $permission
                ];
                
                $groupsModel = new Groups(); // Load Groups model
                $create = $groupsModel->createGroup($data);
                // die(var_dump($create));

                if ($create) {
                    session()->setFlashdata('success', 'Creation réussie');
                    return redirect()->to('/groups');
                } else {
                    session()->setFlashdata('errors', 'Une erreur est survenue !!');
                    return redirect()->to('/groups/create');
                }    
            } else {
                // If validation fails, load the form with validation errors
                $data['validation'] = $validation;

                return $this->render_template('groups/create', $data); // Render the create view
            }
            
        } else {

            return $this->render_template('groups/create', $data); // Render the create view
        }
    }

    public function edit($id = null)
    {
        $this->verifyRole('updateGroup');
        $data['page_title'] = $this->pageTitle;

        $groupsModel = new Groups();

        if ($id) {
            // Set validation rules
            $validation = \Config\Services::validation();
            $validation->setRules([
                'group_name' => 'required',
            ]);

            if ($this->request->getMethod() === 'post') {

                if ($validation->withRequest($this->request)->run()) {
                    // Validation passed
                    $permission = serialize($this->request->getPost('permission'));
    
                    $data = [
                        'group_name' => $this->request->getPost('group_name'),
                        'permission' => $permission,
                    ];
                    // die(var_dump($groupsModel->editGroup($data, $id)));
                    // Update group
                    if ($groupsModel->editGroup($data, $id)) {
                        session()->setFlashdata('success', 'Mise à jour réussie');
                        return redirect()->to('/groups');
                    } else {
                        session()->setFlashdata('errors', 'Une erreur est survenue !!');
                        return redirect()->to("/groups/edit/{$id}");
                    }
                } else {
                    // If validation fails, load the form with validation errors
                    $data['validation'] = $validation;
    
                    return $this->render_template('groups/create', $data); // Render the create view
                }
                
            } else {
                // Validation failed or no POST request
                $groupData = $groupsModel->find($id); // Fetch group data
                if (!$groupData) {
                    session()->setFlashdata('errors', 'Group pas trouver!');
                    return redirect()->to('/groups');
                }

                $data['group_data'] = $groupData;
                // die(var_dump($data));
                return $this->render_template('groups/edit', $data);
            }
        } else {
            session()->setFlashdata('errors', 'Group ID ne correspond pas!');
            return redirect()->to('/groups');
        }
    }

    public function delete(int $id = null)
{
    $this->verifyRole('deleteGroup');
    $data['page_title'] = $this->pageTitle;
    $groupsModel = new Groups();

    if (!$id) {
        session()->setFlashdata('error', 'Invalid Group ID!');
        return redirect()->to('/groups');
    }

    // Vérifier si c'est une requête POST avec confirmation
    if ($this->request->getMethod() === 'post' && $this->request->getPost('confirm')) {
        
        // Supprimer d'abord toutes les associations dans user_group
        $groupsModel->removeUsersFromGroup($id);
        
        // Puis supprimer le groupe
        if ($groupsModel->deleteGroup($id)) {
            session()->setFlashdata('success', 'Rôle supprimé avec succès');
            return redirect()->to('/groups');
        } else {
            session()->setFlashdata('error', 'Une erreur est survenue lors de la suppression!');
            return redirect()->to('/groups');
        }
    }
    
    // Si ce n'est pas une requête POST, rediriger vers la liste
    session()->setFlashdata('error', 'Action non autorisée!');
    return redirect()->to('/groups');
}

}