<?php
// api/endpoints/login_post.php
if (empty($body['username']) || empty($body['password'])) {
    respond(['status' => 'error', 'message' => 'Username dan password wajib diisi'], 400);
}

$username = trim($body['username']);
$password = trim($body['password']);

// Coba login dari tabel ADMIN dulu
$stmt = $pdo->prepare("SELECT id, nama_lengkap AS nama, username, password, role FROM admin WHERE username = ? LIMIT 1");
$stmt->execute([$username]);
$admin = $stmt->fetch();

if ($admin) {
    $valid = false;
    if (password_verify($password, $admin['password'])) $valid = true;
    elseif (md5($password) === $admin['password'])       $valid = true;
    elseif ($password === $admin['password'])             $valid = true;

    if (!$valid) {
        respond(['status' => 'error', 'message' => 'Username atau password salah'], 401);
    }
    respond([
        'status' => 'success',
        'data'   => [
            'id'       => (string)$admin['id'],
            'nama'     => $admin['nama'],
            'username' => $admin['username'],
            'role'     => 'admin',
            'token'    => bin2hex(random_bytes(32)),
            'siswaId'  => '',
            'nis'      => '',
            'kelas'    => '',
            'jurusan'  => '',
        ]
    ]);
}

// Coba login dari tabel USERS
try {
    $stmt = $pdo->prepare("
        SELECT u.id, u.username, u.password, u.role, u.nama, u.siswa_id, u.is_active,
               s.kelas, s.jurusan, s.nis
        FROM users u
        LEFT JOIN siswa s ON u.siswa_id = s.id
        WHERE u.username = ?
        LIMIT 1
    ");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
} catch (PDOException $e) {
    respond(['status' => 'error', 'message' => 'Username atau password salah'], 401);
}

if (!$user) {
    respond(['status' => 'error', 'message' => 'Username atau password salah'], 401);
}

if (!(int)$user['is_active']) {
    respond(['status' => 'error', 'message' => 'Akun dinonaktifkan'], 401);
}

$valid = false;
if (password_verify($password, $user['password'])) $valid = true;
elseif (md5($password) === $user['password'])       $valid = true;
elseif ($password === $user['password'])             $valid = true;

if (!$valid) {
    respond(['status' => 'error', 'message' => 'Username atau password salah'], 401);
}

$isAdmin = $user['role'] === 'admin';

respond([
    'status' => 'success',
    'data'   => [
        'id'       => (string)$user['id'],
        'nama'     => $user['nama'],
        'username' => $user['username'],
        'role'     => $user['role'],
        'token'    => bin2hex(random_bytes(32)),
        'siswaId'  => $isAdmin ? '' : (string)($user['siswa_id'] ?? ''),
        'nis'      => $isAdmin ? '' : ($user['nis'] ?? $user['username']),
        'kelas'    => $isAdmin ? '' : ($user['kelas'] ?? ''),
        'jurusan'  => $isAdmin ? '' : ($user['jurusan'] ?? ''),
    ]
]);