<?php
$conn = new mysqli('localhost', 'root', '', 'siakad');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch PDDIKTI settings
$res = $conn->query("SELECT * FROM pengaturan WHERE pengaturan_key IN ('pddikti_url', 'pddikti_username', 'pddikti_password')");
$settings = [];
while ($row = $res->fetch_assoc()) {
    $settings[$row['pengaturan_key']] = $row['pengaturan_value'];
}

$pddiktiUrl = $settings['pddikti_url'];
$pddiktiUsername = $settings['pddikti_username'];
$pddiktiPassword = $settings['pddikti_password'];

function callApi($url, $payload) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

// Get Token
$tokenRes = callApi($pddiktiUrl, [
    'act' => 'GetToken',
    'username' => $pddiktiUsername,
    'password' => $pddiktiPassword
]);
$token = $tokenRes['data']['token'];
echo "Token: $token\n\n";

$res1 = callApi($pddiktiUrl, [
    'act' => 'GetWilayah',
    'token' => $token,
    'filter' => "nama_wilayah like '%Praya%'",
    'limit' => 5
]);
echo "Test Praya: " . json_encode($res1) . "\n\n";

$res2 = callApi($pddiktiUrl, [
    'act' => 'GetWilayah',
    'token' => $token,
    'filter' => "",
    'limit' => 2
]);
echo "Columns: " . json_encode($res2) . "\n";
