<?php

// API endpoint dan parameter
$api_url = 'https://api.nf22.my.id/sosmed';
$api_key = 'NgDXKhbcN7DKBl71FCYv8av8nyzwfM3M'; // Ganti dengan api key anda
$pin = '4628'; // Ganti dengan pin anda
$action = 'layanan';

// Prepare request data
$postdata = [
    'api_key' => $api_key,
    'pin' => $pin,
    'action' => $action
];

// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postdata));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Execute request
$response = curl_exec($ch);
curl_close($ch);

// =======================================================
//                    HEADER OUTPUT
// =======================================================

// Memberitahu browser bahwa ini adalah data JSON
header('Content-Type: application/json');

// !! BARIS BARU: Memaksa browser untuk mengunduh file dengan nama 'layanan.json' !!
header('Content-Disposition: attachment; filename="layanan.json"');


// Process response
$result = json_decode($response, true);

if ($result === null) {
    $error_response = ['error' => 'Gagal menerima data atau format respons tidak valid.'];
    echo json_encode($error_response, JSON_PRETTY_PRINT);
    exit();
}

if (isset($result['status']) && $result['status']) {
    echo json_encode($result['data'], JSON_PRETTY_PRINT);
} else {
    $error_message = $result['data']['pesan'] ?? 'Terjadi kesalahan tidak diketahui';
    $error_response = ['error' => $error_message];
    echo json_encode($error_response, JSON_PRETTY_PRINT);
}

?>
