<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Email_model extends CI_Model {
	public function xss_html_filter($input){
		return $this->security->xss_clean(html_escape($input));
	}
	//UPDATE SMS API
	public function api_update(){
		extract($this->xss_html_filter(array_merge($this->data,$_POST,$_GET)));
		//print_r($this->xss_html_filter(array_merge($this->data,$_POST,$_GET)));exit();
		$store_id = get_current_store_id();
		$this->db->trans_begin();
		if($hidden_rowcount>0){
		$this->db->query("delete from db_emailapi where store_id=".$store_id);
		$this->db->query("ALTER TABLE db_emailapi AUTO_INCREMENT = 1");
			for($i=1; $i<=$hidden_rowcount; $i++){
				if(isset($_POST['info_'.$i])){
					$info 	 	= $_POST['info_'.$i];
					$key 	 	= $_POST['key_'.$i];
					$key_value 	= $_POST['key_val_'.$i];
					
					$q1=$this->db->query("insert into db_emailapi(
								info,`key`,key_value,store_id)
								values(
								'$info',
								'$key',
								'$key_value',
								$store_id
							)");
					if(!$q1){
						return "failed";
					}

				}//if end()
			}//for end()	
		}

		$q2=$this->db->query("update db_store set email_status=$email_status where id=".$store_id);
		if(!$q2){
			return "failed";
		}

		//save Twilio SMS API
		$twilio = array('account_sid' => $account_sid,'auth_token'=>$auth_token,'twilio_phone'=>$twilio_phone );
		$q1=$this->db->select("*")->where("store_id",$store_id)->get("db_twilio");
        if($q1->num_rows()>0){
          $q2 = $this->db->where("store_id",$store_id)->update("db_twilio",$twilio);
        }
        else{
        	$twilio = array_merge($twilio,array('store_id' => $store_id));
        	$q2=$this->db->insert("db_twilio",$twilio);
        }

        if(!$q2){
        	return "failed";
        }

			$this->session->set_flashdata('success', 'Record Successfully Saved!!');
			$this->db->trans_commit();
		    return "success";
	}

	//Send email
	public function send_email(array $content){
		// Extract and validate – do NOT pass whole array through xss_html_filter (can corrupt store_id/message)
		$to      = isset($content['to']) ? $this->xss_html_filter($content['to']) : '';
		$subject = isset($content['subject']) ? $this->xss_html_filter($content['subject']) : '';
		$message = isset($content['message']) ? $content['message'] : ''; // keep raw so newlines/special chars not broken
		if (is_string($message)) {
			$message = $this->security->xss_clean($message);
		}

		if (empty($to)) {
			return "You forgot to add Recipient Email Address";
		}
		if (empty($subject)) {
			return "Email Subject should not be empty";
		}

		// Use store_id from content if provided and valid; otherwise current or safe store
		if (isset($content['store_id']) && $content['store_id'] !== null && $content['store_id'] !== '' && (int)$content['store_id'] > 0) {
			$store_id = (int) $content['store_id'];
		} else {
			$store_id = (store_module()) ? 1 : get_current_store_id();
			if ($store_id === null || $store_id === '' || (int)$store_id < 1) {
				$store_id = get_safe_store_id_for_query();
			}
		}

		$store_rec = get_store_details($store_id);
		if (!$store_rec) {
			return "Store configuration not found (store_id " . $store_id . "). Cannot send email.";
		}

		$smtp_status = $store_rec->smtp_status;

		if ($smtp_status) {
			$port = (int) $store_rec->smtp_port;
			$smtp_crypto = '';
			if ($port === 465) {
				$smtp_crypto = 'ssl';
			} elseif ($port === 587 || $port === 25) {
				$smtp_crypto = 'tls';
			}

			$config = array(
				'protocol'     => 'smtp',
				'smtp_host'    => $store_rec->smtp_host,
				'smtp_port'    => $store_rec->smtp_port,
				'smtp_user'    => $store_rec->smtp_user,
				'smtp_pass'    => $store_rec->smtp_pass,
				'crlf'         => "\r\n",
				'newline'      => "\r\n",
				'mailtype'     => 'text',
				'charset'      => 'utf-8',
				'smtp_timeout' => 30,
				'validate'     => false
			);
			if ($smtp_crypto !== '') {
				$config['smtp_crypto'] = $smtp_crypto;
			}

			$this->load->library('email', $config);
			$this->email->clear(true);
			$this->email->to($to);
			$this->email->from($store_rec->smtp_user, $store_rec->store_name);
			$this->email->subject($subject);
			$this->email->message($message);

			if ($this->email->send()) {
				return true;
			}
			$debug = $this->email->print_debugger(array('headers', 'subject', 'body'));
			$err = trim(strip_tags($debug));
			return "SMTP failed (store_id " . $store_id . "). " . ($err ? $err : "Check host, port, user, password, and TLS/SSL (e.g. 587=TLS, 465=SSL).");
		}

		// PHP mail()
		if (mail($to, $subject, $message)) {
			return true;
		}
		return "PHP mail() failed. Turn ON SMTP in Store Settings (store_id " . $store_id . ") and set Host, Port, User, Password for reliable delivery.";
	}

}