<?php
namespace App\Controllers\Auth;
use App\Controllers\BaseController;

class AuthController extends BaseController
{
    public function login()
    {
        if (session()->get('user_id')) return redirect()->to('/');
        return $this->view('auth/login', ['error' => session()->getFlashdata('error'), 'success' => session()->getFlashdata('success')]);
    }

    public function doLogin()
    {
        // Rate limiting — max 5 attempts per 10 minutes per IP
        $cache    = \Config\Services::cache();
        $ip       = $this->request->getIPAddress();
        $attempts = $cache->get("login_attempts_{$ip}") ?? 0;
        if ($attempts >= 5) {
            return redirect()->to('/fieldly/public/index.php/login')->with('error', 'Too many login attempts. Please wait 10 minutes.');
        }

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

        if (!$email || !$password) {
            return redirect()->to('/fieldly/public/index.php/login')->with('error', 'Email and password are required.');
        }

        $db   = db_connect();
        $user = $db->table('users')
                   ->where('email', $email)
                   ->where('status', 'active')
                   ->where('deleted_at IS NULL', null, false)
                   ->get()->getRowArray();

        if (!$user || !password_verify($password, $user['password_hash'])) {
            $cache->save("login_attempts_{$ip}", $attempts + 1, 600);
            return redirect()->to('/fieldly/public/index.php/login')->with('error', 'Invalid email or password.');
        }

        // Clear rate limit on success
        $cache->delete("login_attempts_{$ip}");

        $permissions = array_column(
            $db->table('role_permissions')->where('role_id', $user['role_id'])->get()->getResultArray(),
            'permission'
        );

        $settings = model('CompanySettingModel')->getAllForCompany($user['company_id']);

        $sessionUser = $user;
        unset($sessionUser['password_hash'], $sessionUser['password_reset_token']);

        session()->set([
            'user_id'       => $user['id'],
            'company_id'    => $user['company_id'],
            'user'          => $sessionUser,
            'permissions'   => $permissions,
            'settings'      => $settings,
            'last_activity' => time(),
        ]);

        $db->table('users')->where('id', $user['id'])->update(['last_login_at' => date('Y-m-d H:i:s')]);

        $redirect = session()->getFlashdata('redirect_url') ?? '/';
        return redirect()->to($redirect);
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/fieldly/public/index.php/login')->with('success', 'You have been logged out.');
    }

    public function forgotPassword()
    {
        if ($this->request->getMethod() === 'post') {
            $email = trim($this->request->getPost('email'));
            $db    = db_connect();
            $user  = $db->table('users')->where('email', $email)->where('status','active')->get()->getRowArray();

            if ($user) {
                $token = bin2hex(random_bytes(32));
                $db->table('users')->where('id', $user['id'])->update([
                    'password_reset_token' => hash('sha256', $token),
                    'password_reset_at'    => date('Y-m-d H:i:s'),
                ]);
                // TODO: send email with link: /reset-password/{$token}
            }
            return redirect()->to('/fieldly/public/index.php/login')->with('success', 'If that email exists, a reset link has been sent.');
        }
        return $this->view('auth/forgot');
    }

    public function resetPassword(string $token)
    {
        $db   = db_connect();
        $user = $db->table('users')
                   ->where('password_reset_token', hash('sha256', $token))
                   ->where('password_reset_at >', date('Y-m-d H:i:s', strtotime('-1 hour')))
                   ->get()->getRowArray();

        if (!$user) return redirect()->to('/fieldly/public/index.php/login')->with('error', 'Invalid or expired reset link.');
        return $this->view('auth/reset', ['token' => $token]);
    }

    public function doResetPassword()
    {
        $token    = $this->request->getPost('token');
        $password = $this->request->getPost('password');
        $confirm  = $this->request->getPost('confirm');

        if ($password !== $confirm) return redirect()->back()->with('error', 'Passwords do not match.');
        if (strlen($password) < 8)  return redirect()->back()->with('error', 'Password must be at least 8 characters.');

        $db   = db_connect();
        $user = $db->table('users')
                   ->where('password_reset_token', hash('sha256', $token))
                   ->where('password_reset_at >', date('Y-m-d H:i:s', strtotime('-1 hour')))
                   ->get()->getRowArray();

        if (!$user) return redirect()->to('/fieldly/public/index.php/login')->with('error', 'Invalid or expired reset link.');

        $db->table('users')->where('id', $user['id'])->update([
            'password_hash'        => password_hash($password, PASSWORD_DEFAULT),
            'password_reset_token' => null,
            'password_reset_at'    => null,
        ]);

        return redirect()->to('/fieldly/public/index.php/login')->with('success', 'Password updated. Please log in.');
    }
}
