<?php

require_once __DIR__ . '/../../../config/bootstrap_cross_auth.php';

 $token = getBearerToken();
if (!$token) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Akses ditolak. Token tidak ditemukan.']);
    exit;
}

 $token_hash = hash('sha256', $token);
 $stmtToken = $pdo->prepare("SELECT user_id, role FROM auth_tokens WHERE token_hash = ? AND expires_at > UTC_TIMESTAMP()");
 $stmtToken->execute([$token_hash]);
 $auth_data = $stmtToken->fetch();

if (!$auth_data || $auth_data['role'] !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Akses ditolak. Hanya Admin.']);
    exit;
}

try {
    $keyword = isset($_GET['search']) ? $_GET['search'] : '';
    $id_kelas = isset($_GET['id_kelas']) ? intval($_GET['id_kelas']) : 0;
    $status = isset($_GET['status']) ? $_GET['status'] : 'aktif'; 

    $sql = "
        SELECT 
            s.id_siswa, 
            s.nisn, 
            s.nama_siswa, 
            s.email,
            s.id_kelas, 
            s.id_rombel,
            s.jenis_kelamin,
            s.no_telepon,
            s.alamat,
            s.status,
            s.role, 
            k.nama_kelas, 
            r.nama_rombel
        FROM siswa s 
        LEFT JOIN kelas k ON s.id_kelas = k.id_kelas
        LEFT JOIN rombel r ON s.id_rombel = r.id_rombel
    ";
    
    $where = [];
    $params = [];

    
    if ($status !== '' && $status !== 'semua') {
        $where[] = "s.status = ?";
        $params[] = $status;
    }

    if ($id_kelas > 0) {
        $where[] = "s.id_kelas = ?";
        $params[] = $id_kelas;
    }

    if (!empty($keyword)) {
        $where[] = "(s.nisn LIKE ? OR s.nama_siswa LIKE ?)";
        $searchTerm = "%" . $keyword . "%";
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }

    if (!empty($where)) {
        $sql .= " WHERE " . implode(' AND ', $where);
    }

    $sql .= " ORDER BY k.id_kelas ASC, s.nama_siswa ASC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $data
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
}