<?php
// get_times.php
// Pastikan server menjalankan PHP 7+
// Menerima JSON POST { latitude, longitude, timeZone, method }

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

$raw = file_get_contents('php://input');
if (!$raw) {
    http_response_code(400);
    echo json_encode(['error'=>'no input']);
    exit;
}

$data = json_decode($raw, true);
if (!is_array($data) || !isset($data['latitude']) || !isset($data['longitude'])) {
    http_response_code(400);
    echo json_encode(['error'=>'invalid input']);
    exit;
}

$lat = floatval($data['latitude']);
$lon = floatval($data['longitude']);
$tz = isset($data['timeZone']) ? urlencode($data['timeZone']) : '';
$method = isset($data['method']) ? intval($data['method']) : 2; // 2 = Muslim World League (example)

$timestamp = date("Y-m-d");
// Aladhan API endpoint (public)
$apiUrl = "https://api.aladhan.com/v1/timings/{$timestamp}?latitude={$lat}&longitude={$lon}&method={$method}";
if ($tz !== '') {
    $apiUrl .= "&timezonestring={$tz}";
}

// gunakan curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_USERAGENT, 'JadwalSholatPHP/1.0');

$response = curl_exec($ch);
$err = curl_error($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response === false || $httpcode != 200) {
    http_response_code(502);
    echo json_encode(['error'=>'failed calling external API', 'details'=>$err, 'http_code'=>$httpcode]);
    exit;
}

// langsung teruskan response API (bisa di-parse & dimodifikasi jika perlu)
echo $response;
