<?php

namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;
use App\Models\UserModel;

class AuthApi extends ResourceController
{
    public function login()
    {
        $userModel = new UserModel();
        $db = \Config\Database::connect();
        
        $username  = $this->request->getVar('username');
        $password  = $this->request->getVar('password');

        if (!$username || !$password) {
            return $this->fail('Username dan password wajib diisi', 400);
        }

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

        if ($user && password_verify($password, $user['password'])) {
            // Log ke tabel login_logs
            $db->table('login_logs')->insert([
                'id_user'    => $user['id_user'],
                'ip_address' => $this->request->getIPAddress(),
                'browser'    => $this->request->getUserAgent()->getAgentString()
            ]);

            return $this->respond([
                'status'  => 200,
                'message' => 'Login berhasil',
                'data'    => [
                    'id_user'      => $user['id_user'],
                    'nama_lengkap' => $user['nama_lengkap'],
                    'token'        => bin2hex(random_bytes(32)) // Harap ganti dengan library JWT di production
                ]
            ]);
        }
        return $this->failUnauthorized('Username atau password salah.');
    }
}