<?php
namespace App\Controllers\Api;

use Core\Controller;
use App\Models\ApiMaba;
use App\Models\ApiToken;

class MabaController extends Controller
{
    public function index()
    {
        // cek token
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? '';
        if (!preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            http_response_code(401);
            echo json_encode(['error' => true, 'message' => 'Unauthorized']);
            exit;
        }
        $token = $matches[1];

        $tokenModel = new ApiToken();
        if (!$tokenModel->isValid($token)) {
            http_response_code(401);
            echo json_encode(['error' => true, 'message' => 'Token expired or invalid']);
            exit;
        }

        // ambil tahun masuk dari query
        $tahun = isset($_GET['tahun']) ? preg_replace('/[^0-9]/','',$_GET['tahun']) : null;
        if (!$tahun) {
            http_response_code(400);
            echo json_encode(['error' => true, 'message' => 'Parameter tahun wajib diisi']);
            exit;
        }

        $mahasiswaModel = new ApiMaba();
        $data = $mahasiswaModel->getByTahun($tahun);

        header('Content-Type: application/json');
        echo json_encode(['error' => false, 'tahun' => $tahun, 'data' => $data]);
        exit;
    }
}
