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

class Sms_promotional extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('sms_model');
		$this->load->model('customers_model');
	}
	
	//Open Promotional SMS Form 
	public function index(){
		$this->permission_check('promotional_sms');
		$data=$this->data;
		$data['page_title']=$this->lang->line('promotional_sms');
		$data['customers'] = $this->get_customers_list();
		$data['templates'] = $this->get_sms_templates();
		$this->load->view('sms-promotional', $data);
	}

	//Send promotional SMS to single customer
	public function send_single(){
		$this->permission_check('promotional_sms');
		$data=$this->data;
		$data['page_title']=$this->lang->line('send_single_sms');
		$data['customers'] = $this->get_customers_list();
		$data['templates'] = $this->get_sms_templates();
		
		// Pre-select customer if provided in URL
		$data['preselected_customer'] = $this->input->get('customer_id');
		
		$this->load->view('sms-promotional-single', $data);
	}

	//Send promotional SMS to multiple customers
	public function send_bulk(){
		$this->permission_check('promotional_sms');
		$data=$this->data;
		$data['page_title']=$this->lang->line('send_bulk_sms');
		$data['customers'] = $this->get_customers_list();
		$data['templates'] = $this->get_sms_templates();
		$this->load->view('sms-promotional-bulk', $data);
	}


	//Send promotional message
	public function send_message(){
		try {
			// Security checks
			$this->permission_check('promotional_sms');
			// CSRF disabled for SMS sending
			
			extract($this->security->xss_clean(html_escape($_POST)));
			
			$result = array('status' => false, 'message' => '');
		
		// Validate inputs
		if(empty($message) && empty($template_id)){
			$result['message'] = 'Please enter a message or select a template';
			echo json_encode($result);
			return;
		}

		// Get final message
		$final_message = $message;
		if(!empty($template_id) && empty($message)){
			$template = $this->get_template_content($template_id);
			if($template){
				$final_message = $template->content;
			}
		}

		// Process recipients
		$recipients = array();
		if($send_type == 'single'){
			if(empty($customer_id)){
				$result['message'] = 'Please select a customer';
				echo json_encode($result);
				return;
			}
			$customer = $this->get_customer_details($customer_id);
			if($customer && !empty($customer->mobile)){
				$recipients[] = array(
					'id' => $customer->id,
					'name' => $customer->customer_name,
					'mobile' => $customer->mobile
				);
			}
		} else if($send_type == 'bulk'){
			if(empty($customer_ids)){
				$result['message'] = 'Please select at least one customer';
				echo json_encode($result);
				return;
			}
			$customer_ids_array = explode(',', $customer_ids);
			foreach($customer_ids_array as $id){
				$customer = $this->get_customer_details($id);
				if($customer && !empty($customer->mobile)){
					$recipients[] = array(
						'id' => $customer->id,
						'name' => $customer->customer_name,
						'mobile' => $customer->mobile
					);
				}
			}
		} else if($send_type == 'all'){
			$customers = $this->get_all_customers_with_mobile();
			foreach($customers as $customer){
				$recipients[] = array(
					'id' => $customer->id,
					'name' => $customer->customer_name,
					'mobile' => $customer->mobile
				);
			}
		}

		if(empty($recipients)){
			$result['message'] = 'No valid recipients found';
			echo json_encode($result);
			return;
		}

		// Send SMS to each recipient
		$success_count = 0;
		$failed_count = 0;
		$failed_recipients = array();

		foreach($recipients as $recipient){
			// Replace template variables if template is used
			$message_to_send = $final_message;
			if(!empty($template_id)){
				$message_to_send = $this->replace_template_variables($final_message, $recipient);
			}

			$sms_result = $this->sms_model->send_sms($recipient['mobile'], $message_to_send);
			
			if($sms_result == 'success'){
				$success_count++;
			} else {
				$failed_count++;
				$failed_recipients[] = $recipient['name'] . ' (' . $recipient['mobile'] . ')';
			}
		}

		// Log promotional SMS
		$this->log_promotional_sms($send_type, $final_message, $success_count, $failed_count, $failed_recipients);

		$result['status'] = true;
		$result['message'] = "SMS sent successfully to {$success_count} recipients";
		if($failed_count > 0){
			$result['message'] .= ". Failed to send to {$failed_count} recipients: " . implode(', ', $failed_recipients);
		}

		echo json_encode($result);
		
		} catch (Exception $e) {
			error_log('Promotional SMS Error: ' . $e->getMessage());
			error_log('Promotional SMS Error Trace: ' . $e->getTraceAsString());
			
			$result = array('status' => false, 'message' => 'Error: ' . $e->getMessage());
			echo json_encode($result);
		}
	}

	//Get customers list for dropdown
	public function get_customers_list(){
		$store_id = get_current_store_id();
		$query = $this->db->select('id, customer_name, mobile')
						  ->from('db_customers')
						  ->where('store_id', $store_id)
						  ->where('status', 1)
						  ->where('delete_bit', 0)
						  ->where('mobile IS NOT NULL')
						  ->where('mobile !=', '')
						  ->order_by('customer_name', 'ASC')
						  ->get();
		return $query->result();
	}

	//Get all customers with mobile numbers
	public function get_all_customers_with_mobile(){
		$store_id = get_current_store_id();
		$query = $this->db->select('id, customer_name, mobile')
						  ->from('db_customers')
						  ->where('store_id', $store_id)
						  ->where('status', 1)
						  ->where('delete_bit', 0)
						  ->where('mobile IS NOT NULL')
						  ->where('mobile !=', '')
						  ->get();
		return $query->result();
	}

	//Get customer details by ID
	public function get_customer_details($customer_id){
		$store_id = get_current_store_id();
		$query = $this->db->select('id, customer_name, mobile, email, address')
						  ->from('db_customers')
						  ->where('id', $customer_id)
						  ->where('store_id', $store_id)
						  ->where('status', 1)
						  ->where('delete_bit', 0)
						  ->get();
		return $query->row();
	}

	//Get SMS templates
	public function get_sms_templates(){
		$store_id = get_current_store_id();
		$query = $this->db->select('id, template_name, content, variables')
						  ->from('db_smstemplates')
						  ->where('store_id', $store_id)
						  ->where('status', 1)
						  ->order_by('template_name', 'ASC')
						  ->get();
		return $query->result();
	}

	//Get template content by ID
	public function get_template_content($template_id){
		$store_id = get_current_store_id();
		$query = $this->db->select('id, template_name, content, variables')
						  ->from('db_smstemplates')
						  ->where('id', $template_id)
						  ->where('store_id', $store_id)
						  ->where('status', 1)
						  ->get();
		return $query->row();
	}

	//AJAX method to get template content
	public function get_template_content_ajax(){
		$template_id = $this->input->post('template_id');
		$template = $this->get_template_content($template_id);
		
		$response = array('status' => false, 'content' => '');
		if($template){
			$response['status'] = true;
			$response['content'] = $template->content;
		}
		
		echo json_encode($response);
	}

	//AJAX method to get customer details
	public function get_customer_details_ajax(){
		$customer_id = $this->input->post('customer_id');
		$customer = $this->get_customer_details($customer_id);
		
		$response = array('status' => false);
		if($customer){
			$response['status'] = true;
			$response['customer_name'] = $customer->customer_name;
			$response['mobile'] = $customer->mobile;
			$response['email'] = $customer->email;
			$response['address'] = $customer->address;
		}
		
		echo json_encode($response);
	}

	//Replace template variables
	public function replace_template_variables($content, $customer){
		// Get store details
		$store = get_store_details();
		
		// Replace customer variables (both {{}} and {} formats)
		$content = str_replace("{customer_name}", $customer['name'], $content);
		$content = str_replace("{{customer_name}}", $customer['name'], $content);
		$content = str_replace("{customer_mobile}", $customer['mobile'], $content);
		$content = str_replace("{{customer_mobile}}", $customer['mobile'], $content);
		
		// Replace store variables (both {{}} and {} formats)
		$content = str_replace("{store_name}", $store->store_name, $content);
		$content = str_replace("{{store_name}}", $store->store_name, $content);
		$content = str_replace("{phone}", $store->mobile, $content);
		$content = str_replace("{store_mobile}", $store->mobile, $content);
		$content = str_replace("{{store_mobile}}", $store->mobile, $content);
		$content = str_replace("{store_address}", $store->address, $content);
		$content = str_replace("{{store_address}}", $store->address, $content);
		$content = str_replace("{store_website}", $store->store_website, $content);
		$content = str_replace("{{store_website}}", $store->store_website, $content);
		$content = str_replace("{store_email}", $store->email, $content);
		$content = str_replace("{{store_email}}", $store->email, $content);
		
		// Replace date variables (both {{}} and {} formats)
		$content = str_replace("{current_date}", date('d-m-Y'), $content);
		$content = str_replace("{{current_date}}", date('d-m-Y'), $content);
		$content = str_replace("{current_time}", date('H:i:s'), $content);
		$content = str_replace("{{current_time}}", date('H:i:s'), $content);
		$content = str_replace("{today}", date('d-m-Y'), $content);
		$content = str_replace("{now}", date('H:i:s'), $content);
		
		// For promotional SMS, use descriptive text instead of placeholders
		$content = str_replace("{sales_amount}", "Amount", $content);
		$content = str_replace("{{sales_amount}}", "Amount", $content);
		$content = str_replace("{sales_id}", "Invoice#", $content);
		$content = str_replace("{{sales_id}}", "Invoice#", $content);
		$content = str_replace("{sales_date}", "Date", $content);
		$content = str_replace("{{sales_date}}", "Date", $content);
		$content = str_replace("{paid_amt}", "Paid", $content);
		$content = str_replace("{{paid_amt}}", "Paid", $content);
		$content = str_replace("{due_amt}", "Due", $content);
		$content = str_replace("{{due_amt}}", "Due", $content);
		$content = str_replace("{amount}", "Amount", $content);
		$content = str_replace("{invoice_number}", "Invoice#", $content);
		$content = str_replace("{order_number}", "Order#", $content);
		$content = str_replace("{days_overdue}", "Days", $content);
		$content = str_replace("{delivery_time}", "Time", $content);
		$content = str_replace("{tracking_link}", "Link", $content);
		$content = str_replace("{appointment_date}", "Date", $content);
		$content = str_replace("{appointment_time}", "Time", $content);
		$content = str_replace("{discount_percent}", "%", $content);
		$content = str_replace("{promo_code}", "Code", $content);
		$content = str_replace("{expiry_date}", "Date", $content);
		$content = str_replace("{service_id}", "ID", $content);
		$content = str_replace("{feedback_link}", "Link", $content);
		
		return $content;
	}

	//Log promotional SMS
	public function log_promotional_sms($send_type, $message, $success_count, $failed_count, $failed_recipients){
		$store_id = get_current_store_id();
		$data = array(
			'store_id' => $store_id,
			'send_type' => $send_type,
			'message' => $message,
			'success_count' => $success_count,
			'failed_count' => $failed_count,
			'failed_recipients' => json_encode($failed_recipients),
			'created_date' => date('Y-m-d'),
			'created_time' => date('H:i:s'),
			'created_by' => get_current_user_id()
		);
		
		$this->db->insert('db_promotional_sms_log', $data);
	}

	//Get promotional SMS history
	public function history(){
		$this->permission_check('promotional_sms');
		$data=$this->data;
		$data['page_title']=$this->lang->line('promotional_sms_history');
		$this->load->view('sms-promotional-history', $data);
	}

	//AJAX list for promotional SMS history
	public function ajax_history_list(){
		$this->permission_check('promotional_sms');
		
		$store_id = get_current_store_id();
		
		$query = $this->db->select('p.*, u.username')
						  ->from('db_promotional_sms_log p')
						  ->join('db_users u', 'p.created_by = u.id', 'left')
						  ->where('p.store_id', $store_id)
						  ->order_by('p.created_date DESC, p.created_time DESC')
						  ->get();
		
		$data = array();
		foreach($query->result() as $row){
			$data[] = array(
				'id' => $row->id,
				'send_type' => ucfirst($row->send_type),
				'message' => substr($row->message, 0, 100) . (strlen($row->message) > 100 ? '...' : ''),
				'success_count' => $row->success_count,
				'failed_count' => $row->failed_count,
				'created_date' => $row->created_date,
				'created_time' => $row->created_time,
				'created_by' => $row->username ?: 'Unknown User'
			);
		}
		
		echo json_encode($data);
	}
	
	//Clear SMS history
	public function clear_history(){
		$this->permission_check('promotional_sms');
		
		$store_id = get_current_store_id();
		$result = $this->db->where('store_id', $store_id)
						   ->delete('db_promotional_sms_log');
		
		if($result){
			echo json_encode(array('status' => true, 'message' => 'SMS history cleared successfully'));
		} else {
			echo json_encode(array('status' => false, 'message' => 'Failed to clear SMS history'));
		}
	}
}
