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

class Templates extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('templates_model','templates');
	}

	public function sms_new(){
		$this->permission_check('sms_template_add');

		$data=$this->data;
		$data['page_title']=$this->lang->line('sms_template');
		$this->load->view('sms-template', $data);
	}
	public function newtemplate(){
		$this->permission_check('sms_template_add');
		$this->form_validation->set_rules('template_name', 'Templates', 'trim|required');
		$this->form_validation->set_rules('content', 'Templates', 'trim|required');
		
		if ($this->form_validation->run() == TRUE) {
			$result=$this->templates->verify_and_save();
			echo $result;
		} else {
			echo "Please Enter Templates name & Content!";
		}
	}
	public function update($id){
		$this->permission_check('sms_template_edit');
		$this->belong_to('db_smstemplates',$id);
		$data=$this->data;
		$result=$this->templates->get_details($id,$data);
		$data['page_title']=$this->lang->line('sms_template');
		$data=array_merge($data,$result);
		$this->load->view('sms-template', $data);
	}
	public function update_template(){
		$this->permission_check('sms_template_edit');
		$this->form_validation->set_rules('template_name', 'Templates', 'trim|required');
		$this->form_validation->set_rules('content', 'Templates', 'trim|required');
		$this->form_validation->set_rules('q_id', '', 'trim|required');

		if ($this->form_validation->run() == TRUE) {
			$result=$this->templates->update_template();
			echo $result;
		} else {
			echo "Please Enter Templates name & Content!";
		}
	}
	public function sms(){
		$this->permission_check('sms_template_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('sms_templates_list');
		$this->load->view('sms-templates-list', $data);
	}

	public function ajax_list()
	{
		$list = $this->templates->get_datatables();
		
		$data = array();
		$no = $_POST['start'];
		$i=1;
		foreach ($list as $templates) {
			$no++;
			$row = array();
			
			$row[] = $i++;
			$row[] = $templates->template_name;
			$row[] = $templates->content;

			 		if($templates->status==1){ 
			 			$str= "<span onclick='update_status(".$templates->id.",0)' id='span_".$templates->id."'  class='label label-success' style='cursor:pointer'>Active </span>";}
					else{ 
						$str = "<span onclick='update_status(".$templates->id.",1)' id='span_".$templates->id."'  class='label label-danger' style='cursor:pointer'> Inactive </span>";
					}
			$row[] = $str;			
			   		$str2 = '<div class="btn-group" title="View Account">
										<a class="btn btn-primary btn-o dropdown-toggle" data-toggle="dropdown" href="#">
											Action <span class="caret"></span>
										</a>
										<ul role="menu" class="dropdown-menu dropdown-light pull-right">';

											if($this->permissions('sms_template_edit'))
											$str2.='<li>
												<a title="Update Record ?" href="'.base_url().'templates/update/'.$templates->id.'">
													Update
												</a>
											</li>';

											if($this->permissions('sms_template_delete') && 1==0)
											$str2.='<li>
												<a style="cursor:pointer" title="Delete Record ?" onclick="delete_template('.$templates->id.')">
													Delete
												</a>
											</li>
											
										</ul>
									</div>';			

			$row[] = $str2;						
			$data[] = $row;
		}

		$output = array(
						"draw" => $_POST['draw'],
						"recordsTotal" => $this->templates->count_all(),
						"recordsFiltered" => $this->templates->count_filtered(),
						"data" => $data,
				);
		//output to json format
		echo json_encode($output);
	}

	public function update_status(){
		$this->permission_check_with_msg('sms_template_edit');
		$id=$this->input->post('id');
		$status=$this->input->post('status');
		$result=$this->templates->update_status($id,$status);
		return $result;
	}
	public function delete_template(){
		$this->permission_check_with_msg('sms_template_delete');
		$id=$this->input->post('q_id');
		$result=$this->templates->delete_template($id);
		return $result;
	}
	
	//Create default SMS templates
	public function create_default_templates(){
		$this->permission_check('sms_template_add');
		
		$store_id = get_current_store_id();
		
		// Default templates for common business communications
		$templates = [
			[
				'template_name' => 'Payment Reminder',
				'content' => 'Hi {{customer_name}}, Your sales Id is {{sales_id}}, Sales Date {{sales_date}}, Total amount {{sales_amount}}, You have paid {{paid_amt}}, and due amount is {{due_amt}}. Thank you Visit Again - {{store_name}}',
				'variables' => 'customer_name,sales_id,sales_date,sales_amount,paid_amt,due_amt,store_name'
			],
			[
				'template_name' => 'Payment Overdue',
				'content' => 'Dear {{customer_name}}, Your payment of {{sales_amount}} for sales ID {{sales_id}} is now overdue. Due amount: {{due_amt}}. Please contact us immediately. - {{store_name}}',
				'variables' => 'customer_name,sales_amount,sales_id,due_amt,store_name'
			],
			[
				'template_name' => 'Sales Confirmation',
				'content' => 'Thank you {{customer_name}}! Your sales ID {{sales_id}} for {{sales_amount}} has been confirmed. Sales Date: {{sales_date}}. - {{store_name}}',
				'variables' => 'customer_name,sales_id,sales_amount,sales_date,store_name'
			],
			[
				'template_name' => 'Payment Received',
				'content' => 'Dear {{customer_name}}, We have received your payment of {{paid_amt}} for sales ID {{sales_id}}. Remaining due: {{due_amt}}. Thank you! - {{store_name}}',
				'variables' => 'customer_name,paid_amt,sales_id,due_amt,store_name'
			],
			[
				'template_name' => 'Welcome Message',
				'content' => 'Welcome to {{store_name}}, {{customer_name}}! Thank you for choosing us. We look forward to serving you. For any queries, contact us at {{phone}}.',
				'variables' => 'store_name,customer_name,phone'
			],
			[
				'template_name' => 'Promotional Offer',
				'content' => 'Special offer for {{customer_name}}! Get {{discount_percent}}% off on your next purchase. Valid until {{expiry_date}}. - {{store_name}}',
				'variables' => 'customer_name,discount_percent,expiry_date,store_name'
			],
			[
				'template_name' => 'Service Completion',
				'content' => 'Dear {{customer_name}}, Your service request has been completed. Total amount: {{sales_amount}}. Please visit us to collect. - {{store_name}}',
				'variables' => 'customer_name,sales_amount,store_name'
			],
			[
				'template_name' => 'Birthday Wishes',
				'content' => 'Happy Birthday {{customer_name}}! 🎉 Enjoy a special {{discount_percent}}% discount on your birthday. Visit us today! - {{store_name}}',
				'variables' => 'customer_name,discount_percent,store_name'
			],
			[
				'template_name' => 'Feedback Request',
				'content' => 'Hi {{customer_name}}, We hope you enjoyed your recent visit. Please share your feedback. Your opinion matters to us! - {{store_name}}',
				'variables' => 'customer_name,store_name'
			],
			[
				'template_name' => 'Invoice Reminder',
				'content' => 'Hi {{customer_name}}, Your invoice {{sales_id}} dated {{sales_date}} for {{sales_amount}} is pending. Due amount: {{due_amt}}. Please make payment. - {{store_name}}',
				'variables' => 'customer_name,sales_id,sales_date,sales_amount,due_amt,store_name'
			]
		];
		
		$created_count = 0;
		$skipped_count = 0;
		
		foreach ($templates as $template) {
			// Check if template already exists
			$existing = $this->db->query("SELECT id FROM db_smstemplates WHERE template_name = ? AND store_id = ?", 
				[$template['template_name'], $store_id]);
			
			if ($existing->num_rows() == 0) {
				// Insert new template
				$query = "INSERT INTO db_smstemplates(template_name,content,variables,status,store_id) VALUES(?,?,?,1,?)";
				$this->db->query($query, [
					$template['template_name'],
					$template['content'],
					$template['variables'],
					$store_id
				]);
				$created_count++;
			} else {
				$skipped_count++;
			}
		}
		
		$message = "Created {$created_count} new templates";
		if ($skipped_count > 0) {
			$message .= ", {$skipped_count} already existed";
		}
		
		echo json_encode(['status' => true, 'message' => $message]);
	}
	
	//Create system-required SMS templates (for transaction SMS)
	public function create_system_templates(){
		$this->permission_check('sms_template_add');
		
		$store_id = get_current_store_id();
		
		// System-required templates that the application expects
		$system_templates = [
			[
				'template_name' => 'GREETING TO CUSTOMER ON SALES',
				'content' => 'Hi {{customer_name}}, Your sales Id is {{sales_id}}, Sales Date {{sales_date}}, Total amount {{sales_amount}}, You have paid {{paid_amt}}, and due amount is {{due_amt}}. Thank you Visit Again - {{store_name}}',
				'variables' => 'customer_name,sales_id,sales_date,sales_amount,paid_amt,due_amt,store_name'
			],
			[
				'template_name' => 'GREETING TO CUSTOMER ON SALES RETURN',
				'content' => 'Hi {{customer_name}}, Your return Id is {{return_id}}, Return Date {{return_date}}, Return amount {{return_amount}}, You have received {{paid_amt}}, and due amount is {{due_amt}}. Thank you Visit Again - {{store_name}}',
				'variables' => 'customer_name,return_id,return_date,return_amount,paid_amt,due_amt,store_name'
			]
		];
		
		$created_count = 0;
		$updated_count = 0;
		
		foreach ($system_templates as $template) {
			// Check if template already exists
			$existing = $this->db->query("SELECT id FROM db_smstemplates WHERE template_name = ? AND store_id = ?", 
				[$template['template_name'], $store_id]);
			
			if ($existing->num_rows() == 0) {
				// Insert new template
				$query = "INSERT INTO db_smstemplates(template_name,content,variables,status,store_id) VALUES(?,?,?,1,?)";
				$this->db->query($query, [
					$template['template_name'],
					$template['content'],
					$template['variables'],
					$store_id
				]);
				$created_count++;
			} else {
				// Update existing template
				$query = "UPDATE db_smstemplates SET content=?, variables=?, status=1 WHERE template_name=? AND store_id=?";
				$this->db->query($query, [
					$template['content'],
					$template['variables'],
					$template['template_name'],
					$store_id
				]);
				$updated_count++;
			}
		}
		
		$message = "System templates ready! ";
		if ($created_count > 0) {
			$message .= "Created {$created_count} new templates. ";
		}
		if ($updated_count > 0) {
			$message .= "Updated {$updated_count} existing templates. ";
		}
		$message .= "Transaction SMS should now work!";
		
		echo json_encode(['status' => true, 'message' => $message]);
	}
}

