<?php

/**
 *------------------------------------------------------------------------------.
 *
 * @copyright     Copyright (C) 2004-2020 JoomlArt.com. All Rights Reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       JoomlArt
 * @forum:        https://www.joomlart.com/forums/t/t4-builder
 * @Link:         https://demo.t4-builder.joomlart.com/
 *------------------------------------------------------------------------------
 */

namespace JPB\Editor\Action;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\Registry\Registry;
use Joomla\CMS\Http\HttpFactory;
use Joomla\CMS\Plugin\PluginHelper;

class Contact extends Base
{
    public function run()
    {
        $data = Factory::getApplication()->input;
        $error = self::captchaConfirmation();
        if(count($error) > 0){
            return ['error' => "Invalid input captcha"];
        }
        $task = $data->get('task');
        switch ($task) {
            case 'contact':
                $return = self::contact($data);
                break;

            case 'subscribe':
                if ($data->get('platform') == 'acym') {
                    $return = self::subscribe($data);
                } elseif ($data->get('platform') == 'mailchimp') {
                    $return = self::subscribeMailChimp($data);
                }
                break;
            default:
                $return = ['error' => Text::_('COM_T4PAGEBUILDER_CONTACT_NO_ACTION')];
        }

        return $return;
    }

    public static function subscribe($data)
    {
        $db = Factory::getDbo();
        //get data
        $name = $data->getVar('name');
        $email = $data->getVar('email');
        $field_list = explode('@', $data->getVar('hiddenlists'));

        if (empty($name)) {
            $matching = explode('@', $email);
            $name = $matching[0];
        }
        if (self::vali_acymEmail($email)) {
            return ['message' => Text::_('COM_T4PAGEBUILDER_EMAIL_SUBCRIBED')];
        }
        //create user subscribe and subscribe list
        $user = new \stdClass();
        $user->name = $name;
        $user->email = $email;
        $user->key = self::acym_generateKey(14);
        $user->source = 'T4 Page Builder';
        $user->creation_date = date('Y-m-d h:m:s');
        $db->insertObject('#__acym_user', $user, 'id');
        $userId = $db->insertId();
        foreach ($field_list as $list) {
            $userList = new \stdClass();
            $userList->user_id = $userId;
            $userList->list_id = $list;
            $userList->status = 1;
            $userList->subscription_date = date('Y-m-d h:m:s');
            $db->insertObject('#__acym_user_has_list', $userList);
        }

        return ['message' => Text::_('COM_T4PAGEBUILDER_EMAIL_SUBCRIBE_SUCCESS')];
    }

    public static function contact($data)
    {
        if (empty($data)) {
            return '';
        }
        $dataForm = $data->get('data','','raw');
        foreach ($dataForm as $item) {
            switch ($item['name']) {
                case 'recipient':
                case 'email':
                   $recipient = $item['value'] ? $item['value'] : "";
                    break;
                case 'subject':
                case 'name':
                   $subject = $item['value'] ?: "";
                    break;
                case 'emailtpl':
                case 'message':
                   $emailContent = $item['value']?: "";
                    break;

                default:
                    // code...
                    break;
            }
        }
        if(!isset($recipient)){
            return $return = ['error' => Text::_('COM_T4PAGEBUILDER_CONTACT_SEND_EMAIL_ERROR')];
        }
        $config = Factory::getConfig();
        $result = false;
        if($emailContent) $emailContent = self::getEmailBody($dataForm, $emailContent);
        $fromName = $config->get('fromname');
        $fromEmail = $config->get('mailfrom');
        $result = self::sendEmail($recipient, $subject, $emailContent, $fromName, $fromEmail);
        if ($result) {
            $return = ['message' => Text::_('COM_T4PAGEBUILDER_CONTACT_SEND_EMAIL_MESSAGE')];
        } else {
            $return = ['error' => Text::_('COM_T4PAGEBUILDER_CONTACT_SEND_EMAIL_ERROR')];
        }

        return $return;
    }

    public static function sendEmail($recipient, $subject, $emailBody, $fromname, $fromemail)
    {
        $res = Factory::getMailer()->sendMail(
            $fromemail,
            $fromname,
            $recipient,
            $subject,
            $emailBody,
            true
        );

        return $res;
    }

    public static function getEmailBody($data, $emailContent)
    {
        foreach ($data as $item) {
            $emailContent = str_replace('{'.$item['name'].'}', $item['value'], $emailContent);
        }

        return $emailContent;
    }

    public static function getUsers()
    {
        $db = Factory::getDbo();

        return $db->setQuery('select name,email from #__users WHERE sendEmail = "1"')->loadObjectList();
    }

    public static function acym_generateKey($length)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        $max = strlen($characters) - 1;
        for ($i = 0; $i < $length; ++$i) {
            $randstring .= $characters[mt_rand(0, $max)];
        }

        return $randstring;
    }

    public static function vali_acymEmail($email)
    {
        $db = Factory::getDbo();
        $q = 'SELECT EXISTS(SELECT * FROM #__acym_user WHERE email = '.$db->quote($email).')';

        return $db->setQuery($q)->loadResult();
    }

    public static function subscribeMailChimp($data)
    {
        $dataForm = $data->getVar('data');
         //API Details
        $apiKey = '05540c5ec38f8c15dad8871f5f563859-us5';
        $listId = '78869976d3';
        $firstname = '';
        $lastname = '';
        foreach ($dataForm as $field) {
            if($field['value']){
                if($field['name'] == 'email'){
                    $email = $field['value'];
                }elseif ($field['name'] == 'api') {
                    $apiKey = $field['value'];
                }elseif($field['name'] == 'list_id'){
                    $listId = $field['value'];
                }
            }
        }
        if ($email) {
            //Create mailchimp API url
            $memberId = md5(strtolower($email));
            $dataCenter = substr($apiKey, strpos($apiKey, '-') + 1);
            $url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/lists/'.$listId.'/members/'.$memberId;

            //Member info
            $dataMember = [
            'email_address' => $email,
            'status' => 'subscribed',
            'merge_fields' => [
                'FNAME' => $firstname,
                'LNAME' => $lastname,
            ],
            ];
            $jsonString = json_encode($dataMember);

            // send a HTTP POST request with curl
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_USERPWD, 'user:'.$apiKey);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);
            $result = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            //Collecting the status
            switch ($httpCode) {
                case 200:
                    $msg = ['message'=>'Success, newsletter subcribed using mailchimp API'];
                    break;
                case 214:
                    $msg = ['message'=>'Already Subscribed'];
                    break;
                default:
                    $msg = ['error' => 'Oop, Email can not subscribe. Please contact the admin'];
                    break;
            }
        }else{
            $msg = ['error'=> 'Oops, please try again. Please add email'];
        }

        return $msg;
    }
    public static function captchaConfirmation()
    {
        $mainframe = Factory::getApplication();
        $captcha = PluginHelper::importPlugin('captcha', 'recaptcha');
        $captcha_inv = PluginHelper::importPlugin('captcha', 'recaptcha_invisible');
        $sitekey='';
        $secretkey='';
        $error = array();
        $captcha_systems='';
        if ($captcha || $captcha_inv) {
            $cp_plugin = PluginHelper::getPlugin('captcha', 'recaptcha');
            
            if (!empty($cp_plugin)) {
                $cp_plgParams = new Registry($cp_plugin->params);
                $sitekey = $cp_plgParams->get('public_key' , '');
                $secretkey = $cp_plgParams->get('private_key' , '');
            }else{
                $_cp_plugin = PluginHelper::getPlugin('captcha', 'recaptcha_invisible');
                $_cp_plgParams = new Registry($_cp_plugin->params);
                if ($sitekey == '')
                    $sitekey = $_cp_plgParams->get('public_key', '');
                if ($secretkey == '')
                    $secretkey = $_cp_plgParams->get('private_key', '');
            }
       
            $data = $mainframe->input->post->get('data','','raw');
            $grecaptcha = '';
            foreach ($data as $post) {
                if($post['name'] == 'g-recaptcha-response'){
                    $grecaptcha = $post['value'];
                }
            }
            $res = array(true);
            // the check had failed so we tempo remove the check.
            $uri = 'https://www.google.com/recaptcha/api/siteverify?response='.$grecaptcha.'&secret=' . $secretkey . '&remoteip=' . $_SERVER['REMOTE_ADDR'];
            $headers = new \stdClass;
            $headers->Origin = 'https://www.google.com';

            $options = new Registry;
            $options->set('headers', $headers);
            $options->set('userAgent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36');

            $http = HttpFactory::getHttp($options);
            $response = $http->get($uri);

            $body = $response->body;
            if (is_string($body)) {
                $response = new Registry($body);
            }
            if ($response->get('success') == false) {
                $error['captcha_code'] = $response->get('error-codes')[0];
            }
        }

        return $error;
    }
}
