<?php
namespace WpBookingProFrontend\app\helpers;

use BenMajor\ExchangeRatesAPI\ExchangeRatesAPI;
use WpBookingPro\Factory;
use WpBookingPro\Utilities\Utility;

class FrontendHelper
{

    public static function format_currency($price = 0)
    {
        $appConfig = Factory::getAppConfig();
        $default_currency = $appConfig->get('default_currency','');
        $current_currency = isset($_SESSION['currency']) ? sanitize_text_field($_SESSION['currency']) : sanitize_text_field($default_currency);
        $format = static::getFormatCurrentCurrency();
        $rate = static::getExchangeRate($current_currency);
        $price = round($rate * $price, 2);
        return "$format $price";
    }
    public static function get_order_appointment_from_order_woocommerce($order_woo) {
        $db= Factory::getDBO();
        $query = $db->getQuery(true);
        $query->select('wborder.id')
            ->from(Utility::getTableName('order').' AS wborder')
            ->where('wborder.open_source_order_id='.(int)$order_woo)
            ;
        $order_id = $db->setQuery($query)->loadResult();
        return $order_id;
    }
    public static function write_log($log) {
        if (true === WP_DEBUG) {
            if (is_array($log) || is_object($log)) {
                error_log(print_r($log, true));
            } else {
                error_log($log);
            }
        }
    }
    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 checkUserDemo() {
        $result = array();
        $is_ok = false;
        $config = Factory::getConfig();
        $environment = $config->get('environment', 'production');
        $user_id_login = isset($_SESSION['user_id']) ? sanitize_text_field($_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 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']) ? sanitize_text_field($_SESSION['currency']) : sanitize_text_field($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;
    }

}