<?php
if (!defined('BASEPATH')) {
	exit('No direct script access allowed');
}

class Promotion extends Admin_Controller
{
	// promotion
	public function __construct()
	{
		parent::__construct();
		$this->load->model('promotion_model');
	}
	public function index($id = NULL)
	{
		$data['title'] = lang('promotion');
		$data['page_title'] = lang('promotion');
		$data['page_description'] = lang('overview_of_promotion');
		$data['header_actions'] = array();
		if (!empty(can_action('100', 'created'))) {
			$data['header_actions'][] = array(
				'label' => lang('new') . ' ' . lang('promotion'),
				'icon' => 'plus',
				'style' => 'primary',
				// 'href' => base_url('admin/promotion/new_promotion'),
				// 'attrs' => array('data-toggle' => 'modal', 'data-target' => '#myModal_lg'),
				'attrs' => array('data-modal-url' => base_url('admin/promotion/new_promotion'), 'data-modal-title' => lang('new') . ' ' . lang('promotion'), 'data-modal-size' => 'lg'),
			);
		}
		if ($id) {
			$data['promotions'] = $this->db->where('id', $id)->get('tbl_promotions')->row();
			if (empty($data['promotions'])) {
				$type = "error";
				$message = lang("no_record_found");
				set_message($type, $message);
				redirect('admin/promotion');
			}
		}
		$data['active'] = 1;
		$data['dataTables'] = true;
		$data['subview'] = $this->load->view('admin/promotion/promotion', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}

	public function promotionList()
	{
		if ($this->input->is_ajax_request()) {
			$this->load->model('datatables');
			$this->datatables->table = 'tbl_promotions';
			$this->datatables->join_table = array('tbl_account_details', 'tbl_designations');
			$this->datatables->join_where = array('tbl_promotions.user_id=tbl_account_details.user_id', 'tbl_account_details.designations_id=tbl_designations.designations_id ');
			$action_array = array('tbl_promotions.id');
			$main_column = array('promotion_title', 'description', 'promotion_date', 'tbl_designations.designations', 'tbl_account_details.fullname',);
			$result = array_merge($main_column,  $action_array);
			$this->datatables->column_order = $result;
			$this->datatables->column_search = $result;
			$this->datatables->order = array('id' => 'desc');
			$fetch_data = make_datatables();
			$edited = can_action('100', 'edited');
			$deleted = can_action('100', 'deleted');
			$data = array();
			foreach ($fetch_data as $_key => $v_promotions) {
				$action = null;
				$sub_array = array();
				if (!empty($deleted)) {
					$sub_array[] = '<div class="checkbox c-checkbox"><label class="needsclick"><input value="' . $v_promotions->id . '" type="checkbox"></label></div>';
				}
				$sub_array[] = $v_promotions->fullname;
				$sub_array[] = $v_promotions->designations;
				$sub_array[] = $v_promotions->promotion_title;
				$sub_array[] = display_date($v_promotions->promotion_date);
				
				$action .= btn_modal('admin/promotion/promotion_details/' . $v_promotions->id, '', lang('promotion_details'), 'lg', 'eye', array(
					'class' => 'inline-flex items-center gap-2 rounded-lg bg-slate-900 px-3 py-2 text-xs font-semibold text-white hover:bg-slate-800 dark:hover:bg-slate-700 h-7 ml-1'
				));
				$action .= '<a href="' . base_url('admin/promotion/promotion_letter_pdf/' . $v_promotions->id) . '" class="ml-1 inline-flex h-7 items-center gap-2 rounded-lg bg-indigo-600 px-3 py-2 text-xs font-semibold text-white hover:bg-indigo-700" title="' . html_escape(lang('pdf')) . '"><i data-lucide="file-text" class="h-3.5 w-3.5"></i><span>' . html_escape(lang('pdf')) . '</span></a>';
				$action .= '<a href="' . base_url('admin/promotion/promotion_letter_print/' . $v_promotions->id) . '" target="_blank" class="ml-1 inline-flex h-7 items-center gap-2 rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800" title="' . html_escape(lang('print')) . '"><i data-lucide="printer" class="h-3.5 w-3.5"></i><span>' . html_escape(lang('print')) . '</span></a>';
				if (!empty($edited)) {
					$action .=	btn_modal('admin/promotion/new_promotion/' . $v_promotions->id, '', lang('edit') . ' ' . lang('promotion'), 'lg', 'edit', array(
						'class' => 'ml-1 inline-flex items-center gap-2 rounded-lg bg-slate-900 px-3 py-2 text-xs font-semibold text-white hover:bg-slate-800 dark:hover:bg-slate-700 h-7'
					));
					
			
				}
				if (!empty($deleted)) {
					$action .= ajax_anchor(base_url('admin/promotion/delete_promotion/' . $v_promotions->id), '', array("class" => "", "title" => lang('delete'), "data-fade-out-on-success" => "#table_" . $_key)) . ' ';
				}
				$sub_array[] = $action;
				$data[] = $sub_array;
			}
			render_table($data);
		} else {
			redirect('admin/promotion');
		}
	}


	public function new_promotion($id = null)
	{
		$data['title'] = lang('promotion'); //Page title
		$created = can_action('100', 'created');
		$edited = can_action('100', 'edited');
		if (empty($id) && empty($created)) {
			show_404();
		}
		if (!empty($id)) {
			if (empty($edited)) {
				show_404();
			}
			$data['promotions'] = $this->db->where('id', $id)->get('tbl_promotions')->row();
			if (empty($data['promotions'])) {
				$type = "error";
				$message = lang("no_record_found");
				set_message($type, $message);
				redirect('admin/promotion/new_promotion');
			}
		}
		$this->load->model('job_circular_model');
		$data['all_dept_info'] = $this->db->get('tbl_departments')->result();
		foreach ($data['all_dept_info'] as $v_dept_info) {
			$data['all_department_info'][] = $this->job_circular_model->get_add_department_by_id($v_dept_info->departments_id);
		}
		$data['all_employee'] = $this->promotion_model->get_all_employee();
		$this->load->view('admin/promotion/new_promotion', $data, FALSE);
	}

	public function new_designation()
	{
		if (!$this->input->is_ajax_request()) {
			redirect('admin/promotion');
		}

		$created = can_action('100', 'created');
		$edited = can_action('100', 'edited');
		if (empty($created) && empty($edited)) {
			show_404();
		}

		$data['departments'] = $this->db->order_by('deptname', 'asc')->get('tbl_departments')->result();
		$this->load->view('admin/promotion/new_designation', $data, FALSE);
	}

	public function save_designation()
	{
		$created = can_action('100', 'created');
		$edited = can_action('100', 'edited');
		if (empty($created) && empty($edited)) {
			echo json_encode(array('status' => 'error', 'message' => 'Access denied'));
			exit();
		}

		$designation_name = trim((string)$this->input->post('designations', true));
		$department_id = (int)$this->input->post('departments_id', true);
		if (empty($designation_name) || empty($department_id)) {
			echo json_encode(array('status' => 'error', 'message' => 'Department and designation are required.'));
			exit();
		}
		$department = $this->db->where('departments_id', $department_id)->get('tbl_departments')->row();
		$department_name = !empty($department->deptname) ? $department->deptname : '';

		$existing = $this->db
			->where('LOWER(designations)=', strtolower($designation_name))
			->where('departments_id', $department_id)
			->get('tbl_designations')
			->row();
		if (!empty($existing)) {
			echo json_encode(array(
				'status' => 'error',
				'message' => '<strong style="color:#000">' . $designation_name . '</strong> ' . lang('already_exist'),
			));
			exit();
		}

		$this->promotion_model->_table_name = 'tbl_designations';
		$this->promotion_model->_primary_key = 'designations_id';
		$designation_id = $this->promotion_model->save(array(
			'designations' => $designation_name,
			'departments_id' => $department_id,
		));

		$activity = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'department',
			'module_field_id' => $designation_id,
			'activity' => 'activity_added_a_designation',
			'icon' => 'fa-sitemap',
			'value1' => $designation_name,
		);
		$this->promotion_model->_table_name = 'tbl_activities';
		$this->promotion_model->_primary_key = 'activities_id';
		$this->promotion_model->save($activity);

		echo json_encode(array(
			'status' => 'success',
			'message' => 'Designation saved successfully.',
			'id' => $designation_id,
			'name' => $designation_name,
			'group' => $department_name,
			'department' => $department_name,
			'deptname' => $department_name,
		));
		exit();
	}

	public function save_promotion($id = NULL)
	{
		$created = can_action('100', 'created');
		$edited = can_action('100', 'edited');
		if (!empty($created) || !empty($edited) && !empty($id)) {
			$data = $this->promotion_model->array_from_post(array(
				'user_id',
				'designation_id',
				'promotion_title',
				'promotion_date',
				'description',
			));
			$get_user = get_row('tbl_account_details', array('user_id' => $data['user_id']));
			if (!empty($get_user->designations_id) && $data['designation_id'] == $get_user->designations_id) {
				$msg = lang('you_are_already_in_same_designations');
				$type = "error";
				$message = $msg;
			} else {
					$this->promotion_model->_table_name = "tbl_promotions"; // table name
					$this->promotion_model->_primary_key = "id"; // $id
					$return_id = $this->promotion_model->save($data, $id);
					$this->send_promotions_email($data);

					$promotion_id = !empty($id) ? $id : $return_id;
					$notifyUser = array($get_user->user_id);
					if (!empty($notifyUser)) {
						foreach ($notifyUser as $v_user) {
							if (!empty($v_user)) {
								if ($v_user != $this->session->userdata('user_id')) {
									add_notification(array(
										'to_user_id' => $v_user,
										// 'description' => 'not_leave_request',
										'description' => 'promotions',
										'icon' => 'clock-o',
										'link' => 'admin/promotion/promotion_details/' . $promotion_id,
										'value' => lang('by') . ' ' . $get_user->fullname,
									));
								}
							}
					}
				}
				if (!empty($notifyUser)) {
					show_notification($notifyUser);
				}
				$get_user = get_row('tbl_account_details', array('user_id' => $data['user_id']));
				if (!empty($get_user)) {
					$this->promotion_model->_table_name = "tbl_account_details"; //table name
					$this->promotion_model->_primary_key = 'account_details_id';
					$uDate['designations_id'] = $data['designation_id'];
					$this->promotion_model->save($uDate, $get_user->account_details_id);
					$this->promotion_model->_table_name = "tbl_promotions"; // table name
					$this->promotion_model->_primary_key = "id"; // $id
					$upData['from_designations'] = (!empty($get_user->designations_id) ? $get_user->designations_id : NULL);
					$this->promotion_model->save($upData, $return_id);
				}
				$activity = 'activity_added_promotions';
				if (!empty($id)) {
					$activity = 'activity_updated_promotions';
				}
					$activities = array(
						'user' => $this->session->userdata('user_id'),
						'module' => 'promotion',
						'module_field_id' => $promotion_id,
						'activity' => $activity,
						'icon' => 'fa-ticket',
					);
				// Update into tbl_project
				$this->promotion_model->_table_name = "tbl_activities"; //table name
				$this->promotion_model->_primary_key = "activities_id";
				$this->promotion_model->save($activities);
				// messages for user
				$type = "success";
				$msg = lang('promotions_information_saved');
				if (!empty($id)) {
					$msg = lang('promotions_information_update');
				}
				$message = $msg;
			}
		}
		// set_message($type, $message);
		if ($this->input->is_ajax_request()) {
			echo json_encode(array("status" => $type, 'message' => $message));
			exit();
		}
		redirect('admin/promotion');
	}
	public function send_promotions_email($data)
	{
		$all_users = get_row('tbl_account_details', array('user_id' => $data['user_id']));
		$users_email = get_row('tbl_users', array('user_id' => $data['user_id']));
		$all_designations = get_row('tbl_designations', array('designations_id' => $data['designation_id']));
		$promotions_email = config_item('promotions_email');
		if (!empty($promotions_email) && $promotions_email == 1) {
			$email_template = email_templates(array('email_group' => 'promotion_email'));
			$message = $email_template->template_body;
			$subject = $email_template->subject;
			$title = str_replace("{NAME}", $all_users->fullname, $message);
			$designation = str_replace("{DESIGNATIONS}", $all_designations->designations, $title);
			$message = str_replace("{SITE_NAME}", config_item('company_name'), $designation);
			$data['message'] = $message;
			$message = $this->load->view('email_template', $data, TRUE);
			$params['subject'] = $subject;
			$params['message'] = $message;
			$params['resourceed_file'] = '';
			$params['recipient'] = $users_email->email;
			$this->promotion_model->send_email($params);
		}
		return true;
	}
	public function promotion_details($id = null)
	{
		$data['title'] = lang('promotion_details'); //Page title
		$data['promotion_details'] = join_data('tbl_promotions', '*', array('id' => $id), array('tbl_account_details' => 'tbl_account_details.user_id = tbl_promotions.user_id'));
		if (empty($data['promotion_details'])) {
			$type = "error";
			$message = lang("no_record_found");
			set_message($type, $message);
			redirect('admin/promotion');
		}
		$this->load->model('job_circular_model');
		$data['all_dept_info'] = get_row('tbl_designations', array('designations_id' => $data['promotion_details']->designations_id));
		$data['subview'] = $this->load->view('admin/promotion/promotion_details', $data, FALSE);
	}

	private function ensure_promotion_print_date_column()
	{
		if ($this->db->table_exists('tbl_promotions') && !$this->db->field_exists('print_date', 'tbl_promotions')) {
			$this->db->query("ALTER TABLE `tbl_promotions` ADD `print_date` date DEFAULT NULL AFTER `promotion_date`");
		}
	}

	private function mark_promotion_letter_printed($id)
	{
		$this->ensure_promotion_print_date_column();
		$this->db->where('id', $id)->update('tbl_promotions', array('print_date' => date('Y-m-d')));
	}

	private function get_promotion_letter_data($id)
	{
		if (empty($id)) {
			return null;
		}

		$this->db->select('tbl_promotions.*');
		$this->db->select('tbl_account_details.fullname, tbl_account_details.employment_id, tbl_account_details.joining_date, tbl_account_details.phone, tbl_account_details.mobile');
		$this->db->select('tbl_users.email');
		$this->db->select('new_designations.designations as new_designation, new_departments.deptname as new_department');
		$this->db->select('old_designations.designations as previous_designation, old_departments.deptname as previous_department');
		$this->db->from('tbl_promotions');
		$this->db->join('tbl_account_details', 'tbl_account_details.user_id = tbl_promotions.user_id', 'left');
		$this->db->join('tbl_users', 'tbl_users.user_id = tbl_promotions.user_id', 'left');
		$this->db->join('tbl_designations as new_designations', 'new_designations.designations_id = tbl_promotions.designation_id', 'left');
		$this->db->join('tbl_departments as new_departments', 'new_departments.departments_id = new_designations.departments_id', 'left');
		$this->db->join('tbl_designations as old_designations', 'old_designations.designations_id = tbl_promotions.from_designations', 'left');
		$this->db->join('tbl_departments as old_departments', 'old_departments.departments_id = old_designations.departments_id', 'left');
		$this->db->where('tbl_promotions.id', $id);
		return $this->db->get()->row();
	}

	public function promotion_letter_pdf($id = null)
	{
		$this->mark_promotion_letter_printed($id);
		$data['promotion'] = $this->get_promotion_letter_data($id);
		if (empty($data['promotion'])) {
			$type = "error";
			$message = lang("no_record_found");
			set_message($type, $message);
			redirect('admin/promotion');
		}
		$data['print_mode'] = false;
		$this->load->helper('dompdf');
		$viewfile = $this->load->view('admin/promotion/promotion_letter_pdf', $data, true);
		pdf_create($viewfile, slug_it('Promotion Letter - ' . $data['promotion']->fullname), true, 'portrait');
	}

	public function promotion_letter_print($id = null)
	{
		$this->mark_promotion_letter_printed($id);
		$data['promotion'] = $this->get_promotion_letter_data($id);
		if (empty($data['promotion'])) {
			$type = "error";
			$message = lang("no_record_found");
			set_message($type, $message);
			redirect('admin/promotion');
		}
		$data['print_mode'] = true;
		$this->load->view('admin/promotion/promotion_letter_pdf', $data);
	}

	public function delete_promotion($id = NULL)
	{
		$deleted = can_action('100', 'deleted');
		if (!empty($deleted)) {
			$promotions_info = $this->promotion_model->check_by(array('id' => $id), 'tbl_promotions');
			if (empty($promotions_info)) {
				$type = "error";
				$message = lang("no_record_found");
				set_message($type, $message);
				redirect('admin/promotion');
			}
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'promotion',
				'module_field_id' => $id,
				'activity' => 'activity_delete_promotion',
				'icon' => 'fa-ticket',
				'value1' => $promotions_info->promotion_title,
			);
			// Update into tbl_project
			$this->promotion_model->_table_name = "tbl_activities"; //table name
			$this->promotion_model->_primary_key = "activities_id";
			$this->promotion_model->save($activities);
			$this->promotion_model->_table_name = "tbl_promotions";
			$this->promotion_model->_primary_key = "id";
			$this->promotion_model->delete($id);
			// messages for user
			$type = "success";
			$message = lang('promotion_information_delete');
		}
		echo json_encode(array("status" => $type, 'message' => $message));
		exit();
	}
}
