<?php 

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use Firebase\JWT\JWT;
use App\Models\PenggunaModel;
use App\Models\SiswaModel;

class AuthController extends ResourceController
{
    public function login()
    {
        $userModel = new PenggunaModel();
        $siswaModel = new SiswaModel(); // Tambahan untuk ambil data siswa

        $username = $this->request->getVar('username');
        $password = $this->request->getVar('password');

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

        if (!$user) {
            return $this->respond(['message' => 'Username tidak ada'], 401);
        }

        if (!password_verify($password, $user['password'])) {
            return $this->respond(['message' => 'Password Salah'], 401);
        }

        $key = getenv('JWT_SECRET');
        $payload = [
            'iss' => 'localhost',
            'aud' => 'localhost',
            'iat' => time(),
            'exp' => time() + 3600,
            'uid' => $user['id'],
            'username' => $user['username'],
            'role' => $user['role']
        ];

        $token = JWT::encode($payload, $key, 'HS256');

        $response = [
            'token' => $token,
            'user' => [
                'id' => $user['id'],
                'username' => $user['username'],
                'role' => $user['role']
            ]
        ];

        // Jika role siswa, tambahkan data siswa dari tabel siswa
        if ($user['role'] === 'siswa') {
            $siswa = $siswaModel->where('username', $user['username'])->first();
            if ($siswa) {
                $response['siswa'] = $siswa;
            } else {
                // Optional: beri warning jika username tidak cocok dengan data siswa
                $response['siswa'] = null;
            }
        }

        return $this->respond($response);
    }
}