<?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' => isset($countries['US']) ? $countries['US'] : '',
                                '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),
 */