<?php
header('Content-Type: application/json; charset=utf-8');

date_default_timezone_set('Asia/Jakarta');

$lat = isset($_GET['lat']) ? (float)$_GET['lat'] : null;
$lon = isset($_GET['lon']) ? (float)$_GET['lon'] : null;

if (!$lat || !$lon) {
    echo json_encode(['error' => 'missing coordinates']);
    exit;
}

$api = "https://api.aladhan.com/v1/timings/" . time()
     . "?latitude={$lat}&longitude={$lon}&method=2";

$ch = curl_init($api);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 8);
$res = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

if ($err || !$res) {
    echo json_encode(['error' => 'api_error']);
    exit;
}

$data = json_decode($res, true);
if (!isset($data['data']['timings'])) {
    echo json_encode(['error'=>'unexpected']);
    exit;
}

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

$map = [
    'subuh'   => preg_replace('/[^0-9:]/','', $t['Fajr']),
    'dzuhur'  => preg_replace('/[^0-9:]/','', $t['Dhuhr']),
    'ashar'   => preg_replace('/[^0-9:]/','', $t['Asr']),
    'maghrib' => preg_replace('/[^0-9:]/','', $t['Maghrib']),
    'isya'    => preg_replace('/[^0-9:]/','', $t['Isha']),
];

$tz = $data['data']['meta']['timezone'] ?? 'Asia/Jakarta';

date_default_timezone_set($tz);

$today = date('Y-m-d');
$now = new DateTime();

$nextPrayer = null;
$nextTime   = null;

foreach (['subuh','dzuhur','ashar','maghrib','isya'] as $p) {
    $dt = DateTime::createFromFormat('Y-m-d H:i', "$today {$map[$p]}");
    if ($dt && $dt > $now) {
        $nextPrayer = ucfirst($p);
        $nextTime = $dt->format('c');
        break;
    }
}

if (!$nextPrayer) {
    // tomorrow subuh
    $tom = date('Y-m-d', strtotime('+1 day'));
    $dt = DateTime::createFromFormat('Y-m-d H:i', "$tom {$map['subuh']}");
    $nextPrayer = 'Subuh';
    $nextTime = $dt ? $dt->format('c') : null;
}

echo json_encode([
    'timings'     => $map,
    'timezone'    => $tz,
    'next_prayer' => $nextPrayer,
    'next_time'   => $nextTime
]);
