<?php
/**
 * @TODO remove ng-repeat end and start from sending email
 */
class MaApplication extends MaSingleton {

    private $_order = null;
    private $_wcEmail = null;
    private $_activatedTemplate = 1;
    private $_sendingEmailKey = null;
    private $_slug = null;

    /**
     *
     * @var MaEmail 
     */
    private $_email = null;

    /**
     *
     * @var MaConfig 
     */
    private $_config = null;
    private $_nonce = null;
    private $_wcTemplatesToOveride = array(
        'customer-completed-order',
        'admin-new-order'
    );

    public function init() {
        add_filter('wc_get_template', array($this, 'checkTemplate'), 10, 5);
        //Plugin actions
        add_action('ma_multiple_emails', array($this, 'getMultipleEmails'), 10, 2);
        add_action('ma_email_head', array($this, 'emailHead'), 12, 2);
        add_action('ma_email_body', array($this, 'emailBody'), 12, 2);
        add_action('ma_email_foot', array($this, 'emailFooter'), 12, 2);
        add_action('ma_items_loop', array($this, 'itemsLoop'), 12, 5);


        $this->_config = MaConfig::getInstance();
        $this->_config->init();
        $this->_activatedTemplate = $this->_config->activeTemplate;
        add_action('init', array($this, 'afterWpInit'));
    }

    public function itemsLoop($order, $email, $separator = '', $start = '', $end = '') {

        if ($this->_email->isPreview()) {
            echo $start ?  $start : "<ng-repeat ng-repeat='item in products'>";
            
            echo $this->_email->getPart('item-loop');
            //echo '<ng-show ng-show="$last">'.$separator.'</ng-show>';
            echo $end ? $end :  "</ng-repeat>";
        } else {

            if (!is_null($order)) {
                $templateEngine = MaTemplateEngine::getInstance();
                $templateEngine->setOrder($order);
                $items = $order->get_items();
                $index = 0;
                foreach ($items as $item) {
                    $_product = apply_filters('woocommerce_order_item_product', $order->get_product_from_item($item), $item);
                    $item_meta = new WC_Order_Item_Meta($item, $_product);
                    $templateEngine->setCurrentItem($item);
                    $templateEngine->setCurrentProduct($_product);
                    $templateEngine->initProductReplaceVars();
                    $templateEngine->setItemMeta($item_meta);

                    $index++;
                    if(isset($start)){
                        echo $start;
                    }
                    echo $templateEngine->parseProductTemplate($this->_email->getPart('item-loop', true));
                    if(isset($end)){
                        echo $end;
                    }
                    if($index != count($items)){
                        echo $separator;
                    }
                }
            }
        }
    }

    public function setEmail(MaEmail $email) {

        $this->_email = $email;
    }

    public function afterWpInit() {
        $this->_nonce = wp_create_nonce('ma-ajax-nonce');
    }

    public function emailHead($order, $email) {
        $engine = MaTemplateEngine::getInstance();
        $engine->setOrder($order);
        $this->_email->setOrder($order);
        $this->_email->setWcEmail($email);
        echo $engine->parseTemplate($this->_email->getPart('header'));
    }

    public function emailBody($order, $email) {
        $engine = MaTemplateEngine::getInstance();
        $engine->setOrder($order);
        $this->_email->setOrder($order);
        $this->_email->setWcEmail($email);

        echo $engine->parseOrderVariables($engine->parseTemplate($this->_email->getPart('body', true)));
    }

    public function emailFooter($order, $email) {
        $engine = MaTemplateEngine::getInstance();
        $engine->setOrder($order);
        $this->_email->setOrder($order);
        $this->_email->setWcEmail($email);
        echo $engine->parseTemplate($this->_email->getPart('footer'));
    }

    public function initAjax() {

        add_action('wp_ajax_ma_ajax_main', array($this, 'ajaxFrontController'));
        add_action('wp_ajax_ma_ajax_main', array($this, 'ajaxFrontController'));
    }

    public function __get($property) {
        $propName = "_" . $property;
        if (property_exists($this, $propName)) {
            return $this->$propName;
        } else {
            return null;
        }
    }

    public function __set($name, $value) {
        $propName = '_' . $name;
        if (property_exists($this, $propName)) {
            $this->$propName = $value;
        }
    }

    public function saveConfig($data = null) {
        if (is_null($data)) {
            $data = file_get_contents('php://input');
            
            $resp = update_option(MaConfig::getInstance()->slug . '-order-' . $_REQUEST['order'], base64_encode($data));

            if (!$resp) {
                return array(
                    'error' => true,
                    'message' => __("Can't save changes in database")
                );
            }
            return array(
                'error' => false,
                'message' => __("Your changes have been successfuly saved")
            );
        }
    }

    public function ajaxFrontController() {

        if (!check_ajax_referer('ma-ajax-nonce', 'nonce')) {
            wp_die();
        }
        $func = $_REQUEST['func'];

        if (!empty($func) && method_exists($this, $func)) {
            echo json_encode($this->$func());
        }
        exit;
    }

    public function getGoogleFonts() {

        $curl = new Curl();
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        $curl->get('https://www.googleapis.com/webfonts/v1/webfonts', array(
            'key' => $this->_config->appConfig['google-api-key'],
            'sort' => 'popularity'
        ));
        if (!$curl->error) {
            $reponse = new stdClass();
            $curl->response->items = array_slice($curl->response->items, 0, 50);
            
            return $curl->response;
        } else {
            return array(
                'error' => true,
                'message' => $curl->errorMessage
            );
        }
    }

    public function checkTemplate($located, $template_name, $args, $template_path, $default_path) {


        $pathParts = explode('/', str_replace('.php', '', $template_name));
        $supportedTypes = $this->_config->appConfig['emailTypes'];
        $emailKeys = array_keys($supportedTypes);


        if (in_array('emails', $pathParts) && !in_array('plain', explode('/', $template_name))) {

            foreach ($emailKeys as $key) {
                $dashedKey = str_replace('_', '-', $key);

                if (in_array($dashedKey, $pathParts)) {
                    $this->_sendingEmailKey = $key;
                    break;
                }
            }
        }


        if (!is_null($this->_sendingEmailKey)) {

            $this->_config = MaConfig::getInstance();

            $this->_email = new MaEmail($this->_config->activeTemplate, false);

            $this->_email->setEamilType($this->_sendingEmailKey);



            MaTemplateEngine::getInstance()->initGlobalVars($this->_config->getEmailConfig($this->_activatedTemplate), $this->_sendingEmailKey);

            return MA_ROOT . 'emails' . DS . 'order-' . $this->_activatedTemplate . DS . 'main.php';
        }
        return $located;
    }

    public function getMultipleEmails($emailType, $fileName) {

        $previewMode = isset($_GET['order']) && isset($_GET['page']) && $_GET['page'] === $this->_config->slug ? true : false;

        if ($previewMode) {
            foreach ($this->_config->appConfig['emailTypes'] as $key => $args) {
                echo '<ng-show ng-show="currentType === \'' . $key . '\'">';
                
                echo str_replace('%s%', $key, $this->_email->getMultipleEmailPart($fileName));
                echo "</ng-show>";
            }
        } else {

            echo str_replace('%s%', $this->_sendingEmailKey, $this->_email->getMultipleEmailPart($fileName));
        }
    }

    public function isPage($page) {
        return isset($_GET['page']) && $_GET['page'] === $page;
    }

    public function isAction($action) {
        return isset($_GET['action']) && $_GET['action'] === $action;
    }

}
