<?php

namespace App\Controllers;

use App\Models\UserModel;

class Auth extends BaseController
{
    public function login()
    {
        if ($this->session->has('user')) {
            return $this->redirectByRole($this->session->get('user')['role']);
        }

        return view('auth/login', [
            'title' => 'Login POS Barber',
        ]);
    }

    public function attemptLogin()
    {
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');
        $role = $this->request->getPost('role');

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

        $defaultUsers = [
            'owner' => ['username' => 'owner', 'password' => 'owner123', 'name' => 'Owner Barber', 'role' => 'owner'],
            'cashier' => ['username' => 'kasir', 'password' => 'kasir123', 'name' => 'Kasir Barber', 'role' => 'cashier'],
        ];

        $defaultUser = $defaultUsers[$role] ?? null;

        if ($user && password_verify($password, $user['password'])) {
            $this->session->set('user', [
                'id' => $user['id'],
                'name' => $user['name'],
                'role' => $user['role'],
                'username' => $user['username'],
            ]);

            return $this->redirectByRole($user['role']);
        }

        if ($defaultUser && $defaultUser['username'] === $username && $defaultUser['password'] === $password) {
            $this->session->set('user', [
                'id' => 0,
                'name' => $defaultUser['name'],
                'role' => $defaultUser['role'],
                'username' => $defaultUser['username'],
            ]);

            return $this->redirectByRole($defaultUser['role']);
        }

        return view('auth/login', [
            'title' => 'Login POS Barber',
            'error' => 'Kredensial salah atau role tidak sesuai.',
        ]);
    }

    public function logout()
    {
        $this->session->remove('user');
        $this->session->destroy();

        return redirect()->to('/login');
    }

    private function redirectByRole(string $role)
    {
        if ($role === 'owner') {
            return redirect()->to('/owner');
        }

        return redirect()->to('/cashier');
    }
}
