<?php
define('FCPATH', __DIR__ . DIRECTORY_SEPARATOR);
chdir(__DIR__ . '/../');
require 'system/bootstrap.php';
$app = \Config\Services::codeigniter();
$app->initialize();

$neo = new \App\Services\NeoFeederService();
$res = $neo->request('GetMatkulKurikulum');

$mataKuliahModel = new \App\Models\MataKuliahModel();
$kurikulumModel = new \App\Models\KurikulumModel();

$kurikulumData = $kurikulumModel->findAll();
$kurikulumMap = [];
foreach ($kurikulumData as $k) {
    $kurikulumMap[$k['id_kurikulum_pddikti']] = $k['id'];
}

$updated = 0;
if (isset($res['error_code']) && $res['error_code'] == 0 && isset($res['data'])) {
    foreach ($res['data'] as $pddikti) {
        $idMatkul = $pddikti['id_matkul'] ?? '';
        $pddiktiIdKurikulum = $pddikti['id_kurikulum'] ?? '';
        $localIdKurikulum = isset($kurikulumMap[$pddiktiIdKurikulum]) ? $kurikulumMap[$pddiktiIdKurikulum] : null;
        $semesterTingkat = $pddikti['semester'] ?? $pddikti['semester_tingkat'] ?? null;

        if (!empty($idMatkul)) {
            $mataKuliahModel->where('id_matkul_pddikti', $idMatkul)
                ->set(['id_kurikulum' => $localIdKurikulum, 'semester' => $semesterTingkat])
                ->update();
            $updated++;
        }
    }
}
echo "Updated $updated matkul records";
