<?php
namespace App\Controllers\Api;

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

class ApiKrsController extends Controller
{
    public function index()
    {
        header('Content-Type: application/json');

        // 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 invalid/expired']);
            exit;
        }

        // Ambil Data
        $krsModel = new ApiKrs();
        $tahun = isset($_GET['tahun']) ? $_GET['tahun'] : $krsModel->getTahunAktif();
        if (!$tahun) {
            http_response_code(400);
            echo json_encode(['error' => true, 'message' => 'Parameter tahun_akademik tidak ditemukan']);
            exit;
        }

        $data = $krsModel->getData($tahun);
        echo json_encode([
            'error' => false,
            'tahun_akademik' => $tahun,
            'jumlah' => count($data),
            'data' => $data
        ]);
        exit;
    }
}
