<?php

namespace App\Controllers;

use App\Models\Groups;
use App\Models\Users;
use App\Models\Stores;
use Config\Services;

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

    /**
     * title of the page
     * @var string
     */
    private $pageTitle = 'User';
    private $pageTitle2 = 'Profile';

    /**
     * get all users
     */
    public function index()
    {
        $this->verifyRole('viewUser');

        $Users = new Users();
        $userData = $Users->getUserData();
        $result = [];
        $Stores = new Stores();
        foreach ($userData as $key => $value) {
            if (is_numeric($value['store_id']))
                $value['store_id'] = $value['store_id'] == 0 ? "TOUS"  : $Stores->getStoresData($value['store_id'])["name"];
            $result[$key]['user_info'] = $value;
            $group = $Users->getUserGroup($value['id']);

            $result[$key]['user_group'] = $group;
        }

        $data['user_data'] = $result;

        $session = session();
        $usersSession = $session->get('user');
        $data['groupName'] = $usersSession['group_name']; 

        // die(var_dump($usersSession['group_name']));
        $data['page_title'] = $this->pageTitle;
        $data['stores'] = $Stores->getActiveStore();

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

    public function fetchUserData()
{
    $this->verifyRole('viewUser');

    try {
        $Users = new Users();
        $userData = $Users->getUserData();
        $result = [];
        $Stores = new Stores();

        foreach ($userData as $key => $value) {
            $buttons = '';

            if (in_array('updateUser', $this->permission)) {
             $buttons .= '<button type="button" class="btn btn-default" onclick="editFunc(' . $value['id'] . ')">'
          . '<i class="fa fa-pencil"></i>'
          . '</button>';

            }

            if (in_array('deleteUser', $this->permission)) {
            $buttons .= ' <button type="button" '
                . 'class="btn btn-danger" '
                . 'data-toggle="modal" '
                . 'data-target="#removeModal" '
                . 'data-id="' . $value['id'] . '">'
                . '<i class="fa fa-trash"></i>'
                . '</button>';
            }
           if (in_array('viewProfile', $this->permission)) {
                $buttons .= ' <button 
                    type="button" 
                    class="btn btn-success" data-toggle="modal" 
                 data-target="#profileModal" 
                    onclick="profileFunc(' . $value['id'] . ')" 
                    title="Voir le profil">
                    <i class="fa fa-user"></i>
                </button>';
            }



            if (in_array('viewUser', $this->permission)) {
                $buttons .= ' <button type="button" class="btn btn-info" onclick="loginFunc(' . $value['id'] . ')"><i class="fa fa-chevron-right"></i></button>';
            }

            if (in_array('assignerUser', $this->permission)) {
             $buttons .= '<button type="button" class="btn btn-info" onclick="assignFunc(' . $value['id'] . ')">
                    <i class="fa fa-cog"></i>
                </button>';
            }
           $group_data = $Users->getUserWithGroupName($value['id']);
        //    die(var_dump($group_data['group_name']));
            $result[] = [
                $value['firstname'],
                $value['lastname'],
                $value['email'],
                $value['phone'],
                $Stores->getStoresName($value['store_id']),
                $group_data['group_name'],
                $buttons
            ];
        }

        return $this->response->setJSON(['data' => $result]);

    } catch (\Exception $e) {
        return $this->response->setJSON([
            'data' => [],
            'error' => true,
            'message' => 'Erreur lors de la récupération des données utilisateur : ' . $e->getMessage()
        ]);
    }
}

    public function assign_store()
    {
        // Vérifie que la requête est bien une requête AJAX
        if (!$this->request->isAJAX()) {
            $response = Services::response();
            $response->setStatusCode(404, 'Page Not Found')->send();
            exit;
        }

        // Récupère les données POST sous format JSON
        $user_id = $this->request->getPost('user_id');
        $store_id = $this->request->getPost('store_id');
        $Users = new Users();

        if (!isset($user_id) || !isset($store_id)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Paramètres manquants.'
            ])->setStatusCode(400);
        }

        $user_id1 = $user_id;
        $store_id1 = $store_id;

        $usersModel = new Users();
        // die(var_dump([$user_id, $store_id]));
        // Appeler la méthode assignToStore pour mettre à jour la base de données
        $result = $usersModel->assignToStore($user_id1, $store_id1);

        // Répondre en JSON avec le résultat
        if ($result) {
            return $this->response->setJSON(['success' => true, 'message' => 'Mise è jour réusit.']);
        } else {
            return $this->response->setJSON(['success' => false, 'message' => 'Échec de la mise à jour.']);
        }
    }


    public function create()
    {
        //         ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);

        $this->verifyRole('createUser');
        // Define validation rules
        $validationRules = [
            'groups' => [
                'label' => 'Group',
                'rules' => 'required'
            ],
            'username' => [
                'label' => 'Username',
                'rules' => 'required|trim|min_length[5]|is_unique[users.username]'
            ],
            'email' => [
                'label' => 'Email',
                'rules' => 'required|trim|valid_email|is_unique[users.email]'
            ],
            'password' => [
                'label' => 'Password',
                'rules' => 'required|trim|min_length[8]'
            ],
            'cpassword' => [
                'label' => 'Confirm Password',
                'rules' => 'required|trim|matches[password]'
            ],
            'fname' => [
                'label' => 'First Name',
                'rules' => 'required|trim'
            ]
        ];

        $Groups = new Groups();
        $Users = new Users();
        $data['page_title'] = $this->pageTitle;

        // Check if it's a POST request before validating
        if ($this->request->getMethod() === 'post') {
            // Load validation service and run validation
            if (!$this->validate($validationRules)) {

                // Validation failed, load view with errors
                $groupData = $Groups->getGroupData(); // Assuming model_groups is loaded
                $data['group_data'] = $groupData;
                $data['validation'] = $this->validator; // Pass validation instance to the view
                $Stores = new Stores();
                $data['stores'] = $Stores->getActiveStore();

                return $this->render_template('users/create', $data);
            }

            // Validation passed, process form data
            $password = $this->passwordHash($this->request->getPost('password')); // Update hashing logic if needed

            $data = [
                'username' => $this->request->getPost('username'),
                'password' => $password,
                'email' => $this->request->getPost('email'),
                'firstname' => $this->request->getPost('fname'),
                'lastname' => $this->request->getPost('lname'),
                'phone' => $this->request->getPost('phone'),
                'gender' => $this->request->getPost('gender'),
                'store_id' => $this->request->getPost('store'),
            ];

            $create = $Users->create($data, $this->request->getPost('groups'));

            if ($create) {
                // Success
                return redirect()->to('/users')->with('success', 'Successfully created');
            } else {
                // Error
                return redirect()->to('/users/create')->with('error', 'Error occurred!!');
            }
        }
        $Stores = new Stores();

        // If it's not a POST request, just render the create page with no validation errors
        $groupData = $Groups->getGroupData();
        $data['group_data'] = $groupData;
        $data['stores'] = $Stores->getActiveStore();
        return $this->render_template('users/create', $data);
    }


    public function passwordHash($pass = '')
    {
        if ($pass) {
            $password = password_hash($pass, PASSWORD_DEFAULT);
            return $password;
        }
    }

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

        $validation = \Config\Services::validation();
        $usersModel = new Users();
        $groupsModel = new Groups();

        // Define validation rules
        $validationRules = [
            'groups' => 'required',
            'username' => 'required|trim|min_length[5]|max_length[12]',
            'email' => 'required|trim|valid_email',
            'fname' => 'required|trim',
        ];

        // Check if the ID exists in the request
        if ($id) {
            // Check if it's a POST request before validating
            if ($this->request->getMethod() === 'post') {
                // Validate the form
                if (!$this->validate($validationRules)) {
                    // Validation failed
                    $data['validation'] = $validation;
                    $data['user_data'] = $usersModel->getUserData($id);
                    $data['user_group'] = $usersModel->getUserGroup($id);
                    $data['group_data'] = $groupsModel->getGroupData();
                    return $this->render_template('users/edit', $data);
                }

                // If password is empty, skip password validation
                $password = '';
                if ($this->request->getPost('password') && $this->request->getPost('cpassword')) {
                    $validation->setRule('password', 'Password', 'required|min_length[8]');
                    $validation->setRule('cpassword', 'Confirm Password', 'required|matches[password]');

                    if (!$this->validate($validationRules)) {
                        // Validation failed for password
                        $data['validation'] = $validation;
                        $data['user_data'] = $usersModel->getUserData($id);
                        $data['user_group'] = $usersModel->getUserGroup($id);
                        $data['group_data'] = $groupsModel->getGroupData();
                        return $this->render_template('users/edit', $data);
                    }
                    $password = password_hash($this->request->getPost('password'), PASSWORD_DEFAULT); // Hash the password
                }

                // Prepare user data for update
                $data = [
                    'username' => $this->request->getPost('username'),
                    'password' => $password ?: $this->request->getPost('password'), // If no new password, keep the old one
                    'email' => $this->request->getPost('email'),
                    'firstname' => $this->request->getPost('fname'),
                    'lastname' => $this->request->getPost('lname'),
                    'phone' => $this->request->getPost('phone'),
                    'gender' => $this->request->getPost('gender'),
                ];

                $groupId = $this->request->getPost('groups');

                // Update user
                $update = $usersModel->edit($data, $id, $groupId);

                if ($update) {
                    session()->setFlashdata('success', 'Successfully updated');
                    return redirect()->to('/users');
                } else {
                    session()->setFlashdata('errors', 'Error occurred!');
                    return redirect()->to("/users/edit/{$id}");
                }
            }

            // If it's not a POST request (initial load), load user data
            $data['user_data'] = $usersModel->getUserData($id);
            $data['user_group'] = $usersModel->getUserGroup($id);
            $data['group_data'] = $groupsModel->getGroupData();

            return $this->render_template('users/edit', $data);
        }

        // If no ID is provided, you can handle the error or redirect
        return redirect()->to('/users');
    }


// supression utilisateur


    public function delete($id)
    {
        $this->verifyRole('deleteUser');
    
        if (!$id) {
            return $this->response->setJSON(['success' => false, 'message' => 'ID manquant']);
        }
    
        $usersModel = new Users();
        $delete = $usersModel->delete($id);
    
        if ($delete) {
            return $this->response->setJSON(['success' => true, 'message' => 'Supprimé avec succès']);
        } else {
            return $this->response->setJSON(['success' => false, 'message' => 'Échec de la suppression']);
        }
    }

    public function profile()
    {
        $this->verifyRole('viewProfile');
        $user = session()->get('user');
        $userId = $user['id'];

        $Users = new Users();
        $Store = new Stores();
        $data['user_data'] = $Users->getUserData($userId);
        $data['store_name']= $Store->getStoreById($data['user_data']['store_id']);
        $data['page_title'] = $this->pageTitle2;
        $data['user_group'] = $Users->getUserGroup($userId);

        return $this->render_template('users/profile', $data);
    }

    public function setting()
    {
        $this->verifyRole('updateSetting');
        $user = session()->get('user');
        $userId = $user['id'];

        if ($userId) {
            $validation = \Config\Services::validation();

            // Set validation rules
            $validation->setRules([
                'username' => 'required|trim|min_length[5]|max_length[12]',
                'email'    => 'required|trim|valid_email',
                'fname'    => 'required|trim',
            ]);
            $Users = new Users();
            // If validation passes for the first set of rules
            if ($this->request->getMethod() === 'post' && $validation->withRequest($this->request)->run()) {
                // Handle the case when password is not being updated
                if (empty($this->request->getPost('password')) && empty($this->request->getPost('cpassword'))) {

                    $data = [
                        'username'   => $this->request->getPost('username'),
                        'email'      => $this->request->getPost('email'),
                        'firstname'  => $this->request->getPost('fname'),
                        'lastname'   => $this->request->getPost('lname'),
                        'phone'      => $this->request->getPost('phone'),
                        'gender'     => $this->request->getPost('gender'),
                    ];
                    $update = $Users->update($userId, $data);
                    // die(var_dump($update));

                    if ($update) {
                        return redirect()->to('/users/setting')->with('success', 'Successfully updated');
                    } else {
                        return redirect()->back()->with('errors', 'Error occurred!')->withInput();
                    }
                } else {
                    // Additional validation for password
                    $validation->setRules([
                        'password'  => 'required|min_length[8]',
                        'cpassword' => 'required|matches[password]',
                    ]);

                    if ($validation->withRequest($this->request)->run()) {
                        $password = password_hash($this->request->getPost('password'), PASSWORD_DEFAULT);

                        $data = [
                            'username'   => $this->request->getPost('username'),
                            'password'   => $password,
                            'email'      => $this->request->getPost('email'),
                            'firstname'  => $this->request->getPost('fname'),
                            'lastname'   => $this->request->getPost('lname'),
                            'phone'      => $this->request->getPost('phone'),
                            'gender'     => $this->request->getPost('gender'),
                        ];

                        $update = $Users->update($userId, $data);

                        if ($update) {
                            return redirect()->to('/users/setting')->with('success', 'Successfully updated');
                        } else {
                            return redirect()->back()->with('errors', 'Error occurred!')->withInput();
                        }
                    } else {
                        // Handle validation errors for password
                        return redirect()->back()->with('errors', $validation->getErrors())->withInput();
                    }
                }
            } else {

                $userData = $Users->find($userId);

                $groupModel = new Groups(); // Assuming you have a GroupModel
                $groups = $groupModel->findAll();

                $data = [
                    'user_data' => $userData,
                    'group_data' => $groups,
                    'validation' => $validation->getErrors(),
                    'page_title' => 'Paramètre',
                ];

                return $this->render_template('users/setting', $data);
            }
        }
    }

    public function loginToOtherAccount(int $id)
    {
        $Users = new Users();

        $userInfo = $Users->getUserData($id);

        $email = $userInfo['email'];
        $password = $userInfo['password'];
        $user = $Users->attempt($email, $password, "connected_inside");
        // die(var_dump($user));

        if ($user) {
            // Set user session
            session()->set('user', $user);
            // Redirect to dashboard
            return redirect()->to('/');
        }
    }

    public function fetchProfile($id)
    {
        $this->verifyRole('viewProfile');

        $Users = new Users();
        $Store = new Stores();

        $user_data = $Users->getUserData($id);
        if (!$user_data) {
            return $this->response->setStatusCode(404)->setBody('Utilisateur introuvable');
        }

        $store_name = $Store->getStoreById($user_data['store_id']);
        $user_group = $Users->getUserGroup($id);

        $data =[
            'user_data'   => $user_data,
            'store_name'  => $store_name,
            'user_group'  => $user_group
        ];
        return $this->response->setJSON([$data]);
    }

    public function fetchUserForAssign()
{
    if (!$this->request->isAJAX()) {
        return $this->response->setStatusCode(404)->setJSON(['message' => 'Requête invalide']);
    }

    $user_id = $this->request->getPost('user_id');
    $userModel = new Users();
    $storeModel = new Stores();

    $user = $userModel->getUserDataForAssign($user_id);
    $stores = $storeModel->getAllStores();

    if (!$user) {
        return $this->response->setJSON(['success' => false, 'message' => 'Utilisateur introuvable']);
    }

    return $this->response->setJSON([
        'success' => true,
        'user' => [
            'id' => $user['id'],
            'name' => $user['firstname'] . ' ' . $user['lastname'],
            'role' => $user['group_name'],
            'current_store' => $user['store_name'],
        ],
        'stores' => $stores
    ]);
}


}
