<?php
session_start();
require_once "../../config.php";
require_once "../../../validation.php";
require_once "../../../Helper.php";
require_once '../../database1.php';
require_once "../../check_admin.php";

$databaseFile = '../../../uploads/geolite/ip.mmdb';
require_once "../../../translation.php";
require_once "../../../translation_ee.php";
require_once "../../../translation_lt.php";
require_once "../../../translation_en.php";
require_once "../../../translation_fi.php";

require_once "../../../ajax/send_email.php";

class sendEmail extends database
{
   	public function index($data, $from)
    {
    	$data['cl_from'] = $from;
        return $this->insert('tb_mailbox',$data);
    }

    public function getAllCustomers()
    {
    	return $this->fetchAll('user', ['user_type' => 'customer']);
    }

    public function getAllCustomersRegisteredLastThreeDays()
    {
    	$sql = '  SELECT email,cl_name FROM user WHERE user_type="customer" AND cl_deleted_at IS NULL AND cl_created_at>=? ';
    	$where[] = date('Y-m-d', strtotime('-3 days'));
    	return $this->callQuery($sql, $where);
    }

    public function getAllCustomersWithItemOrderedStatus()
    {
    	$sql = ' SELECT u.email,u.cl_name FROM tb_checkout c INNER JOIN user u ON c.cl_user_id=u.id WHERE c.cl_deleted_at IS NULL AND c.cl_status="Items ordered" GROUP BY u.id ';
    	return $this->callQuery($sql);
    }

    public function getAllCustomersWithShippedStatus()
    {
    	$sql = ' SELECT u.email, u.cl_name FROM tb_checkout c INNER JOIN user u ON c.cl_user_id=u.id WHERE c.cl_deleted_at IS NULL AND c.cl_status="Shipped" GROUP BY u.id ';
    	return $this->callQuery($sql);
    }

    public function getAllBlockedContacts()
    {
    	return $this->fetchRow('tb_blocked');
    }
}


$obj = new sendEmail();   
if(!isset($_POST['data']))
{
	http_response_code(400);
	echo json_encode(array('No input found'));
	exit;
}

$data = $_POST['data'];
$helper = new Helper();
$validation = new validation();

$data = $helper->changeSerialzeArrayValues($data);

$res = array();
if($data['email_to'] == 'Custom Emails')
{
	$requiredFields = array('to', 'subject', 'body', 'email_to');
}
else
{
	$requiredFields = array('subject', 'body', 'email_to');
}
$return = $validation->checkRequired($requiredFields, $data);
if($return)
{
	$res['error_description'][] = $return;
}


if(!empty($res['error_description']))
{
	$result['error_description'] = $validation->setErrors($res['error_description']);
	$result['error_text'] = $validation->setErrors($res['error_description']);

	http_response_code(400);
	echo json_encode($result);
	exit;
}

$data = $validation->removeEmptyValues($data);

$emailTo = $data['cl_email_to'];
unset($data['cl_email_to']);
$res = $obj->index($data, MAILGUN_FROM);
if(!$res)
{
	http_response_code(401);
	echo json_encode(array('error_text' => 'Something Went Wrong'));
	exit;
}

$blockedContacts = $obj->getAllBlockedContacts();
$blockedContactsArray = explode(',', $blockedContacts['cl_emails']);


# Include the Autoloader (see "Libraries" for install instructions)
/*require '../../../vendor/autoload.php';
use Mailgun\Mailgun;*/
# Instantiate the client.
//$mgClient = new Mailgun('e2fe7da08654f7bc014d1804c5472e79-4167c382-083075dd');
//$domain = "efix.lv";
# Make the call to the client.
/*$result = $mgClient->sendMessage($domain, array(
	'from'	=> 'Excited User <mailgun@sandbox1859b15781e846af8c59f8993d3822bd.mailgun.org>',
	'to'	=> 'Shayas <shayasmk@gmail.com>',
	'subject' => 'Hello',
	'text'	=> 'Testing some Mailgun awesomness!'
));*/

// First, instantiate the SDK with your API credentials
//$mg = Mailgun::create('e2fe7da08654f7bc014d1804c5472e79-4167c382-083075dd'); // For US servers
//$mg = Mailgun::create(MAILGUN_API_KEY, 'https://api.eu.mailgun.net'); // For EU servers

// Now, compose and send your message.
// $mg->messages()->send($domain, $params);


/*
foreach($toArray AS $to)
{
	$mg->messages()->send(MAILGUN_DOMAIN, [
	  'from'    => MAILGUN_FROM,
	  'to'      => $to,
	  'subject' => $data['cl_subject'],
	  'text'    => 'You cannot view this email. YOu need an html enabled email client',
	  'html'	=> $data['cl_body']
	]);
}*/




use Mailgun\Mailgun;
# Instantiate the client.
//$mgClient = new Mailgun('816d5bea526363625ca7f1abc032d8de-32a0fef1-d49ae232');
$mgClient = Mailgun::create('bf38fc09fc6bbcbffc558526b3437f16-32a0fef1-a2b204a2', 'https://api.eu.mailgun.net');
$domain = "newsletter.axo.lv";
# Make the call to the client.


$toAddress = '';


if($emailTo == 'Custom Emails')
{
	$emailCount = 0;
	$toArray1 = explode(',', $data['cl_to']);
	
	foreach($toArray1 AS $to)
	{
		
		if(trim($to) != '' && filter_var(trim($to), FILTER_VALIDATE_EMAIL) && !in_array($to, $blockedContactsArray))
		{
		    $toAddress.= trim($to) . ',';
			$toArray[$emailCount]['email'] = trim($to);
			$toArray[$emailCount]['name'] = trim($to);
			$emailCount++;
		}
	}
}
else if($emailTo == 'Last 3 Days')
{
	$emailCount = 0;
	$customers = $obj->getAllCustomersRegisteredLastThreeDays();
	foreach($customers AS $customer)
	{	
		if(trim($customer['email']) != '' && filter_var($customer['email'], FILTER_VALIDATE_EMAIL) && !in_array($customer['email'], $blockedContactsArray))
		{
		    $toAddress.= trim($customer['email']) . ',';
			$toArray[$emailCount]['email'] = $customer['email'];
			$toArray[$emailCount]['name'] = $customer['cl_name'];
			$emailCount++;
		}
	}
}
else if($emailTo == 'Item Ordered Status')
{
	$emailCount = 0;
	$customers = $obj->getAllCustomersWithItemOrderedStatus();
	foreach($customers AS $customer)
	{	
		if(trim($customer['email']) != '' && filter_var($customer['email'], FILTER_VALIDATE_EMAIL) && !in_array($customer['email'], $blockedContactsArray))
		{
		    $toAddress.= trim($customer['email']) . ',';
			$toArray[$emailCount]['email'] = $customer['email'];
			$toArray[$emailCount]['name'] = $customer['cl_name'];
			$emailCount++;
		}
	}
}
else if($emailTo == 'Shipped Status')
{
	$emailCount = 0;
	$customers = $obj->getAllCustomersWithShippedStatus();

	
	foreach($customers AS $customer)
	{	
		if(trim($customer['email']) != '' && filter_var($customer['email'], FILTER_VALIDATE_EMAIL) && !in_array($customer['email'], $blockedContactsArray))
		{
		    $toAddress.= trim($customer['email']) . ',';
			$toArray[$emailCount]['email'] = $customer['email'];
			$toArray[$emailCount]['name'] = $customer['cl_name'];
			$emailCount++;
		}
	}
}
else
{
	$emailCount = 0;
	$customers = $obj->getAllCustomers();
	foreach($customers AS $customer)
	{	
		if(trim($customer['email']) != '' && filter_var($customer['email'], FILTER_VALIDATE_EMAIL) && !in_array($customer['email'], $blockedContactsArray))
		{
		    $toAddress.= trim($customer['email']) . ',';
			$toArray[$emailCount]['email'] = $customer['email'];
			$toArray[$emailCount]['name'] = $customer['cl_name'];
			$emailCount++;
		}
	}
}




$body = '<table style="width:100%;max-width:800px;margin:0 auto;font-family:arial;color:#595151">'
 . $data['cl_body'] . 
                            '<tr>
                                <th style="text-align: center;padding-top: 81px;font-size: 18px">
                                  ' . lang('Paldies, ka izvēlējāties Axo.lv', $language) . '!
                                </th>
                              </tr>
                             </table>';

//foreach($toArray AS $to)
//{
	//send_email( $toArray, '', $data['cl_subject'], $body, null, 1, 1);
//}


$result = $mgClient->messages()->send($domain, array(
	'from'	=> 'AXO.LV - Interneta veikals <info@newsletter.axo.lv>',
	'to'	=> 'Axo <info@axo.lv>',
	'subject' => $data['cl_subject'],
	'html'	=> $body,
    'bcc'   => $toAddress	
));


session_start();
$_SESSION['error_message'] = 'Email Sent Succesfully';
$_SESSION['error_type'] = 'success';

http_response_code(200);
echo json_encode(array('message' => 'Email Sent Succesfully'));
exit;