<?php
namespace App\Controllers;

use App\Models\UserModel;

class AuthController extends BaseController
{
    public function login()
    {
        if (session()->get('user_id')) {
            return redirect()->to('/dashboard');
        }
        return view('auth/login');
    }

    /*public function authenticate()
    {
        $validation = \Config\Services::validation();
        $validation->setRules([
            'username' => 'required',
            'password' => 'required'
        ]);

        if (!$validation->withRequest($this->request)->run()) {
            return redirect()->back()->withInput()->with('errors', $validation->getErrors());
        }

        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

        $userModel = new UserModel();
        $user = $userModel->where('username', $username)->first();

        if ($user && password_verify($password, $user['password'])) {
            session()->set([
                'user_id'  => $user['id_usuario'],
                'username' => $user['username'],
                'role'     => $user['id_rol'] == 1 ? 'admin' : 'vendedor'
            ]);
            return redirect()->to('/dashboard')->with('success', 'Bienvenido ' . $user['username']);
        }

        return redirect()->back()->with('error', 'Usuario o contrasena incorrectos');
    }*/
    public function authenticate()
    {
        $validation = \Config\Services::validation();
        $validation->setRules([
            'email'    => 'required|valid_email',
            'password' => 'required'
        ]);

        if (!$validation->withRequest($this->request)->run()) {
            return redirect()->back()->withInput()->with('errors', $validation->getErrors());
        }

        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $userModel = new UserModel();
        $user = $userModel->where('email', $email)->first();

        if ($user && password_verify($password, $user['password'])) {
            session()->set([
                'user_id'  => $user['id_usuario'],
                'username' => $user['username'],
                'role'     => $user['id_rol'] == 1 ? 'admin' : 'vendedor'
            ]);
            return redirect()->to('/dashboard')->with('success', 'Bienvenido ' . $user['username']);
        }

        return redirect()->back()->with('error', 'Email o contrasena incorrectos');
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/login')->with('success', 'Sesion cerrada correctamente');
    }
}
