<?php
namespace WpBookingProAdmin\app\helpers;

use BenMajor\ExchangeRatesAPI\ExchangeRatesAPI;
use WpBookingPro\Factory;
use WpBookingPro\Filesystem\File;
use WpBookingPro\Mvc\Model\Model;
use WpBookingPro\Utilities\Utility;
use WpBookingProFrontend\app\helpers\FrontendHelper;

class AdminHelper
{
    public static $list_key_appointment_properties=array(
      'event'=>"event",
      'package'=>'package',
      'service'=>'service',
      'employee'=>'employee',
      'customer'=>'customer',
      'category'=>'category',
      'coupon'=>'coupon',
    );
    public static function getWpBookingEventKey(){
        return self::$list_key_appointment_properties['event'];
    }
    public static function getWpBookingPackageKey(){
        return self::$list_key_appointment_properties['package'];
    }
    public static function getWpBookingServiceKey(){
        return self::$list_key_appointment_properties['service'];
    }
    public static function getWpBookingEmployeeKey(){
        return self::$list_key_appointment_properties['employee'];
    }
    public static function getWpBookingCustomerKey(){
        return self::$list_key_appointment_properties['customer'];
    }
    public static function getWpBookingCategoryKey(){
        return self::$list_key_appointment_properties['category'];
    }
    public static function getWpBookingCouponKey(){
        return self::$list_key_appointment_properties['coupon'];
    }


    public static function checkSyncOrderstatus() {
        $list_order_status_woo = wc_get_order_statuses();
        $arr_key_order = [];
        foreach ($list_order_status_woo as $key =>$value) {
            array_push($arr_key_order, str_replace('wc-','',$key));
        }
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->select('order_status.open_source_order_status_id')
            ->from(Utility::getTableName('order_status').' AS order_status')
            ;
        $list_order_status_appointment = $db->setQuery($query)->loadColumn();
        $compare_result = array_diff($arr_key_order,$list_order_status_appointment);
        if(count((array)$compare_result)) {
            return false;
        }
        return true;

    }
    public static function getDateOfWeekDayInMonth($date_start, $date_end, $day_of_week=array()) {
        $date_recurring = array();
        if(!empty($day_of_week)) {
            foreach ($day_of_week as $day) {
                switch ($day) {
                    case "monday":
                        $date_recurring["monday"] = self::getDayOfWeekInRange($date_start, $date_end, 'monday');
                        break;
                    case "tuesday":
                        $date_recurring["tuesday"] = self::getDayOfWeekInRange($date_start, $date_end, 'tuesday');
                        break;
                    case "wednesday":
                        $date_recurring["wednesday"] = self::getDayOfWeekInRange($date_start, $date_end, 'wednesday');
                        break;
                    case "thursday":
                        $date_recurring["thursday"] = self::getDayOfWeekInRange($date_start, $date_end, 'thursday');
                        break;
                    case "friday":
                        $date_recurring["friday"] = self::getDayOfWeekInRange($date_start, $date_end, 'friday');
                        break;
                    case "saturday":
                        $date_recurring["saturday"] = self::getDayOfWeekInRange($date_start, $date_end, 'saturday');
                        break;
                    case "sunday":
                        $date_recurring["sunday"] = self::getDayOfWeekInRange($date_start, $date_end, 'sunday');
                        break;
                }
            }
        } else {
            return $date_recurring;
        }
        return  $date_recurring;

    }
    public static function getDayOfWeekInRange($dateFromString, $dateToString, $day='')
    {

        $dateFrom = new \DateTime($dateFromString);
        $dateTo = new \DateTime($dateToString);
        $dates = [];
        if(strtolower(date('l',strtotime($dateFromString))) == $day) {
            $dates[] = $dateFromString;
        }

        if ($dateFrom > $dateTo) {
            return $dates;
        }


        if (1 != $dateFrom->format('W')) {
            $dateFrom->modify('next '.$day);
        }

        while ($dateFrom <= $dateTo) {
            $dates[] = $dateFrom->format('Y-m-d');
            $dateFrom->modify('+1 week');
        }

        return $dates;
    }

    public static function setPermission(){
        $uri = Factory::getUri();
        $page = $uri->getVar('page','');
        $path = $uri->getPath();
        $modelPermission = Model::getInstance('permission');
        $permission = $modelPermission->getPermission();
        if(strpos($path,'sellercenter') == false && trim($page) != '') {
            foreach ($permission as $key => $value) {
                $key = 'wb_'.$key;
                $value = json_decode($value);
                if($key == $page && is_array($value) && in_array('edit',$value)) {
                    return true;
                }
            }
        } else {
            foreach ($permission as $key => $value) {
                $key = 'wb_'.$key;
                $value = json_decode($value);
                if(strpos($path, $key) !== false && is_array($value) && in_array('edit',$value)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static function checkInstalled()
    {
        $app = Factory::getApplication(1);
        $db = Factory::getDBO();
        $installed = true;
        $list_table_in_database = $db->setQuery("SHOW TABLES LIKE " . $db->quote("woobooking\\_%"))->loadColumn();
        if (count($list_table_in_database) == 0) {
            $installed = false;
        }
        $json_table_need_install = File::read(WPBOOKINGPRO_PATH_ROOT . "/install/tables.json");

        $json_table_need_install = json_decode($json_table_need_install);

        foreach ($json_table_need_install as $need_table) {
            if (!in_array($need_table, $list_table_in_database)) {
                $installed = false;
                break;
            }
        }

        return $installed;
    }

    public static function get_editable_roles() {
    global $wp_roles;

    $all_roles = $wp_roles->roles;
    $editable_roles = apply_filters('editable_roles', $all_roles);

    return $editable_roles;
    }

    public static function get_list_table()
    {
        $db = Factory::getDBO();
        $list_table = $db->setQuery("SHOW TABLES LIKE " . $db->quote("woobooking\\_%"))->loadColumn();
        return $list_table;
    }

    public static function get_table_user_demo($blog_id){
        $db = Factory::getDBO();
        $list_table = $db->setQuery("SHOW TABLES LIKE " . $db->quote("wp_$blog_id\\_%\\_woobooking\\_%"))->loadColumn();
        return $list_table;
    }

    public static function getUserInfo() {
        $modelUser = Model::getInstance('user');
        $user = $modelUser->getUserInfo();
        return $user;
    }

    public static function checkUserDemo() {
        $result = array();
        $is_ok = false;
        $config = Factory::getConfig();
        $environment = $config->get('environment', 'production');
        $user_id_login = isset($_SESSION['user_id'])?$_SESSION['user_id']:'';
        if(is_admin()) {
            $user = wp_get_current_user();
        } else {
            $user = get_userdata($user_id_login);
        }


        $is_exist_wp_mp_demo_sandboxes = Utility::checkTableExist('wp_mp_demo_sandboxes');
        $is_exist_wp_mp_demo_users = Utility::checkTableExist('wp_mp_demo_users');
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $blog_id = '';
        if($is_exist_wp_mp_demo_sandboxes && $is_exist_wp_mp_demo_users) {
            $query->clear()
                ->select('wp_mp_demo_sandboxes.blog_id')
                ->from('wp_mp_demo_sandboxes AS wp_mp_demo_sandboxes')
                ->leftJoin('wp_mp_demo_users AS wp_mp_demo_users ON wp_mp_demo_users.user_id = wp_mp_demo_sandboxes.user_id')
                ->where('wp_mp_demo_users.wp_user_id='.(int)(is_admin()?$user->ID:$user_id_login))
            ;
            $blog_id = $db->setQuery($query)->loadResult();
        }
        if($environment == 'demo' && $user && trim($blog_id) != '' && $blog_id > 0) {
            $is_ok =  true;
        }
        $result['blog_id'] = $blog_id;
        $result['is_demo'] = $is_ok;
        return $result;
    }

    public static function checkImageData($baseurl, $image) {
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once (ABSPATH . '/wp-admin/includes/file.php');
            WP_Filesystem();
        }
        $file = $baseurl.'/'.$image;
        $data =  $wp_filesystem->get_contents($file);
        if(trim($data) != '') {
            return true;
        }
        return false;
    }

    public static function getListCurrencySupported() {
        $lookup = new ExchangeRatesAPI();
        $currencies  = $lookup->getSupportedCurrencies();
        return $currencies;
    }

    public static function getExchangeRate($to) {
        $appConfig = Factory::getAppConfig();
        $default_currency = $appConfig->get('default_currency','');
        $lookup = new ExchangeRatesAPI();
        if($default_currency == 'EUR' && $to == 'EUR') {
            $rates  = 1;
        } else {
            $rates  = $lookup->addRate($to)->setBaseCurrency($default_currency)->fetch()->getRate();
        }

        return $rates;

    }

    public static function getFormatCurrentCurrency() {
        $appConfig = Factory::getAppConfig();
        $default_currency = $appConfig->get('default_currency','');
        $current_currency = isset($_SESSION['currency'])?$_SESSION['currency']: $default_currency;
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->select('symbol_currency')
            ->from(Utility::getTableName('currency'))
            ->where('unit_currency='.$query->quote($current_currency))
        ;
        $format = $db->setQuery($query)->loadResult();
        return $format;
    }
    public static function getFormatDefaultCurrency() {
        $appConfig = Factory::getAppConfig();
        $default_currency = $appConfig->get('default_currency','');
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->select('symbol_currency')
            ->from(Utility::getTableName('currency'))
            ->where('unit_currency='.$query->quote($default_currency))
        ;
        $format = $db->setQuery($query)->loadResult();
        return $format;
    }

    public static function getListCurrencyUsed() {
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->select('unit_currency')
            ->from(Utility::getTableName('currency'))
        ;
        $list_currency_used = $db->setQuery($query)->loadColumn();
        return $list_currency_used;
    }


}