<?php namespace App\Controllers;

use App\Models\UserModel;

class Auth extends BaseController
{
    public function login()
    {
        helper('form');
        $session = session();
        if ($this->request->getMethod() === 'post') {
            $identity = $this->request->getPost('identity'); // username or email
            $password = $this->request->getPost('password');

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

            if ($user && password_verify($password, $user['password'])) {
                $session->set('user_id', $user['id']);
                $session->set('user_role', $user['role']);
                $session->set('user_name', $user['name']);
                if ($user['role'] === 'admin') {
                    return redirect()->to('/admin/dashboard');
                }
                return redirect()->to('/user/dashboard');
            }
            return redirect()->back()->with('error','Invalid credentials')->withInput();
        }
        echo view('auth/login');
    }

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

    // login by loan uid (for convenience; production needs OTP)
    public function loginByLoanUid()
    {
        if ($this->request->getMethod() !== 'post') return redirect()->to('/login');
        $loanUid = $this->request->getPost('loan_uid');
        $db = \Config\Database::connect();
        $loan = $db->table('loans')->where('loan_uid', $loanUid)->get()->getRowArray();
        if (!$loan) return redirect()->back()->with('error','Loan not found');
        $user = $db->table('users')->where('id', $loan['user_id'])->get()->getRowArray();
        if (!$user) return redirect()->back()->with('error','User for loan not found');
        session()->set('user_id', $user['id']);
        session()->set('user_role', $user['role']);
        session()->set('user_name', $user['name']);
        return redirect()->to('/user/dashboard')->with('success','Logged in by loan id');
    }
}
