<?php

namespace Vinteract\Notifications;

use Vinteract\Resources\Resource;
use Vinteract\API\Response;

use Exception;
use InvalidArgumentException;

class Email extends Resource {
	
	/*
		Properties
	*/
	
	const API_URL = "https://www.mandrillapp.com/api/1.0/messages/send.json";
	const API_KEY = "7W3cKQWNVImpx0oUPX_mGA";
	
	const FROM_EMAIL_ADDRESS = "noreply@vinteract.com.au";
	const FROM_EMAIL_NAME = "V interact";
	
	const SUPPORT_HOURS = "Our support hours are between 9 am and 5 pm on Monday to Friday (ACST)";
	
	const VERIFY_HOST = false;
	const VERIFY_PEER = false;
	
	public $response;
	
	/*
		Constructor
	*/
	
	function __construct($params = []) {
		
		// Construct parent.
		
		parent::__construct();
		
		// Set data.
		
		$this->__set_data($params);
		
		// Required fields.
		
		$this->required = ["to", "subject", "html"];
		
	}
	
	/*
		Methods
	*/
	
    public function send($params = []) {
        
		// Set data.
		
		$this->__set_data($params);
		
		// Validate required fields before trying to send the SMS.
		
		$this->validate_required_fields();
		
		// Payload.
		
		$payload = json_encode([
			"key" => $this::API_KEY,
			"async" => false,
			"message" => array(
				"inline_css" => true,
				"html" => $this->__get_data("html"),
				"subject" => $this->__get_data("subject"),
				"from_email" => $this::FROM_EMAIL_ADDRESS,
				"from_name" => array_key_exists("sender", $params) ? $params["sender"] : $this::FROM_EMAIL_NAME,
				"to" => $this->__get_data("to"),
			),
		]);
		
		// Request.
		
		$ch = curl_init($this::API_URL);
		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this::VERIFY_HOST);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this::VERIFY_PEER);
		curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "Content-Length: " . strlen($payload) ]);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
		curl_setopt($ch, CURLOPT_POST, 1);
		
		$response = json_decode(curl_exec($ch), true);
		
		// Response.
		
		$this->response = new Response([
			"code" => curl_getinfo($ch, CURLINFO_HTTP_CODE),
		]);
		
		// Return response.
		
		return $this->response;
		
    }
	
}
