<?php

namespace App\Controllers;

use App\Models\UserModel;

class Auth extends BaseController
{
    protected $userModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
    }

    public function login()
    {
        if ($this->request->getMethod(true) === 'POST') {
            $username = trim((string)$this->request->getPost('username'));
            $password = (string)$this->request->getPost('password');

            if ($username === '' || $password === '') {
                session()->setFlashdata('error', 'Username and password are required.');
                return redirect()->to('/login')->withInput();
            }

            $db = \Config\Database::connect();
            $user = $db->table('users')
                ->where('username', $username)
                ->orWhere('email', $username)
                ->limit(1)
                ->get()
                ->getRowArray();

            if ($user && password_verify($password, $user['password_hash'] ?? '')) {
                if (($user['status'] ?? 1) != 1) {
                    session()->setFlashdata('error', 'Account is disabled.');
                    return redirect()->to('/login')->withInput();
                }
                $this->setUserSession($user);

                if ($user['role'] === 'admin') {
                    return redirect()->to('/admin');
                } elseif ($user['role'] === 'agent') {
                    return redirect()->to('/agent');
                }
                return redirect()->to('/');
            }

            session()->setFlashdata('error', 'Invalid username or password.');
            return redirect()->to('/login')->withInput();
        }

        if ($this->isLoggedIn()) {
            $user = $this->currentUser();
            if (($user['role'] ?? '') === 'admin') {
                return redirect()->to('/admin');
            } elseif (($user['role'] ?? '') === 'agent') {
                return redirect()->to('/agent');
            }
        }

        return view('auth/login');
    }

    public function register()
    {
        if ($this->request->getMethod(true) === 'POST') {
            $rules = [
                'username'  => 'required|min_length[3]|is_unique[users.username]',
                'email'     => 'required|valid_email|is_unique[users.email]',
                'password'  => 'required|min_length[6]',
                'full_name' => 'required',
            ];

            if (!$this->validate($rules)) {
                return view('auth/register', [
                    'errors' => $this->validator->getErrors(),
                ]);
            }

            $userData = [
                'username'      => $this->request->getPost('username'),
                'email'         => $this->request->getPost('email'),
                'password_hash' => password_hash((string)$this->request->getPost('password'), PASSWORD_DEFAULT),
                'full_name'     => $this->request->getPost('full_name'),
                'role'          => 'agent',
                'status'        => 1,
            ];

            $db = \Config\Database::connect();
            $db->table('users')->insert($userData);

            session()->setFlashdata('success', 'Registration successful. You can now log in.');
            return redirect()->to('/login');
        }

        if ($this->isLoggedIn()) {
            $user = $this->currentUser();
            if ($user['role'] === 'admin') {
                return redirect()->to('/admin');
            } elseif ($user['role'] === 'agent') {
                return redirect()->to('/agent');
            }
        }

        return view('auth/register');
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/login');
    }
}
