<?php

define('WP_UPLOADS_FOLDERNAME', 'uploads');


class StoreLocator
{
    public $aMemberVar = 'aMemberVar Member Variable';
    public $aFuncName = 'aMemberFunc';
    public $ftp_server = 'sftp.vtinfo.com';
    public $ftp_user_name = 'lauuser2';
    public $ftp_user_pass = '1d2w08kS';
    public $local_file_us = WP_CONTENT_DIR . '/' . WP_UPLOADS_FOLDERNAME . '/stores/us_tmp.gz';
    public $local_file_us_extracted = WP_CONTENT_DIR . '/' . WP_UPLOADS_FOLDERNAME . '/stores/us_tmp.csv';
    public $local_file_us_extracted_valid = WP_CONTENT_DIR . '/' . WP_UPLOADS_FOLDERNAME . '/stores/us.csv';
    public $must_headers_us = [];
    public $must_headers_fr = [];

    public function __construct()
    {

        $this->must_headers_fr = [
            'id',
            'title',
            '_laup_store_store',
            '_laup_store_address',
            '_laup_store_address2',
            '_laup_store_region',
            '_laup_store_country',
            '_laup_store_coord',
            '_laup_store_zipcode',
            '_laup_store_city',
            '_laup_store_phone',
            '_laup_store_phone_intl',
            '_laup_store_website'
        ];

        $this->must_headers_us = [
            'DBAName',
            'StreetNumber',
            'StreetName',
            'State',
            'Zip+4',
            'City',
            'PhoneNumber',
            'Latitude',
            'Longitude',
            'BrandDescription'
        ];

        foreach ($this->must_headers_us as $k => $must_header) {
            $this->must_headers_us[$k] = strtolower($must_header);
        }
    }

    public function cuveerose_get_stores_csv($page_id = null)
    {
        $output = [];
        $stores_csv = get_field('stores_csv', $page_id);
        if ($stores_csv) {
            $url = $stores_csv['url'];
            $file_csv = realpath(str_replace(site_url(), '.', $url));
            if (empty($file_csv)) return array();
            $row = 1;

            $current_lang = apply_filters('wpml_current_language', null);
            $countries = COUNTRIES_EN;
            if (defined('COUNTRIES_' . strtoupper($current_lang))) {
                $countries = constant('COUNTRIES_' . strtoupper($current_lang));
            }

            $output = [];
            $headers = [];
            $dedoublon = [];

            if (($handle = fopen($file_csv, "r")) !== false) {
                while (($data = fgetcsv($handle, 1000, ",")) !== false) {

                    $num = count($data);

                    // Entetes
                    if ($row == 1) {
                        for ($c = 0; $c < $num; $c++) {
                            if (in_array(strtolower($data[$c]), $this->must_headers_fr)) {
                                $headers[strtolower($data[$c])] = $c;
                            }
                            //echo $data[$c] . "<br />\n";

                        }
                        if (sizeof($this->must_headers_fr) > sizeof($headers)) {
                            return array();
                        }
                    } else {

                        $gps = unserialize($data[$headers['_laup_store_coord']]);
                        $lat = (isset($gps[0]['_laup_store_lat'])) ? $gps[0]['_laup_store_lat'] : '';
                        $lng = (isset($gps[0]['_laup_store_lng'])) ? $gps[0]['_laup_store_lng'] : '';
                        if (!in_array($data[$headers['_laup_store_store']] . $lat . $lng, $dedoublon)) {
                            $store = [
                                'i' => 'st-' . $row,
                                'n' => trim($data[$headers['_laup_store_store']]),
                                'co' => trim(strtoupper($data[$headers['_laup_store_country']])),
                                'cn' => trim(isset($countries[strtoupper($data[$headers['_laup_store_country']])]) ? $countries[strtoupper($data[$headers['_laup_store_country']])] : ''),
                                'a' => trim($data[$headers['_laup_store_address']]),
                                'a2' => trim($data[$headers['_laup_store_address2']]),
                                'z' => trim($data[$headers['_laup_store_zipcode']]),
                                'c' => trim($data[$headers['_laup_store_city']]),
                                'p' => trim($data[$headers['_laup_store_phone']]),
                                'pi' => trim($data[$headers['_laup_store_phone_intl']]),
                                'w' => trim($data[$headers['_laup_store_website']]),
                                'lat' => trim($lat),
                                'lng' => trim($lng),
                                'f' => 'fr'
                            ];
                            $output[] = $store;
                            $dedoublon[] = $data[$headers['_laup_store_store']] . $lat . $lng;
                        }
                    }
                    $row++;
                }
                fclose($handle);
            }

            return $output;
        }
    }

    public function cuveerose_get_stores_us()
    {
        $output = [];
        $file_csv = $this->local_file_us_extracted_valid;

        $row = 1;

        $current_lang = apply_filters('wpml_current_language', null);
        $countries = COUNTRIES_EN;
        if (defined('COUNTRIES_' . strtoupper($current_lang))) {
            $countries = constant('COUNTRIES_' . strtoupper($current_lang));
        }

        $headers = [];
        $dedoublon = [];
        $this->must_headers_us = [
            'DBAName',
            'StreetNumber',
            'StreetName',
            'State',
            'Zip+4',
            'City',
            'PhoneNumber',
            'Latitude',
            'Longitude',
            'BrandDescription'
        ];

        foreach ($this->must_headers_us as $k => $must_header) {
            $this->must_headers_us[$k] = strtolower($must_header);
        }
        if (($handle = fopen($file_csv, "r")) !== false) {
            while (($data = fgetcsv($handle, 1000, ",")) !== false) {

                $num = count($data);

                // Entetes
                if ($row == 1) {
                    for ($c = 0; $c < $num; $c++) {
                        if (in_array(strtolower($data[$c]), $this->must_headers_us)) {
                            $headers[strtolower($data[$c])] = $c;
                        }
                        //echo $data[$c] . "<br />\n";

                    }
                    if (sizeof($this->must_headers_us) > sizeof($headers)) {
                        return array();
                    }
                } else {
                    if (!in_array(
                        $data[$headers['dbaname']] . $data[$headers['latitude']] . $data[$headers['longitude']],
                        $dedoublon
                    )) {
                        $address = $data[$headers['streetnumber']] . ' ' . $data[$headers['streetname']];
                        $address2 = $data[$headers['city']];
                        if (!empty($data[$headers['state']])) {
                            $address2 .= ', ' . $data[$headers['state']];
                        }
                        if (!empty($data[$headers['zip+4']])) {
                            $address2 .= ' ' . $data[$headers['zip+4']];
                        }

                        if (trim($data[$headers['branddescription']]) == 'Rose') {
                            // Rose ou Grand Siecle

                            $store = [
                                'i' => 'store-' . $row,
                                'n' => trim($data[$headers['dbaname']]),
                                //                                'co' => 'US',
                                'cn' => 'United States',
                                'a' => trim($address),
                                'a2' => trim($address2),
                                //                                'z' => '', //$data[$headers['zip+4']],
                                //                                'c' => '', //$data[$headers['city']],
                                'p' => trim($data[$headers['phonenumber']]),
                                //                                'pi' => trim($data[$headers['phonenumber']]),
                                //                                'w' => '',
                                'lat' => trim($data[$headers['latitude']]),
                                'lng' => trim($data[$headers['longitude']]),
                                'f' => 'us'

                            ];
                            $output[] = $store;
                            $dedoublon[] = $data[$headers['dbaname']] . $data[$headers['latitude']] . $data[$headers['longitude']];
                        }
                    }
                }
                $row++;
            }
            fclose($handle);
        }
        //        }

        //    echo '<pre>';
        //    var_dump($output);
        //    echo '</pre>';
        //    exit;
        return $output;
    }

    public function update_stores_us_ftp()
    {

        // BECAUSE LOCALY WE HAVE A WRITE PROBLEM, WE ESCAPE THE STORE UPDATE
        // NOT FOR PROD, ONLY LOCAL
        if (strpos($_SERVER['HTTP_HOST'], 'local') !== false) {
            //return true;
        }

        // Si fichier assez récent alors on ne fait rien
        if (file_exists($this->local_file_us_extracted_valid)) {
            $diff_days = abs(time() - filemtime($this->local_file_us_extracted_valid)) / 60 / 60 / 24;
            if ($diff_days < 0) return false;
        }

        // Mise en place d'une connexion basique
        $conn_id = ftp_connect($this->ftp_server);
        if ($conn_id) {
            ftp_pasv($conn_id, true);

            // Identification avec un nom d'utilisateur et un mot de passe
            $login_result = ftp_login($conn_id, $this->ftp_user_name, $this->ftp_user_pass);
            ftp_pasv($conn_id, true);

            // Vérification de la connexion
            if ((!$conn_id) || (!$login_result)) {
                //            echo "La connexion FTP a échoué !";
                //            echo "Tentative de connexion au serveur $this->ftp_server pour l'utilisateur $this->ftp_user_name";
                return false;
            } else {

                $filenames = ftp_nlist($conn_id, './');
                $last_date = '20181101';
                $file_to_download = '';

                foreach ($filenames as $filename) {
                    $match = false;
                    preg_match('/BFNDDA.N([0-9]{4}[0-9]{2}[0-9]{2}).gz/', $filename, $match);

                    if (
                        strlen($filename) == 19
                        && substr($filename, 0, 8) == 'BFNDDA.N'
                        && substr($filename, -3) == '.GZ'
                    ) {

                        $date = str_replace('BFNDDA.N', '', $filename);
                        $date = str_replace('.gz', '', $date);

                        if ($date > $last_date) {
                            $last_date = $date;
                            $file_to_download = $filename;
                        }
                    }
                    //                if(isset($match[0]) && isset($match[1]) && $match[0] == $filename) {
                    //                    if($match[1] > $last_date) {
                    //                        $last_date = $match[1];
                    //                        $file_to_download = $filename;
                    //                    }
                    //                }
                }

                if (!empty($file_to_download)) {

                    $remote_file = $file_to_download;

                    $handle = fopen($this->local_file_us, 'w');

                    if (ftp_fget($conn_id, $handle, $remote_file, FTP_BINARY, 0)) {
                        //                    echo "Ecriture dans le fichier $this->local_file_us avec succès\n";

                        $gz = gzopen($this->local_file_us, 'rb');
                        if (!$gz) {
                            //                        throw new \UnexpectedValueException(
                            //                            'Could not open gzip file'
                            //                        );
                            return false;
                        } else {
                            $dest = fopen($this->local_file_us_extracted, 'wb');
                            if (!$dest) {
                                gzclose($gz);
                                //                            throw new \UnexpectedValueException(
                                //                                'Could not open destination file'
                                //                            );
                                return false;
                            } else {
                                while (!gzeof($gz)) {
                                    fwrite($dest, gzread($gz, 4096));
                                }
                                if (1 == 1) {
                                    $headers = [];
                                    $csv_is_valid = false;
                                    if (($handle = fopen($this->local_file_us_extracted, "r")) !== false) {
                                        while (($data = fgetcsv($handle, 1000, ",")) !== false) {

                                            $num = count($data);

                                            for ($c = 0; $c < $num; $c++) {
                                                if (in_array(strtolower($data[$c]), $this->must_headers_us)) {
                                                    $headers[strtolower($data[$c])] = $c;
                                                }
                                                //echo $data[$c] . "<br />\n";

                                            }
                                            if (sizeof($this->must_headers_us) > sizeof($headers)) {
                                                $csv_is_valid = false;
                                            } else {
                                                $csv_is_valid = true;
                                            }
                                            break;
                                        }
                                    }
                                    if ($csv_is_valid) {
                                        rename($this->local_file_us_extracted, $this->local_file_us_extracted_valid);
                                        return true;
                                    }
                                }
                            }
                        }
                        gzclose($gz);
                        fclose($dest);
                    } else {
                        //                    echo "Il y a un problème lors du téléchargement du fichier $remote_file dans $this->local_file_us\n";

                        return false;
                    }
                }
                return false;
                //            echo '<pre>';
                //            var_dump($file_to_download);
                //            echo '</pre>';
                //            echo "Connexion au serveur $this->ftp_server, pour l'utilisateur $this->ftp_user_name";
            }

            // Chargement d'un fichier
            //    $upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
            //
            //    // Vérification du status du chargement
            //    if (!$upload) {
            //        echo "Le chargement FTP a échoué!";
            //    } else {
            //        echo "Chargement de $source_file vers $ftp_server en tant que $destination_file";
            //    }

            // Fermeture du flux FTP
            ftp_close($conn_id);
            //        exit;
        }
    }
}
//$vipCustID = 'LAU';
//$url = 'https://www.vtinfo.com/PF/product_finder-service.asp';
////$url = 'https://www.vtinfo.com/PF/product_finder-test.asp?custID=LAU';
//date_default_timezone_set('GMT');
//$vipTimestamp = date('D, j M Y H:i:00 T', time());
//$vipSecretCode = '01D0635F5455LAU454BC68D9DEA';
//$parms = 'action=results&brand=Rose&lat=40.12&long=-74.12&miles=10000';
//$vipSignature = hash('sha256', $vipTimestamp.$vipSecretCode.$parms.$vipCustID);
//// send a HTTP POST request with curl
//$ch = curl_init();
//curl_setopt($ch, CURLOPT_URL, $url.'?'.$parms);
//curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, [
//    'vipCustID: '.$vipCustID,
//    'vipTimestamp: '.$vipTimestamp,
//    'vipSignature: '.$vipSignature,
//]);
//curl_setopt($ch, CURLOPT_POSTFIELDS, ['action' => 'results', 'brand' => 'Rose', 'lat' => '40.12', 'long' => '-74.12', 'miles' => '100']);
//$result = curl_exec($ch);
//curl_close($ch);
//echo '<pre>';
//var_dump($vipTimestamp, $vipSignature, $result);
//echo '</pre>';
//exit;



/*
 *
        'id' => 'store-' . $i,
        'name' => 'Nom du store',
        'country' => 'FR',
        'country_name' => 'France',
        'address' => 'lorem ipsum address',
        'address2' => 'lorem ipsum address 2',
        'zipcode' => '69004',
        'city' => 'Lyon',
        'phone' => '0123456789',
        'phone_intl' => '0123456789',
        'website' => 'www.google.fr',
        'lat' => '45.'.rand(70, 80),
        'lng' => '4.'.rand(80, 90),
 */

function lp_create_stores_table()
{
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();

    $table_name = $wpdb->prefix . 'stores';

    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
	id mediumint(9) NOT NULL AUTO_INCREMENT,
	country_code varchar(10) DEFAULT NULL,
	country varchar(50) DEFAULT NULL,
	name varchar(100) DEFAULT NULL,
	address varchar(100) DEFAULT NULL,
	address2 varchar(100) DEFAULT NULL,
	zipcode varchar(10) DEFAULT NULL,
	city varchar(50) DEFAULT NULL,
	phone varchar(20) DEFAULT NULL,
	lat varchar(255) DEFAULT NULL,
	lng varchar(255) DEFAULT NULL,
	file_id mediumint(9) NOT NULL,
	PRIMARY KEY  (id)
) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    $r = dbDelta($sql);
}


add_action('acf/save_post', 'lp_get_stores_json');
function lp_get_stores_json()
{
    $field = get_field('stores_list');

    global $wpdb;
    $table_name = $wpdb->prefix . 'stores';

    $data = $wpdb->get_results(
        "
            SELECT id as i, country_code as cc, country as co, name as n, address as a, address2 as a2, zipcode as z, city as c, phone as p, lat, lng
            FROM $table_name
            WHERE lat IS NOT NULL AND lat != '' AND lat != '0' AND lng IS NOT NULL AND lng != '' AND lng != '0'
        ",
        ARRAY_A
    );

    foreach ($data as $k => $v) {
        $v['f'] = 'fr';
        $data[$k] = $v;
    }


    $storeLocator = new StoreLocator();
    $storeLocator->update_stores_us_ftp();

    $stores_us = $storeLocator->cuveerose_get_stores_us();

    $data = array_merge($data, $stores_us);

    $json = json_encode(['data' => $data]);
    return file_put_contents(WP_CONTENT_DIR . "/uploads/stores/stores.json", $json);

    return json_encode($data);
}

function lp_get_stores_file_id()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'stores';

    $data = $wpdb->get_results(
        "
            SELECT file_id
            FROM $table_name
            WHERE `file_id` > 0
            GROUP BY `file_id`
        ",
        ARRAY_A
    );

    return $data;
}

function lp_acf_stores_list_update_value($value, $post_id, $field)
{

    // only do it to certain custom fields
    if ($field['name'] == 'stores_list') {
        cron_update_stores_gps();

        // get the old (saved) value
        $old_value = get_field('stores_list', $post_id, false);

        // get the new (posted) value
        $new_value = $_POST['acf']['field_602cbd8473d03'];

        if (is_array($new_value)) {
            $new_value = array_values($new_value);
        }
        if (is_array($old_value)) {
            $old_value = array_values($old_value);
        }

        if ($old_value != $new_value) {

            global $wpdb;
            $table_name = $wpdb->prefix . 'stores';

            $output = [];
            $inserts = [];
            $files = $new_value;
            $fields = array(
                'country_code',
                'country',
                'name',
                'address',
                'address2',
                'zipcode',
                'city',
                'phone',
                'lat',
                'lng'
            );
            $fields_address = array('address', 'address2', 'zipcode', 'city', 'country_code');
            $files_ids = array();
            $files_ids_exists = array();
            $data_files_ids = lp_get_stores_file_id();
            foreach ($data_files_ids as $data_files_id) {
                $files_ids_exists[] = $data_files_id['file_id'];
            }

            foreach ($files as $file) {
                $id_file = 0;
                if (isset($file['field_602cbdc673d04'])) {
                    $id_file = $file['field_602cbdc673d04'];
                }
                if ($id_file > 0) {
                    $files_ids[] = $id_file;
                }
                if ($id_file > 0 && !in_array($id_file, $files_ids_exists)) {

                    //                    $wpdb->query('DELETE FROM TABLE ' . $table_name . ' WHERE file_id="' . . '"');
                    $file_csv = get_attached_file($id_file);
                    if (!empty($file_csv)) {
                        $row = 1;

                        $output = [];
                        $headers = [];
                        $dedoublon = [];

                        $delimiter = lp_csv_detect_delimiter($file_csv);
                        if (($handle = fopen($file_csv, "r")) !== false) {
                            while (($data = fgetcsv($handle, 1000, $delimiter)) !== false) {

                                $num = count($data);

                                // Entetes
                                if ($row == 1) {
                                    for ($c = 0; $c < $num; $c++) {
                                        if (in_array(strtolower($data[$c]), $fields)) {
                                            $headers[strtolower($data[$c])] = $c;
                                        }
                                    }
                                } else {
                                    $data_sql = array('file_id' => $id_file);
                                    foreach ($fields as $field) {
                                        if (isset($data[$headers[$field]])) {
                                            $data_sql[$field] = $data[$headers[$field]];
                                        }
                                    }
                                    if (sizeof($data_sql) > 3) {
                                        $format = array_fill(0, sizeof($data_sql), '%s');

                                        //                                        if (!isset($data_sql['lat']) && !isset($data_sql['lng'])) {
                                        //                                            $address = '';
                                        //                                            foreach ($fields_address as $f) {
                                        //                                                if (isset($data_sql[$f])) {
                                        //                                                    $address .= $data_sql[$f] . ' ';
                                        //                                                }
                                        //                                            }
                                        ////                                            $gps = lp_get_lat_lng($address);
                                        //                                            if (isset($gps['lat'])) {
                                        //                                                $data_sql['lat'] = $gps['lat'];
                                        //                                            }
                                        //                                            if (isset($gps['lng'])) {
                                        //                                                $data_sql['lng'] = $gps['lng'];
                                        //                                            }
                                        //                                        }
                                        $inserts[] = array(
                                            'data' => $data_sql,
                                            'format' => $format
                                        );
                                    }
                                }
                                $row++;
                            }
                            fclose($handle);
                        }
                    }
                }
            }

            if (sizeof($files_ids) > 0) {
                $wpdb->query('DELETE FROM ' . $table_name . ' WHERE file_id NOT IN (' . implode(',', $files_ids) . ')');
            }


            foreach ($inserts as $insert) {
                $insert_id = $wpdb->insert($table_name, $insert['data'], $insert['format']);
            }

            // Dedoublonnage
            $wpdb->query('DELETE ' . $table_name . ' FROM ' . $table_name . '
                LEFT OUTER JOIN (
                        SELECT MAX(id) as id, country_code, name, address, address2, zipcode, city
                        FROM ' . $table_name . '
                        GROUP BY country_code, name, address, address2, zipcode, city
                    ) as t1
                    ON ' . $table_name . '.id = t1.id
                WHERE t1.id IS NULL');

            wp_schedule_single_event(time() + 1, 'event_cron_update_stores_gps');
        }
    }

    // don't forget to return to be saved in the database
    return $value;
}

if (!wp_get_schedule('event_cron_update_stores_json')) {
    wp_schedule_event(time(), 'hourly', 'event_cron_update_stores_json', []);
}

add_filter('acf/update_value', 'lp_acf_stores_list_update_value', 10, 3);

function lp_csv_detect_delimiter($csvFile)
{
    $delimiters = [";" => 0, "," => 0, "\t" => 0, "|" => 0];

    $handle = fopen($csvFile, "r");
    $firstLine = fgets($handle);
    fclose($handle);
    foreach ($delimiters as $delimiter => &$count) {
        $count = count(str_getcsv($firstLine, $delimiter));
    }

    return array_search(max($delimiters), $delimiters);
}

function lp_get_lat_lng($address)
{

    $address = rawurlencode($address);
    $coord = get_transient('geocode_' . $address);

    $do = false;

    if (empty($coord)) {
        $do = true;
    }
    if (!isset($coord['lat']) || empty($coord['lat'])) {
        $do = true;
    }
    if (!isset($coord['lng']) || empty($coord['lng'])) {
        $do = true;
    }


    if ($do) {
        $coord['lat'] = null;
        $coord['lng'] = null;
        //        $url = 'https://nominatim.openstreetmap.org/?format=json&addressdetails=0&q=' . $address . '&format=json&limit=1';
        //        $json = wp_remote_get($url);
        //
        //        if (200 === (int)wp_remote_retrieve_response_code($json)) {
        //            $body = wp_remote_retrieve_body($json);
        //            $json = json_decode($body, true);
        //        }
        //
        //        if(isset($json[0]['lat']) && !empty($json[0]['lon'])) {
        //            $coord['lat'] = $json[0]['lat'];
        //            $coord['lng'] = $json[0]['lon'];
        //            set_transient('geocode_' . $address, $coord, DAY_IN_SECONDS * 300);
        //        }else {
        // Google

        $data = GmapApi::geocodeAddress($address);
        if (isset($data['lat']) && !empty($data['lng'])) {
            $coord['lat'] = (string) $data['lat'];
            $coord['lng'] = (string) $data['lng'];
            set_transient('geocode_' . $address, $coord, DAY_IN_SECONDS * 300);
        }
        //        }

    }

    return $coord;
}


function lp_get_stores_without_gps()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'stores';

    $data = $wpdb->get_results(
        "
            SELECT id, country_code, name, address, address2, zipcode, city, lat,lng
            FROM $table_name
            WHERE lat IS NULL OR lng IS NULL OR lat = '0' OR lng = '0'
            GROUP BY lat, lng
            LIMIT 10
        ",
        ARRAY_A
    );

    return $data;
}

function lp_get_stores_without_gps_all()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'stores';

    $data = $wpdb->get_results(
        "
            SELECT id, country_code, name, address, address2, zipcode, city
            FROM $table_name
            WHERE lat IS NULL OR lng IS NULL
        ",
        ARRAY_A
    );

    return $data;
}

function lp_get_stores_without_gps_errors()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'stores';

    $data = $wpdb->get_results(
        "
            SELECT id, country_code, name, address, address2, zipcode, city
            FROM $table_name
            WHERE lat = '0' OR lng = '0'
        ",
        ARRAY_A
    );

    return $data;
}


/*
 * CRON ADDRESS TO GPS
 */
function cron_update_stores_gps()
{

    global $wpdb;
    $table_name = $wpdb->prefix . 'stores';
    $data = lp_get_stores_without_gps();

    $fields_address = array('address', 'zipcode', 'city');
    if (sizeof($data) > 0) {
        foreach ($data as $d) {
            $address = '';
            foreach ($fields_address as $f) {
                if (isset($d[$f])) {
                    $address .= $d[$f] . ' ';
                }
            }
            $gps = array();

            if ($address != '') {
                $gps = lp_get_lat_lng($address);
            }
       

            if (isset($gps['lat']) && isset($gps['lng'])) {
                $wpdb->update($table_name, ['lat' => $gps['lat'], 'lng' => $gps['lng']], ['id' => $d['id']]);
            } else {
                $wpdb->update($table_name, ['lat' => 0, 'lng' => 0], ['id' => $d['id']]);
            }
        }
        wp_schedule_single_event(time() + 1, 'event_cron_update_stores_gps');
    }
}

add_action('event_cron_update_stores_gps', 'cron_update_stores_gps');

add_action('event_cron_update_stores_json', 'lp_get_stores_json');

function acf_display_stores_gps_errors($field)
{

    if ($field['key'] == "field_602cbd8473d03") {
        $all_errors = lp_get_stores_without_gps_errors();
        $errors = sizeof($all_errors);
        $reste = sizeof(lp_get_stores_without_gps_all());
        echo '<p><a href="' . get_bloginfo('template_url') . '/assets/example_stores.csv" target="_blank">Télécharger un exemple de fichier CSV</a></p>';
        if ($reste > 0) echo '<p>' . $reste . ' stores en cours de conversion GPS</p>';
        if ($errors > 0) echo '<p>' . $errors . ' erreurs de conversion GPS :<br /><pre>' . print_r($all_errors, true) . '</pre></p>';
    }
}
add_action('acf/render_field', 'acf_display_stores_gps_errors', 10, 1);


class GmapApi
{

    private static $apikey = 'AIzaSyBAdYQYiI_IpavQl8Nb1JwEDnnDCI3XTbk';

    public static function geocodeAddress($address)
    {
        //valeurs vide par défaut
        $data = array('lat' => '', 'lng' => '');
        //on formate l'adresse
        $address = str_replace(" ", "+", $address);
        //on fait l'appel à l'API google map pour géocoder cette adresse
        $url = "https://maps.google.com/maps/api/geocode/json?key=" . self::$apikey . "&address=$address&sensor=false&123";
        //        $json = file_get_contents($url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $response = curl_exec($ch);
        curl_close($ch);
        $json = json_decode($response);

        //on enregistre les résultats recherchés
        if ($json->status == 'OK' && count($json->results) > 0) {

            $res = $json->results[0];
            $data['lat'] = $res->geometry->location->lat;
            $data['lng'] = $res->geometry->location->lng;
        }
        return $data;
    }
}
