<?php namespace App\Controllers\Api;

use App\Controllers\BaseApiController;
use App\Models\UserModel;
use Firebase\JWT\JWT;

class AuthController extends BaseApiController
{
    public function login()
    {
        $throttler = service('throttler');

        $ip = $this->request->getIPAddress();
        $key = 'login-attempt-' . md5($ip);

        if (! $throttler->check($key, 5, MINUTE)) {
            return $this->respondError(429, 'TooManyRequests',
                'Too many attempts, please try again in 60 seconds.',
                ['retry_after' => 60]
            );
        }

        helper('form');
        $rules = [
            'user_id'  => 'required',
            'password' => 'required|min_length[8]'
        ];

        if (! $this->validate($rules)) {
            return $this->respondError(400, 'ValidationError',
                'Invalid input.',
                $this->validator->getErrors()
            );
        }

        $m = new UserModel();
        $user = $m->where('user_id', $this->request->getPost('user_id'))->first();

        if (! $user) {
            return $this->respondError(401, 'Unauthorized', 'Invalid credentials.');
        }

        if (!empty($user['locked_until']) && strtotime($user['locked_until']) > time()) {
            $remaining = (strtotime($user['locked_until']) - time()) / 60;
            return $this->respondError(423, 'Locked', 'Account locked. Try again in ' . ceil($remaining) . ' minutes.');
        }

         if (! password_verify($this->request->getPost('password'), $user['password'])) {
            // Increment failed attempts
            $m->update($user['id'], [
                'failed_attempts' => $user['failed_attempts'] + 1,
                'locked_until' => ($user['failed_attempts'] + 1 >= 5)
                    ? date('Y-m-d H:i:s', strtotime('+15 minutes')) : null,
            ]);

            return $this->respondError(401, 'Unauthorized', 'Invalid credentials.');
        }

         $m->update($user['id'], [
            'failed_attempts' => 0,
            'locked_until' => null
        ]);

        session()->regenerate();
        

        $payload = [
            'iat' => time(),
            'exp' => time() + 3600 * 24, // 24 hours
            'sub' => $user['id'],
            'user_id' => $user['user_id'],
            'name' => $user['name'],
        ];

        $secretKey = getenv('JWT_SECRET') ?: 'your_jwt_secret_key_here';

        $token = JWT::encode($payload, $secretKey, 'HS256');
        session()->set([
            'jwt_token' => $token,
            'user_id' => $user['id'],
        ]);

        return $this->respond([
            'status' => 200,
            'message' => 'Login successful.',
            'token' => $token,
            'user' => [
                'id' => $user['id'],
                'name' => $user['name'],
                'user_id' => $user['user_id'],
            ]
        ]);
    }




    public function logout()
    {
        session()->destroy();
        return $this->respond(['status' => 200, 'message' => 'Logged out.']);
    }

}
