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

class ContactController extends CI_Controller
{


	public function __construct()
	{

		parent::__construct();

		if ($this->session->userdata('admin_logged_in') !== TRUE) {
			redirect('/');
		}

		$this->load->model('dataHandling/crud', 'crud');
		$this->load->model('pages/ContactModel', 'model');
		$this->load->model('TableModel/contact/FetchContactData', 'TableModel');
	}

	public function index()
	{
		$this->layouts->add_includes('assets/backend/js/pages/contact.js');
		$data['title'] = "Message";
		$data['content'] = 'pages/main/contact';
		$this->load->view('layout/backend-access', $data);
	}

	public function getContactData()
	{
		if ($this->input->is_ajax_request()) {
			$list = $this->TableModel->get_datatables();
			$data = array();
			$no = $_POST['start'];

			foreach ($list as $data_n) {


				$no++;
				$row = array();
				$row[] = date('d-F, Y h:i A', strtotime($data_n->time));
				$row[] = $data_n->subject;
				$row[] = $data_n->sender_name;
				$row[] = $data_n->sender_email;
				$row[] = $data_n->seen_status;
				$row[] = $data_n->sender_contact;
				$row[] = $data_n->message;
				$row[] = sha1($data_n->contact_id);


				$data[] = $row;
			}

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

	public function updateMessageStatus()
	{
		if ($this->input->is_ajax_request()) {
			$hash_id = $this->input->post('id');
			$result = $this->model->getIDProcessing($hash_id);
			$dataSet = [
				'seen_status' => 'Seen'
			];
			$table = "contact";
			if ($this->crud->updateData($result->contact_id, $dataSet, 'contact_id', $table)) {
				$data['response'] = 'Status updated';
			} else {
				$data['response'] = 'Error Occured';
			}
			echo json_encode($data);
		}
	}
}
