<?php

namespace App\Controllers\Api;

use App\Models\UserModel;

class AuthController extends BaseApiController
{
    public function login()
    {
        $input = $this->getJsonInput();

        $username = trim($input['username'] ?? '');
        $password = $input['password'] ?? '';

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

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

        if (!$user || !password_verify($password, $user['password'])) {
            return $this->respondError('Username atau password salah', 401);
        }

        if ($user['status'] !== 'aktif') {
            return $this->respondError('User tidak aktif', 403);
        }

        // JWT
        $token = generateJWT([
            'id_user'  => $user['id_user'],
            'username' => $user['username'],
            'role'     => $user['role']
        ]);

        // ✅ LOG LOGIN (PASTI MASUK DB)
        logAktivitas($user['id_user'], 'Login ke sistem');

        return $this->respondSuccess([
            'token' => $token,
            'user'  => [
                'id_user' => $user['id_user'],
                'nama'    => $user['nama'],
                'role'    => $user['role']
            ]
        ], 'Login berhasil');
    }
}