<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
require 'vendor/autoload.php';

class Sendmail
{
	
	function __construct()
	{
		$this->apiKey = 'testmail';
		
		//please use this Pickupstix API, which just grant full access.
		$this->sendgridKey = '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';
	}

	function send_mail($data=array()) {
		if(!empty($data)) {
			$email = new \SendGrid\Mail\Mail();
			$email->setFrom("donotreply@pickupstix.com", "Pickup Stix Updates");
			$email->setSubject($data['sub']);
			$email->addTo($data['to']);
			// $email->addContent("text/plain", "Email without footer");
			$email->addContent(
			    "text/html", $data['template']
			);

			/*$request_body = json_decode('{
			    "enabled": false,
			    "html_content": "",
			    "plain_content": ""
			}');*/

			$sendgrid = new \SendGrid($this->sendgridKey);
			// $result = $sendgrid->client->mail_settings()->footer()->patch($request_body);
			try {
			    $response = $sendgrid->send($email);
			    /*print $response->statusCode() . "\n";
			    print_r($response->headers());
			    print $response->body() . "\n";*/
			    if($response->statusCode()==202) {
			    	return json_encode(array('status'=>'success', 'msg'=>'Mail sent successfully'));
			    }
			} catch (Exception $e) {
			    return json_encode(array('status'=>'error', 'msg'=>'Caught exception: '. $e->getMessage()));
			}
		} else {
			return json_encode(array('status'=>'error', 'msg'=>'No data received'));
		}
	}

	function test() {
		$sg = new \SendGrid($this->sendgridKey, ["impersonateSubuser" => ""]);
		try {
		    $response = $sg->client->mail_settings()->footer()->get();
		    print $response->statusCode() . "\n";
		    print_r($response->headers());
		    print $response->body() . "\n";
		} catch (Exception $ex) {
		    echo 'Caught exception: '.  $ex->getMessage();
		}
	}

}

$mail = new Sendmail();
header('content-type: application/json');
echo $mail->send_mail($_POST);
// echo $mail->send_mail(array('to'=>'sarath.inkrefuge@gmail.com', 'sub'=>'test mail', 'template'=>'test mail check footer'));
// print_r($mail->test());

?>