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

class Smtp extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
	}
	
	//Open SMS Form 
	public function index(){
		$this->permission_check('smtp_settings');
		$data=$this->data;
		$data['page_title']=$this->lang->line('smtp_settings');
		$smtp_rec = get_store_details();
		$data['smtp_status']=$smtp_rec->smtp_status;
		$data['smtp_host']=$smtp_rec->smtp_host;
		$data['smtp_port']=$smtp_rec->smtp_port;
		$data['smtp_user']=$smtp_rec->smtp_user;
		$data['smtp_pass']=$smtp_rec->smtp_pass;
		$this->load->view('smtp', $data);
	}


	//Create Message
	public function send_message(){
		$this->permission_check('send_sms');
		$data=$this->data;
		$this->load->model('sms_model');
		extract($this->security->xss_clean(html_escape($_POST)));
		$result= $this->sms_model->send_sms($mobile,$message);
		echo $result;
	}

	
	//Open SMS API Form 
	public function api(){
		if(!is_admin()){
			show_error("Access Denied", 403, $heading = "Unauthorized Access!!");exit();	
		}
		$this->permission_check('sms_api_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('sms_api');
		$this->load->view('sms-api', $data);
	}

	//UPDATE SMTP – do NOT filter password (xss/html_escape corrupts special chars and breaks SMTP auth)
	public function update_smtp(){
		if(demo_app()){
			echo "Restricted in Demo";exit();
		}
		$this->permission_check_with_msg('smtp_settings');

		$store_id = get_current_store_id();
		if ($store_id === null || $store_id === '' || (int)$store_id < 1) {
			$store_id = get_safe_store_id_for_query();
		} else {
			$store_id = (int) $store_id;
		}

		$filtered = xss_html_filter(array(
			'smtp_status' => isset($_POST['smtp_status']) ? $_POST['smtp_status'] : 0,
			'smtp_host'   => isset($_POST['smtp_host']) ? $_POST['smtp_host'] : '',
			'smtp_port'   => isset($_POST['smtp_port']) ? $_POST['smtp_port'] : '',
			'smtp_user'   => isset($_POST['smtp_user']) ? $_POST['smtp_user'] : '',
		));

		$info = array(
			'smtp_status' => (int) $filtered['smtp_status'],
			'smtp_host'   => trim($filtered['smtp_host']),
			'smtp_port'   => trim($filtered['smtp_port']),
			'smtp_user'   => trim($filtered['smtp_user']),
		);

		// Password: use raw POST only; never run through xss/html_escape (breaks &, <, etc. and SMTP auth)
		$new_pass = isset($_POST['smtp_pass']) ? $_POST['smtp_pass'] : '';
		if ($new_pass !== '') {
			$info['smtp_pass'] = $new_pass;
		}

		$q1 = $this->db->where('id', $store_id)->update('db_store', $info);
		if (!$q1) {
			echo "failed";
			return;
		}
		echo "success";
	}

	// Send a test email using current store SMTP (for debugging)
	public function send_test_email(){
		$out = array('success' => false, 'message' => '');
		if (demo_app()) {
			$out['message'] = 'Restricted in Demo';
			$this->output->set_content_type('application/json')->set_output(json_encode($out));
			return;
		}
		$this->permission_check_with_msg('smtp_settings');

		$to = $this->input->post('test_email');
		if (empty($to) || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
			$out['message'] = 'Please enter a valid email address.';
			$this->output->set_content_type('application/json')->set_output(json_encode($out));
			return;
		}

		$this->load->model('email_model');
		$store_id = 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);
		$store_name = $store_rec && !empty($store_rec->store_name) ? $store_rec->store_name : 'NCS Billing';
		$result = $this->email_model->send_email(array(
			'to'       => $to,
			'subject'  => 'Test email from ' . $store_name,
			'message'  => "This is a test email.\n\nIf you received this, SMTP is working correctly.\n\nSent at " . date('Y-m-d H:i:s'),
			'store_id' => $store_id,
		));

		if ($result === true) {
			$out['success'] = true;
			$out['message'] = 'Test email sent to ' . $to . '. Check inbox (and spam).';
		} else {
			$out['message'] = is_string($result) ? $result : 'Failed to send.';
		}
		$this->output->set_content_type('application/json')->set_output(json_encode($out));
	}
	public function send_SMS_by_Twilio(){
		$this->load->model('twilio_model');
		$this->twilio_model->index();
	}
}

