<?php
namespace App\Controllers\Api;

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

class ApiMkController 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 parameter id_kurikulum (opsional)
        $idKurikulum = isset($_GET['id_kurikulum']) ? (int) $_GET['id_kurikulum'] : null;

        // Ambil Data
        $mkModel = new ApiMk();
        $data = $mkModel->getData($idKurikulum);

        echo json_encode([
            'error' => false,
            'jumlah' => count($data),
            'data' => $data
        ]);
        exit;
    }
}
