<?php

namespace App\Controllers;


use App\Models\Usuarios\UserModel;

class Profile extends BaseController
{

    function __construct()
    {

    }

    public function index()
    {

        $data['breadcrumb'] = [
            ['title' => lang("App.menu_dashboard"), 'route' => "/home", 'active' => false],
            ['title' => lang("App.profile_title"), 'route' => "", 'active' => true]
        ];

        // Get the User Provider (UserModel by default)
        $users = auth()->getProvider();

        // Find by the user_id
        $data['obj'] = $users->findById(auth()->id());

        echo view(getenv('theme.path') . 'form/profile/profileDetails', $data);

    }

    public function store()
    {
        $session = session();
        helper('form');

        $rules = [
            'first_name' => 'required',
            'last_name' => 'required',
            'new_pwd' => 'permit_empty|min_length[8]',
            'new_pwd_confirm' => 'required_with[new_pwd]|matches[new_pwd]'
        ];

        // Definir los mensajes de error personalizados
        $rules_error = [
            'first_name' => ['required' => lang("App.profile_rules_first_name_r")],
            'last_name' => ['required' => lang("App.profile_rules_last_name_r")],
            'new_pwd' => ['min_length' => lang("App.profile_rules_password_m")],
            'new_pwd_confirm' => [
                'matches' => lang("App.profile_rules_password_confirm_m")
            ]
        ];

        // Validar la entrada
        if (!$this->validate($rules, $rules_error)) {
            // Si la validación falla, redirigir de vuelta con errores
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        // Obtener los valores de los campos
        $firstName = $this->request->getPost('first_name');
        $lastName = $this->request->getPost('last_name');
        $newPwd = $this->request->getPost('new_pwd');

        $update_data = [
            'first_name' => $firstName,
            'last_name' => $lastName,
            'password' => $newPwd,
        ];

        if(empty($newPwd)){
            unset($update_data['password']);
        }

        // Aquí debes obtener el usuario actual, por ejemplo, desde la sesión
        $users = auth()->getProvider();
        $user = $users->findById(auth()->id());
        $user->fill($update_data);
        $users->save($user);

        // Redirigir con un mensaje de éxito
        return redirect()->back()->with('success', lang('App.profile_updated_successfully'));

    }
}
