<?php
// config/price.php

$cacheFile = __DIR__ . "/price_cache.json";
$cacheTTL  = 300; // 5 دقائق

function fetchGlobalPrices() {
    $apiKey = "goldapi-1cuztk319mg0hlqzl-io"; // مفتاحك من goldapi.io
    $headers = [
        "x-access-token: $apiKey",
        "Content-Type: application/json"
    ];

    // جلب الذهب
    $ch = curl_init("https://www.goldapi.io/api/XAU/SAR");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $goldData = json_decode(curl_exec($ch), true);
    curl_close($ch);

    // جلب الفضة
    $ch = curl_init("https://www.goldapi.io/api/XAG/SAR");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $silverData = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (!$goldData || !$silverData || !isset($goldData['price']) || !isset($silverData['price'])) {
        return null;
    }

    // تحويل الأونصة إلى جرام
    $gold24 = $goldData['price'] / 31.1035;
    $silver = $silverData['price'] / 31.1035;

    return [
        "gold_24" => round($gold24, 2),
        "gold_21" => round($gold24 * (21/24), 2),
        "gold_18" => round($gold24 * (18/24), 2),
        "silver"  => round($silver, 2),
        "updated" => date("Y-m-d H:i:s")
    ];
}

function getPrices() {
    global $cacheFile, $cacheTTL;

    if (file_exists($cacheFile)) {
        $cache = json_decode(file_get_contents($cacheFile), true);
        if ($cache && isset($cache['updated'])) {
            $last = strtotime($cache['updated']);
            if (time() - $last < $cacheTTL) {
                return $cache;
            }
        }
    }

    $fresh = fetchGlobalPrices();
    if ($fresh) {
        file_put_contents($cacheFile, json_encode($fresh));
        return $fresh;
    }

    return ["gold_24"=>0, "gold_21"=>0, "gold_18"=>0, "silver"=>0, "updated"=>null];
}
