<?php
date_default_timezone_set('Asia/Jakarta');

$cacheFile = __DIR__ . "/cache_jadwal.json";
$tanggal = date("Y-m-d");

// ================= API =================
$api = "http://api.aladhan.com/v1/timingsByCity?city=Jakarta&country=Indonesia&method=2";

$response = @file_get_contents($api);

if ($response === false) {
    error_log("Gagal ambil API jadwal");
    exit;
}

$data = json_decode($response, true);

if (!$data || !isset($data['data']['timings'])) {
    error_log("Format API salah");
    exit;
}

$jadwal = $data['data']['timings'];

// ================= CONVERT =================
function keMenit($jam) {
    list($h, $m) = explode(":", $jam);
    return ($h * 60) + $m;
}

$result = [
    "subuh" => keMenit($jadwal['Fajr']),
    "dzuhur" => keMenit($jadwal['Dhuhr']),
    "ashar" => keMenit($jadwal['Asr']),
    "maghrib" => keMenit($jadwal['Maghrib']),
    "isya" => keMenit($jadwal['Isha'])
];

// ================= SIMPAN =================
file_put_contents($cacheFile, json_encode([
    "tanggal" => $tanggal,
    "data" => $result
]));

// ================= LOG =================
echo "Update jadwal sukses: $tanggal\n";