<?php

function update_api_redis_values() {
    require_once $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/fln-financial-plugin/vendor/predis/predis/autoload.php';

    $endpoints_main = get_posts(array('post_type' => 'finance_api_main', 'numberposts' => -1));
    $endpoints_forex = get_posts(array('post_type' => 'finance_api_forex', 'numberposts' => -1));
    $endpoints_stocks = get_posts(array('post_type' => 'finance_api_stocks', 'numberposts' => -1));
    $endpoints_tables = get_posts(array('post_type' => 'fln_table', 'numberposts' => -1));

    $endpoints = array(
        'tables?per_page=1000',
        'main_brokers?per_page=1000',
        'forex_brokers?per_page=1000',
        'cfd_brokers?per_page=1000',
        'stocks_brokers?per_page=1000',
        'crypto_brokers?per_page=1000',
        'commodities_brokers?per_page=1000',
        'discount_brokers?per_page=1000',
        'social_brokers?per_page=1000',
        'bonds_brokers?per_page=1000',
    );

    foreach ($endpoints_main as $endpoint) {
        array_push($endpoints, 'main_brokers/'.$endpoint->ID.'/');
    }

    foreach ($endpoints_forex as $endpoint) {
        array_push($endpoints, 'forex_brokers/'.$endpoint->ID.'/');
    }

    foreach ($endpoints_stocks as $endpoint) {
        array_push($endpoints, 'stocks_brokers/'.$endpoint->ID.'/');
    }

    foreach ($endpoints_tables as $endpoint) {
        array_push($endpoints, 'tables/'.$endpoint->ID.'/');
    }

    // Predis\Autoloader::register();
$redis = new Predis\Client([
    'scheme' => 'tcp',
    'host'   => '127.0.0.1',
	'port'   => 6379,
	'database' => 0,
]);

try {
    $redis->ping();
} catch (Exception $e) {
    // LOG that redis is down : $e->getMessage();
}

if (!isset($e)) {
    $redis->flushdb();
    foreach ($endpoints as $endpoint) {
        $curl = curl_init();

        curl_setopt_array($curl, array(
        CURLOPT_USERPWD => $curl_auth,
        CURLOPT_URL => 'https://'.$_SERVER['HTTP_HOST'].'/wp-json/acf/v3/'.$endpoint,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 50,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            "Cache-Control: public, max-age=600"
        ),
        ));
    
        $response = curl_exec($curl);
        $err = curl_error($curl);
    
        curl_close($curl);
        $redis->set($endpoint, $response);
    }
}


}

add_action( 'save_post', 'update_api_redis_values');

?>
