<?php
// 환율 자동 실시간 UPDATE
// crontab 등록 : */30 * * * * /usr/bin/php /var/www/html/html_VPNLink/__CRON/cron_fx_rate_api.php >/dev/null 2>&1

if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    echo 'forbidden';
    exit;
}

@chdir(__DIR__ . '/..');
include_once(__DIR__ . '/../_common.php');

// $sql = " select * from fx_data where fx_type='KRWCNY' ORDER BY datetime DESC LIMIT 1 ";
// $row = sql_fetch($sql);
// echo $row['fx_type'].' '.$row['datetime'].' '.$row['fx_rate'];

// exit;

// Your API key from ExchangeRate-API
$apiKey = '6494e154920cbf1da64940ab';
$apiBaseCurrenncy = 'KRW';

// Fetching JSON
$req_url = 'https://v6.exchangerate-api.com/v6/' . $apiKey . '/latest/' . $apiBaseCurrenncy;

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $req_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // SSL 인증서 검증을 비활성화
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // SSL 인증서 검증을 비활성화
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 리디렉션을 따름
curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // 최대 리디렉션 횟수 설정 (default 10)
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 타임아웃 설정 (default 30)
$response_json = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error fetching data: ' . curl_error($ch);
    curl_close($ch);
    exit;
}

curl_close($ch);

// Continuing if we got a result
if (false !== $response_json) {
    // Try/catch for json_decode operation
    try {
        // Decoding
        $response = json_decode($response_json);

        // Check for success
        if ('success' === $response->result) {

            // api data 의 마지막 정보 update 시간 추출
            $time_last_update_unix = $response->time_last_update_unix;

            // Extracting the exchange rates
            $KRWUSD = round($response->conversion_rates->USD, 8);
            $KRWEUR = round($response->conversion_rates->EUR, 8);
            $KRWCNY = round($response->conversion_rates->CNY, 8);
            $KRWJPY = round($response->conversion_rates->JPY, 8);
            $KRWVND = round($response->conversion_rates->VND, 8);



            // Output for debugging purposes
            echo "Time last updated: ". date("Y-m-d H:i:s",$time_last_update_unix). " KST" . PHP_EOL;
            echo "KRW to USD: $KRWUSD" . PHP_EOL;
            echo "KRW to EUR: $KRWEUR" . PHP_EOL;
            echo "KRW to CNY: $KRWCNY" . PHP_EOL;
            echo "KRW to JPY: $KRWJPY" . PHP_EOL;
            echo "KRW to VND: $KRWVND" . PHP_EOL;

            $query_pre  = " SELECT count(*) as cnt FROM fx_data WHERE time_last_update_unix='{$time_last_update_unix}' ORDER BY id DESC ";
            $row = sql_fetch($query_pre);
            if ($row['cnt'] == 0) {
                $KRWKRW = 1;
                $query  = " INSERT INTO fx_data SET ";
                $query .= " fx_type='KRWKRW', fx_rate='{$KRWKRW}', datetime=now(), time_last_update_unix='{$time_last_update_unix}', fx_from_type='KRW', fx_from_amount='{$KRWKRW}' ";
                sql_query($query);

                $USDKRW = 1 / $KRWUSD;
                $query  = " INSERT INTO fx_data SET ";
                $query .= " fx_type='KRWUSD', fx_rate='{$KRWUSD}', datetime=now(), time_last_update_unix='{$time_last_update_unix}', fx_from_type='USD', fx_from_amount='{$USDKRW}' ";
                sql_query($query);

                $EURKRW = 1 / $KRWEUR;
                $query  = " INSERT INTO fx_data SET ";
                $query .= " fx_type='KRWEUR', fx_rate='{$KRWEUR}', datetime=now(), time_last_update_unix='{$time_last_update_unix}', fx_from_type='EUR', fx_from_amount='{$EURKRW}' ";
                sql_query($query);

                $CNYKRW = 1 / $KRWCNY;
                $query  = " INSERT INTO fx_data SET ";
                $query .= " fx_type='KRWCNY', fx_rate='{$KRWCNY}', datetime=now(), time_last_update_unix='{$time_last_update_unix}', fx_from_type='CNY', fx_from_amount='{$CNYKRW}' ";
                sql_query($query);

                $JPYKRW = 1 / $KRWJPY;
                $query  = " INSERT INTO fx_data SET ";
                $query .= " fx_type='KRWJPY', fx_rate='{$KRWJPY}', datetime=now(), time_last_update_unix='{$time_last_update_unix}', fx_from_type='JPY', fx_from_amount='{$JPYKRW}' ";
                sql_query($query);

                $VNDKRW = 1 / $KRWVND;
                $query  = " INSERT INTO fx_data SET ";
                $query .= " fx_type='KRWVND', fx_rate='{$KRWVND}', datetime=now(), time_last_update_unix='{$time_last_update_unix}', fx_from_type='VND', fx_from_amount='{$VNDKRW}' ";
                sql_query($query);

                echo 'New Fx Rate data inserted successfully.';
            } else {
                echo 'Fx Rate data already exists.';
            }
        } else {
            echo 'Error in API response: ' . $response->error_type;
        }
    } catch (Exception $e) {
        // Handle JSON parse error
        echo 'Error parsing JSON: ' . $e->getMessage();
    }
} else {
    echo 'Error fetching data.';
}