<?php 
$path = preg_replace( '/wp-content(?!.*wp-content).*/', '', __DIR__ );
require_once( $path . 'wp-load.php' );

$region = (isset($_GET['region']) &&  $_GET['region'] != 'null' && !empty($_GET['region'])) ? ucwords($_GET['region']) : 'Ankara';
$city = (isset($_GET['city']) && $_GET['city'] != 'null' && !empty($_GET['city'])) ? ucwords($_GET['city']) : $region;
$date = date('Y-m-d');

// Cache folder path
$folder_path = ABSPATH . 'eczane-cache';

// Check if cached file exists and is from today
if (file_exists($folder_path.'/'.kanews_seflink($region).'.json')) {
  $response = get_local_file_contents(ABSPATH."/eczane-cache/".kanews_seflink($region).".json");
  $data = json_decode($response, true);
  if ( $data['updated'] == $date ) {
     echo $response;
    exit();
  }
}

// New API endpoint
$api_link = 'https://api-three-chi-43.vercel.app/api/pharmacy/'.strtolower(kanews_seflink($region))."?api_key=kanews-theme";

// Get data from API
$api_response = kanews_connect_api($api_link);
$api_data = json_decode($api_response, true);

// Check if API response is valid
if (!$api_data || !isset($api_data['data'])) {
    // If API fails, return error
    echo json_encode([
        'error' => true,
        'message' => 'API data could not be retrieved'
    ]);
    exit();
}

// Format data to match the expected structure
$eczaneler = [
    'updated' => $date,
    'detay' => [
        'il' => $region,
        'description' => isset($api_data['data']['description']) ? $api_data['data']['description'] : '',
        'ilce' => $city
    ],
    'data' => []
];

// Process pharmacies data
if (isset($api_data['data']['pharmacies']) && is_array($api_data['data']['pharmacies'])) {
    $eczaneler['data'][0] = [];
    
    foreach ($api_data['data']['pharmacies'] as $pharmacy) {
        $eczaneler['data'][0][] = [
            'eczane_adi' => $pharmacy['name'],
            'important' => isset($pharmacy['important']) ? $pharmacy['important'] : '',
            'adres' => $pharmacy['address'],
            'telefon' => $pharmacy['phone'],
            'ilce' => $pharmacy['district']
        ];
    }
}

// Create cache directory if it doesn't exist
if (!file_exists($folder_path)) {
    mkdir($folder_path);
}

// Save to cache and output
if (isset($eczaneler['data']) && !empty($eczaneler['data'])) {
    $file_name = kanews_seflink($region) . '.json';
    $file_path = $folder_path . '/' . $file_name;
    file_put_contents($file_path, json_encode($eczaneler));
    echo json_encode($eczaneler);
} else {
    echo json_encode([
        'error' => true,
        'message' => 'No pharmacy data available'
    ]);
}