<?php

/**
 * @package: EGPS - Easy Sell for Google Photo
 */

if(!defined('ABSPATH')){
    exit; // Exit if accessed directly
}

class Egps{

    public static function egps_vardump($array){
        print("<pre>");
        print(esc_html( print_r($array, true)) );
        print("</pre>");
    }

    public static function egps_errordump($array){
        echo '<div class="alert alert-danger selmmessagedump" role="alert">';

        foreach($array as $key => $val){
            echo "<strong>" . esc_html($key) . "</strong><br>";
            echo esc_html($val) . "<br>";
        }

        echo "</div>";
    }
    
    public static function egps_datenow(){
        $date = date('Y-m-d H:i:s');
        return $date;
    }
    
    public static function egps_datenow_date(){
        $date = date('Y-m-d');
        return $date;
    }

    public static function egps_check_date($d){

        if($d != null){
            $date = date('Y-m-d');
            $darr = explode('-', $d);
            $date2 = date("Y-m-d", mktime(0, 0, 0, intval($darr[1]), intval($darr[2]+1), intval($darr[0])));

            if(strtotime($date) < strtotime($date2)){
                return true;
            }

        }
        return false;
    }

    public static function egps_chk_lic(){

        $egps_l_opt = get_option('egps_license_options');

        if($egps_l_opt != null){
            $dcrypted = new EgpsAuthenticate;

            $dec_key = $dcrypted->egps_decrypt_key(
                $egps_l_opt['egps_license_key'], 
                $egps_l_opt['egps_api_key']
            );
            if(!isset($dec_key[1])){
                return false;
            }
            return self::egps_check_date($dec_key[1]);

        }
        return null;
    }
    
    public static function egps_zero_progress(){
        $myfile = fopen(__DIR__ . '/progress.json', "w") or die("Unable to open file!");
        $txt = json_encode(array('percentComplete' => 0));
        fwrite($myfile, $txt);
        fclose($myfile);
        
        return;
    }
    
    public static function egps_image_base64($path){
        
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $data = file_get_contents($path);
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

        return $base64;
    }
    
    public static function egps_image_download($file_url, $filename, $folder){

        $image_file = EGPS_ABSPATH . 'wp-content/uploads/egps/' . $folder . '/' . $filename;
        $image_file_return = get_site_url() . '/wp-content/uploads/egps/' . $folder . '/' . $filename;

        if(!file_exists($image_file)){
            try{
                file_put_contents($image_file, fopen($file_url, 'r'));
                
                return $image_file_return;
                
            }catch (Error $error){
                Egps::egps_vardump($error);
                
                return null;
            }
        }
        
        return $image_file_return;
    }
    
    public static function egps_check_file_exists($folder, $file_url){
        $image_file = EGPS_ABSPATH . 'wp-content/uploads/egps/' . $folder . '/' . $file_url;

        if(!file_exists($image_file)){
            return false;
        }
        return true;
    }

    public static function egps_multiple_download($myarray, $need_pbar = false){
        $i = 0;
        $sum_count = count($myarray);

        global $wp_filesystem;

        foreach ($myarray as $key => $photo) {

            $url = $photo->egps_url;
            $img = EGPS_ABSPATH . 'wp-content/uploads/egps/photos/' . $photo->egps_id . '.jpg';

            if(!is_file($img)) {

                try{

                    file_put_contents($img, fopen($url, 'r'));

                }catch (Error $error){
                    Egps::egps_vardump($error);
                }
                
            }

            //remove from database download table
            EgpsDatabase::egps_delete_record('egps_download', $photo->id);

            //progressBar
            
            $i++;
            if($need_pbar){
                $myfile = fopen(__DIR__ . '/progress.json', "w") or die("Unable to open file!");
                $txt = json_encode(array(
                    'percentComplete' => round($i / $sum_count * 100),
                    'albumId' => 0
                ));
                fwrite($myfile, $txt);
                fclose($myfile);
            }
            
        }

        
    }
    
    public static function egps_load_currencycodes(){
        
        $cur_list = array(
            "USD" => "$",
            "EUR" => "€",
            "JPY" => "¥",
            "GBP" => "£",
            "AUD" => "AUD",
            "CAD" => "CAD",
            "CHF" => "CHF",
            "CNY" => "CNY",
            "INR" => "INR"
        );

        return $cur_list;
        
    }

    public static function egps_email_admin_out_allowed(){

        $arr_allowed = array(
            "body" => array(
                "class" => array(),
                "style" => array()
            ),
            "table" => array(
                "id" => array(),
                "class" => array(),
                "style" => array(),
                "cellpadding" => array(),
                "cellspacing" => array(),
                "align" => array(),
                "role" => array(),
                "width" => array(),
                "padding" => array(),
                "border" => array()
            ),
            "tbody" => array(),
            "td" => array(
                "id" => array(),
                "class" => array(),
                "style" => array(),
                "align" => array()
            ),
            "tr" => array(
                "id" => array(),
                "class" => array(),
                "style" => array(),
                "align" => array()
            ),
            "div" => array(
                "id" => array(),
                "class" => array(),
                "style" => array(),
                "align" => array()
            ),
            "p" => array(
                "class" => array(),
                "style" => array()
            ),
            "a" => array(
                "class" => array(),
                "style" => array(),
                "href" => array(),
                "target" => array(),
                "title" => array()
            ),
            "img" => array(
                "align" => array(),
                "border" => array(),
                "src" => array(),
                "alt" => array(),
                "title" => array(),
                "style" => array(),
                "width" => array(),
                "class" => array()
        
            ),
            "b" => array(),
            "br" => array(),
            "h1" => array(
                "class" => array(),
                "style" => array()
            ),
            "strong" => array(),
            "span" => array(
                "class" => array(),
                "style" => array()
            ),
            "pre" => array(
                "class" => array(),
                "style" => array()
            )
        
        );

        return $arr_allowed;
    }

    public static function egps_get_page_by_template($page_tamplate){
        $args = [
            'post_type'  => 'page',
            'fields'     => 'ids',
            'nopaging'   => true,
            'meta_key'   => '_wp_page_template',
            'meta_value' => $page_tamplate
        ];
        $pages = get_posts( $args );
        return $pages;
    }

    public static function egps_title_to_url($text, string $divider = '-'){
        // replace non letter or digits by divider
        $text = preg_replace('~[^\pL\d]+~u', $divider, $text);

        // transliterate
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        // trim
        $text = trim($text, $divider);

        // remove duplicate divider
        $text = preg_replace('~-+~', $divider, $text);

        // lowercase
        $text = strtolower($text);

        if (empty($text)) {
            return 'n-a';
        }

        return $text;
    }

    public static function egps_stripAccents($str) {
        return strtr(utf8_decode($str), utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝíóőúű'), 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUYioouu');
    }

    public static function egps_getlogo(){
        $logo = get_theme_mod( 'custom_logo' );

        if( $logo == "405" ){ // error code
            return array( 0 => "");
        }

        $image = wp_get_attachment_image_src( $logo , 'full' );
        //$image_url = $image[0];
        //$image_width = $image[1];
        //$image_height = $image[2];

        return $image;
    }

    public static function uninstall() {
        global $wpdb;
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '%egps_%'");
    }

}