<?php

/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the HRSALE License
 * that is bundled with this package in the file license.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.hrsale.com/license.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to hrsalesoft@gmail.com so we can send you a copy immediately.
 *
 * @author   HRSALE
 * @author-email  hrsalesoft@gmail.com
 * @copyright  Copyright © hrsale.com. All Rights Reserved
 */
defined('BASEPATH') or exit('No direct script access allowed');

class Job_candidates extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->library('Pdf');
		//load the model
		$this->load->model("Job_post_model");
		$this->load->model("Xin_model");
		$this->load->model("Designation_model");
		$this->load->model("Users_model");
		$this->db2 = $this->load->database('db2', TRUE);
	}

	/*Function to set JSON output*/
	public function output($Return = array())
	{
		/*Set response header*/
		header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		/*Final JSON response*/
		exit(json_encode($Return));
	}

	public function index()
	{
		$session = $this->session->userdata('username');
		if (empty($session)) {
			redirect('admin/');
		}
		$system = $this->Xin_model->read_setting_info(1);
		if ($system[0]->module_recruitment != 'true') {
			redirect('admin/dashboard');
		}
		$data['title'] = $this->lang->line('left_job_candidates') . ' | ' . $this->Xin_model->site_title();
		$data['breadcrumbs'] = $this->lang->line('left_job_candidates');
		$data['path_url'] = 'job_candidates';
		$role_resources_ids = $this->Xin_model->user_role_resource();
		if (in_array('51', $role_resources_ids)) {
			if (!empty($session)) {
				$data['subview'] = $this->load->view("admin/job_post/job_candidates", $data, TRUE);
				$this->load->view('admin/layout/layout_main', $data); //page load
			} else {
				redirect('admin/');
			}
		} else {
			redirect('admin/dashboard');
		}
	}

	public function candidate_list()
	{

		$data['title'] = $this->Xin_model->site_title();
		$session = $this->session->userdata('username');
		if (!empty($session)) {
			$this->load->view("admin/job_post/job_candidates", $data);
		} else {
			redirect('admin/');
		}
		// Datatables Variables
		$draw = intval($this->input->get("draw"));
		$start = intval($this->input->get("start"));
		$length = intval($this->input->get("length"));

		$role_resources_ids = $this->Xin_model->user_role_resource();
		if (in_array('387', $role_resources_ids)) {
			// 			$candidates = $this->Job_post_model->get_employee_jobs_applied($session['user_id']);
			$candidates = $this->Job_post_model->get_jobs_candidates();
		} else {
			$candidates = $this->Job_post_model->get_jobs_candidates();
		}

		$data = array();

		foreach ($candidates->result() as $r) {
			// get job title
			$job = $this->Job_post_model->read_job_information($r->job_id);
			if (!is_null($job)) {
				$app_row = $this->Job_post_model->job_applications_available($r->job_id);
				if ($app_row > 1) {
					$app_available = '<br><a class="badge bg-purple btn-sm" href="' . site_url('admin/job_candidates/') . 'by_job/' . $r->job_id . '" target="_blank"><i class="fa fa-list"></i> ' . $this->lang->line('xin_job_applicants_title') . '</a>';
				} else {
					$app_available = '';
				}
				$job_title = '<a data-toggle="tooltip" data-placement="top" title="" data-original-title="' . $this->lang->line('xin_view') . '">' . $job[0]->job_title . '</a>';
				$job_title = $job_title . $app_available;
			} else {
				$job_title = '-';
			}
			// get date
			$created_at = $this->Xin_model->set_date_format($r->created_at);
			// applicant status
			if ($r->application_status == 0) {
				$status = '<span class="badge bg-warning">' . $this->lang->line('xin_pending') . '</span>';
			} else if ($r->application_status == 1) {
				$status = '<span class="badge bg-primary">' . $this->lang->line('xin_primary_selected') . '</span>';
			}
			if ($r->application_status == 2) {
				$status = '<span class="badge bg-info">' . $this->lang->line('xin_call_for_interview') . '</span>';
			}
			if ($r->application_status == 3) {
				$status = '<span class="badge bg-success">' . $this->lang->line('xin_confirm_del') . '</span>';
			}
			if ($r->application_status == 4) {
				$status = '<span class="badge bg-danger">' . $this->lang->line('xin_rejected') . '</span>';
			}
			if (in_array('294', $role_resources_ids)) { //download
				$download = '<span data-toggle="tooltip" data-placement="top" title="' . $this->lang->line('xin_download') . '">
			<a href="' . site_url('admin/download') . '?type=resume&filename=' . $r->job_resume . '"><button type="button" class="btn btn-outline-secondary btn-sm m-b-0-0 waves-effect waves-light"><i class="oi oi-cloud-download"></i></button></a></span>';
			} else {
				$download = '';
			}
			if (in_array('294', $role_resources_ids)) { //download
				$view = '<span data-toggle="tooltip" data-placement="top" title="Lihat Resume">
			<a href="' . site_url() . 'admin/job_candidates/pdf_create/p/' . $r->id_user . '" target="_blank"><button type="button" class="btn btn-outline-primary btn-sm m-b-0-0 waves-effect waves-light"><span class="oi oi-eye"></span></button></a></span>';
			} else {
				$view = '';
			}
			if (in_array('295', $role_resources_ids)) { // delete
				$delete = '<span data-toggle="tooltip" data-placement="top" title="' . $this->lang->line('xin_delete') . '"><button type="button" class="btn btn-outline-danger btn-sm m-b-0-0 waves-effect waves-light delete" data-toggle="modal" data-target=".delete-modal" data-record-id="' . $r->application_id . '"><i class="fas fa-trash-restore"></i></button></span>';
				// 			$edit_status = '<span data-toggle="tooltip" data-placement="top" title="'.$this->lang->line('xin_change_status').'"><button type="button" class="btn icon-btn btn-sm btn-outline-secondary waves-effect waves-light" data-toggle="modal" data-target=".add-modal-data" data-application_id="'. $r->application_id . '"><i class="fas fa-pencil-alt-square-o"></i></button></span>';

				$edit_status = '<span data-toggle="tooltip" data-placement="top" title="' . $this->lang->line('xin_change_status') . '">
			<button type="button" class="btn btn-outline-secondary btn-sm m-b-0-0 waves-effect waves-light" data-toggle="modal" data-target=".add-modal-data" data-application_id="' . $r->application_id . '"><i class="far fa-arrow-alt-circle-right"></i></button></span>';
			} else {
				$delete = '';
				$edit_status = '';
			}

			$iticket_code = $r->full_name . '<br><small class="text-muted"><i>' . $r->email . '<i></i></i></small>';
			$cover_letter = '<a><button class="btn icon-btn btn-sm btn-outline-secondary waves-effect waves-light" data-toggle="modal" data-target=".view-modal-data" data-application_id="' . $r->application_id . '">' . $this->lang->line('xin_view') . ' ' . $this->lang->line('xin_jobs_cover_letter') . '</button></a>';
			$combhr = $download . $edit_status . $delete . $view;

			if ($r->application_status == 2) {
				$interview = $r->interview_date;
			} else {
				$interview = '-';
			}

			$data[] = array(
				$combhr,
				$job_title,
				$r->full_name,
				$r->email,
				$status,
				$interview,
				// 			$cover_letter,
				$created_at
			);
		}

		$output = array(
			"draw" => $draw,
			"recordsTotal" => $candidates->num_rows(),
			"recordsFiltered" => $candidates->num_rows(),
			"data" => $data
		);
		echo json_encode($output);
		exit();
	}

	public function read_application()
	{
		$session = $this->session->userdata('username');
		if (empty($session)) {
			redirect('admin/');
		}
		$data['title'] = $this->Xin_model->site_title();
		$id = $this->input->get('application_id');
		$result = $this->Job_post_model->read_job_application_info($id);
		$building = $this->Job_post_model->read_building_information();

		$data = array(
			'application_id'        => $result[0]->application_id,
			'user_id'               => $result[0]->user_id,
			'id_user'               => $result[0]->id_user,
			'job_id'                => $result[0]->job_id,
			'notelp'                => $result[0]->notelp,
			'application_status'    => $result[0]->application_status,
			'message'               => $result[0]->message,
			'building'              => $building
		);
		if (!empty($session)) {
			$this->load->view('admin/job_post/dialog_application', $data);
		} else {
			redirect('admin/');
		}
	}
	public function by_job()
	{
		$session = $this->session->userdata('username');
		if (empty($session)) {
			redirect('admin/');
		}
		$system = $this->Xin_model->read_setting_info(1);
		if ($system[0]->module_recruitment != 'true') {
			redirect('admin/dashboard');
		}
		$id = $this->uri->segment(4);
		$job = $this->Job_post_model->read_job_information($id);

		if (is_null($job)) {
			redirect('admin/job_candidates/');
		}
		$data['title'] = $this->lang->line('xin_job_applicants_title') . ' | ' . $this->Xin_model->site_title();
		$data['breadcrumbs']    = $job[0]->job_title . ' ' . $this->lang->line('xin_job_applicants_title');
		$data['path_url']       = 'job_applicants';
		// 		var_dump($building);
		$role_resources_ids = $this->Xin_model->user_role_resource();
		if (in_array('51', $role_resources_ids)) {
			if (!empty($session)) {
				$data['subview'] = $this->load->view("admin/job_post/view_applicants", $data, TRUE);
				$this->load->view('admin/layout/layout_main', $data); //page load
			} else {
				redirect('admin/');
			}
		} else {
			redirect('admin/dashboard');
		}
	}
	public function by_employer()
	{
		$session = $this->session->userdata('username');
		if (empty($session)) {
			redirect('admin/');
		}
		$system = $this->Xin_model->read_setting_info(1);
		if ($system[0]->module_recruitment != 'true') {
			redirect('admin/dashboard');
		}
		$id = $this->uri->segment(4);
		$employer = $this->Users_model->read_users_info($id);
		if (is_null($employer)) {
			redirect('admin/job_post/employer/');
		}

		$data['title'] = $this->lang->line('xin_job_applicants_title') . ' | ' . $this->Xin_model->site_title();
		$data['breadcrumbs'] = $employer[0]->first_name . ' ' . $employer[0]->last_name . ' ' . $this->lang->line('xin_job_applicants_title');
		$data['path_url'] = 'job_employer_applicants';
		$role_resources_ids = $this->Xin_model->user_role_resource();
		if (in_array('51', $role_resources_ids)) {
			if (!empty($session)) {
				$data['subview'] = $this->load->view("admin/job_post/view_employer_applicants", $data, TRUE);
				$this->load->view('admin/layout/layout_main', $data); //page load
			} else {
				redirect('admin/');
			}
		} else {
			redirect('admin/dashboard');
		}
	}
	public function applicants_list()
	{

		$data['title'] = $this->Xin_model->site_title();
		$session = $this->session->userdata('username');
		if (!empty($session)) {
			$this->load->view("admin/job_post/view_applicants", $data);
		} else {
			redirect('admin/');
		}
		// Datatables Variables
		$draw = intval($this->input->get("draw"));
		$start = intval($this->input->get("start"));
		$length = intval($this->input->get("length"));
		$id = $this->uri->segment(4);
		$role_resources_ids = $this->Xin_model->user_role_resource();

		$applicants = $this->Job_post_model->get_jobs_single_candidate($id);

		$data = array();

		foreach ($applicants->result() as $r) {
			// get job title
			$job = $this->Job_post_model->read_job_information($r->job_id);
			if (!is_null($job)) {
				$job_title = $job[0]->job_title;
			} else {
				$job_title = '-';
			}
			// get date
			$created_at = $this->Xin_model->set_date_format($r->created_at);
			// applicant status
			if ($r->value <= 50) {
				$nilai = '<span class="badge bg-danger ">' . $r->value . '</span>';
			} else if ($r->value <= 75) {
				$nilai = '<span class="badge bg-warning">' . $r->value . '</span>';
			} else if ($r->value >= 76) {
				$nilai = '<span class="badge bg-primary">' . $r->value . '</span>';
			}

			if ($r->application_status == 0) {
				$status = '<span class="badge bg-warning">' . $this->lang->line('xin_pending') . '</span>';
			} else if ($r->application_status == 1) {
				$status = '<span class="badge bg-primary">' . $this->lang->line('xin_primary_selected') . '</span>';
			}
			if ($r->application_status == 2) {
				$status = '<span class="badge bg-info">' . $this->lang->line('xin_call_for_interview') . '</span>';
			}
			if ($r->application_status == 3) {
				$status = '<span class="badge bg-success">' . $this->lang->line('xin_confirm_del') . '</span>';
			}
			if ($r->application_status == 4) {
				$status = '<span class="badge bg-danger">' . $this->lang->line('xin_rejected') . '</span>';
			}

			if (in_array('294', $role_resources_ids)) { //download
				$download = '<span data-toggle="tooltip" data-placement="top" title="' . $this->lang->line('xin_download') . ' CV">
			<a href="' . site_url('admin/download') . '?type=resume&filename=' . $r->job_resume . '"><button type="button" class="btn btn-outline-secondary btn-sm m-b-0-0 waves-effect waves-light"><i class="oi oi-cloud-download"></i></button></a></span>';
			} else {
				$download = '';
			}

			if (in_array('294', $role_resources_ids)) { //download
				$view = '<span data-toggle="tooltip" data-placement="top" title="Lihat Resume">
			<a href="' . site_url() . 'admin/job_candidates/pdf_create/p/' . $r->id_user . '" target="_blank"><button type="button" class="btn btn-outline-primary btn-sm m-b-0-0 waves-effect waves-light"><span class="oi oi-eye"></span></button></a></span>';
			} else {
				$view = '';
			}
			if (in_array('295', $role_resources_ids)) { // delete
				$delete = '<span data-toggle="tooltip" data-placement="top" title="' . $this->lang->line('xin_delete') . '">
			<button type="button" class="btn btn-outline-danger btn-sm m-b-0-0 waves-effect waves-light delete" data-toggle="modal" data-target=".delete-modal" data-record-id="' . $r->application_id . '"><i class="fas fa-trash-restore"></i></button></span>';

				// 			$edit_status = '<span data-toggle="tooltip" data-placement="top" title="'.$this->lang->line('xin_change_status').'">
				// 			<button type="button" class="btn icon-btn btn-sm btn-outline-secondary waves-effect waves-light" data-toggle="modal" data-target=".add-modal-data" data-application_id="'. $r->application_id . '"><i class="far fa-arrow-alt-circle-right"></i></button></span>';

				$edit_status = '<span data-toggle="tooltip" data-placement="top" title="' . $this->lang->line('xin_change_status') . '">
			<button type="button" class="btn btn-outline-dark btn-sm m-b-0-0 waves-effect waves-light" data-toggle="modal" data-target=".add-modal-data" data-application_id="' . $r->application_id . '"><i class="far fa-arrow-alt-circle-right"></i></button></span>';
			} else {
				$delete = '';
				$edit_status = '';
			}
			$iticket_code = $r->full_name . '<br><small class="text-muted"><i>' . $r->email . '<i></i></i></small>';
			$cover_letter = '<a><button class="btn icon-btn btn-sm btn-outline-secondary waves-effect waves-light" data-toggle="modal" data-target=".view-modal-data" data-application_id="' . $r->application_id . '" data-user_id="' . $r->user_id . '">' . $this->lang->line('xin_view') . ' ' . $this->lang->line('xin_jobs_cover_letter') . '</button></a>';
			$combhr = $download . $edit_status . $delete . $view . ' ' . $nilai;

			if ($r->application_status == 2) {
				$interview = $r->interview_date;
			} else {
				$interview = '-';
			}

			$data[] = array(
				$combhr,
				$r->full_name,
				$r->email,
				$status,
				$interview,
				$created_at
			);
		}

		$output = array(
			"draw" => $draw,
			"recordsTotal" => $applicants->num_rows(),
			"recordsFiltered" => $applicants->num_rows(),
			"data" => $data
		);
		echo json_encode($output);
		exit();
	}
	public function employer_applicants_list()
	{

		$data['title'] = $this->Xin_model->site_title();
		$session = $this->session->userdata('username');
		if (!empty($session)) {
			$this->load->view("admin/job_post/view_employer_applicants", $data);
		} else {
			redirect('admin/');
		}
		// Datatables Variables
		$draw = intval($this->input->get("draw"));
		$start = intval($this->input->get("start"));
		$length = intval($this->input->get("length"));
		$id = $this->uri->segment(4);
		$role_resources_ids = $this->Xin_model->user_role_resource();

		$applicants = $this->Job_post_model->get_jobs_employer_candidate($id);

		$data = array();

		foreach ($applicants->result() as $r) {
			// get job title
			$job = $this->Job_post_model->read_job_information($r->job_id);
			if (!is_null($job)) {
				$job_title = $job[0]->job_title;
			} else {
				$job_title = '-';
			}
			// get date
			$created_at = $this->Xin_model->set_date_format($r->created_at);
			// applicant status
			if ($r->application_status == 0) {
				$status = '<span class="badge bg-yellow">' . $this->lang->line('xin_pending') . '</span>';
			} else if ($r->application_status == 1) {
				$status = '<span class="badge bg-teal">' . $this->lang->line('xin_primary_selected') . '</span>';
			}
			if ($r->application_status == 2) {
				$status = '<span class="badge bg-primary">' . $this->lang->line('xin_call_for_interview') . '</span>';
			}
			if ($r->application_status == 3) {
				$status = '<span class="badge bg-green">' . $this->lang->line('xin_confirm_del') . '</span>';
			}
			if ($r->application_status == 4) {
				$status = '<span class="badge bg-red">' . $this->lang->line('xin_rejected') . '</span>';
			}

			if (in_array('294', $role_resources_ids)) { //download
				$download = '<span data-toggle="tooltip" data-placement="top" title="' . $this->lang->line('xin_download') . '">
			<a href="' . site_url('admin/download') . '?type=resume&filename=' . $r->job_resume . '"><button type="button" class="btn btn-outline-secondary btn-sm m-b-0-0 waves-effect waves-light"><i class="oi oi-cloud-download"></i></button></a></span>';
			} else {
				$download = '';
			}
			if (in_array('295', $role_resources_ids)) { // delete
				$delete = '<span data-toggle="tooltip" data-placement="top" title="' . $this->lang->line('xin_delete') . '"><button type="button" class="btn btn-outline-danger btn-sm m-b-0-0 waves-effect waves-light delete" data-toggle="modal" data-target=".delete-modal" data-record-id="' . $r->application_id . '"><i class="fas fa-trash-restore"></i></button></span>';
				$edit_status = '<span data-toggle="tooltip" data-placement="top" title="' . $this->lang->line('xin_change_status') . '"><button type="button" class="btn icon-btn btn-sm btn-outline-secondary waves-effect waves-light" data-toggle="modal" data-target=".add-modal-data" data-application_id="' . $r->application_id . '"><i class="fas fa-pencil-alt-square-o"></i></button></span>';
			} else {
				$delete = '';
				$edit_status = '';
			}
			$iticket_code = $r->full_name . '<br><small class="text-muted"><i>' . $r->email . '<i></i></i></small>';
			$cover_letter = '<a><button class="btn icon-btn btn-sm btn-outline-secondary waves-effect waves-light" data-toggle="modal" data-target=".view-modal-data" data-application_id="' . $r->application_id . '">' . $this->lang->line('xin_view') . ' ' . $this->lang->line('xin_jobs_cover_letter') . '</button></a>';
			$combhr = $download . $edit_status . $delete;

			$data[] = array(
				$combhr,
				$r->full_name,
				$r->email,
				$status,
				$cover_letter,
				$created_at
			);
		}

		$output = array(
			"draw" => $draw,
			"recordsTotal" => $applicants->num_rows(),
			"recordsFiltered" => $applicants->num_rows(),
			"data" => $data
		);
		echo json_encode($output);
		exit();
	}

	function formatInterviewDate($dateString, $timeString)
	{
		$date = new DateTime($dateString . ' ' . $timeString);
		$monthNames = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"];
		$day = $date->format('j');
		$month = $monthNames[(int)$date->format('n') - 1];
		$year = $date->format('Y');
		$hours = $date->format('H');
		$minutes = $date->format('i');

		return "$day $month $year jam $hours:$minutes";
	}

	private function formatIndonesianDate($date_input)
	{
		// Buat objek DateTime dari input tanggal
		$date = DateTime::createFromFormat('Y-m-d', $date_input);

		// Array hari dan bulan dalam bahasa Indonesia
		$days = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
		$months = [
			1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
			7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
		];

		// Mengambil nama hari dan bulan dalam bahasa Indonesia
		$day_name = $days[$date->format('w')];
		$month_name = $months[(int)$date->format('m')];

		// Membentuk string tanggal dalam format yang diinginkan
		$formatted_date = $day_name . ', ' . $date->format('j') . ' ' . $month_name . ' ' . $date->format('Y');

		return $formatted_date;
	}



	public function update_status()
	{
		if ($this->input->post('edit_type') == 'update_status') {
			$Return = array('result' => '', 'error' => '', 'csrf_hash' => '');
			$Return['csrf_hash'] = $this->security->get_csrf_hash();

			$text = '';
			$status = $this->input->post('status');
			$notelp = $this->input->post('notelp');
			$pic = $this->input->post('pic');
			$status_date_input = $this->input->post('status_date');
			$lokasi = $this->input->post('building');
			$status_date = $this->formatIndonesianDate($status_date_input);
			$status_time = $this->input->post('status_time');
			$id = $this->input->post('jid');

			error_log("Status: $status, Notelp: $notelp, PIC: $pic, Status Date: $status_date_input, Lokasi: $lokasi, Status Time: $status_time, ID: $id");

			$result = $this->Users_model->read_users_info_job($id);
			$nama_lengkap = $result[0]->first_name . ' ' . $result[0]->last_name;
			$job_title = $result[0]->job_title;

			$datetime = $status_date_input . ' ' . $status_time;

			// Cek apakah status diisi
			if ($status == '') {
				$Return['error'] = 'Status harus diisi';
				echo json_encode($Return);
				exit;
			}

			// Jika status adalah 2, cek apakah field lainnya diisi
			if ($status == 2) {
				if ($lokasi == '') {
					$Return['error'] = 'Lokasi harus diisi';
					header('Content-Type: application/json');
					echo json_encode($Return);
					exit;
				}
				if ($status_time == '') {
					$Return['error'] = 'Waktu harus diisi';
					header('Content-Type: application/json');
					echo json_encode($Return);
					exit;
				}
				if ($pic == '') {
					$Return['error'] = 'PIC harus diisi';
					header('Content-Type: application/json');
					echo json_encode($Return);
					exit;
				}

				// Jika tidak ada error, buat pesan WhatsApp
				$text .= "Selamat Pagi $nama_lengkap\n\n";
				$text .= "Kami dari CV. QTA ingin mengundang saudara/saudari untuk hadir dalam INTERVIEW pada:\n\n";
				$text .= "Hari/Tanggal:  $status_date\n";
				$text .= "Pukul : $status_time\n";
				$text .= "Posisi : $job_title\n";
				$text .= "Lokasi Interview : $lokasi\n";
				$text .= "Pakaian : Bebas rapi bekerah\n";
				$text .= "Menemui : $pic\n\n";
				$text .= "Harap membawa LAMARAN (FC KTP, FC Ijazah, CV/Riwayat hidup, pas foto 3x4 1 lembar) dan FORM PELAMAR yang sudah diprint out dan diisi dari rumah.\n\n";
				$text .= "Berikut link download FORM PELAMAR https://drive.google.com/file/d/1DNErLEkiY_t_bT9kQ_-wP2nrE2PCjIqn/view?usp=sharing\n\n";
				$text .= "Mohon hadir 10 menit sebelum dimulai.\n";
				$text .= "Konfirmasi kehadiran Ke 081233505738, *HADIR/TIDAK HADIR_NAMA*.Terima kasih.\n\n\n";
				$text .= "Hormat kami\n\n";
				$text .= "Tim Rekrutmen\n\n";
				$text .= "CV QTA GROUP\n\n";
				$wa = array(
					'wa_mode'   => 0,
					'wa_no'     => $notelp,
					'wa_text'   => $text
				);
				$whatapp = $this->Job_post_model->sendStatus($wa);
			}

			$data = array(
				'application_status'    => $status,
				'interview_date'        => $datetime
			);
			$result = $this->Job_post_model->update_applicant_status($data, $id);
			if ($result == TRUE) {
				$Return['result'] = 'Update status berhasil';
			} else {
				$Return['error'] = $this->lang->line('xin_error_msg');
			}
			header('Content-Type: application/json');
			echo json_encode($Return);
			exit;
		}
	}





	// delete job candidate / job application	
	public function delete()
	{
		/* Define return | here result is used to return user data and error for error message */
		$Return = array('result' => '', 'error' => '', 'csrf_hash' => '');
		$id = $this->uri->segment(4);
		$Return['csrf_hash'] = $this->security->get_csrf_hash();
		$result = $this->Job_post_model->delete_application_record($id);
		if (isset($id)) {
			$Return['result'] = $this->lang->line('xin_error_job_application');
		} else {
			$Return['error'] = $this->lang->line('xin_error_msg');
		}
		$this->output($Return);
	}

	public function pdf_create()
	{

		//$this->load->library('Pdf');
		$system = $this->Xin_model->read_setting_info(1);
		// create new PDF document
		$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

		$key = $this->uri->segment(5);
		// Membuat instance TCPDF
		$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

		// Mengatur informasi dokumen
		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor('Nama Penulis');
		$pdf->SetSubject('Subjek Dokumen');
		$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

		// Mengatur header dan footer
		$pdf->setPrintHeader(true);
		$pdf->setPrintFooter(true);
		$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, 'Mie Djoetek', 'Data Diri Pelamar');
		$pdf->setFooterData(array(0, 64, 0), array(0, 64, 128));

		// Mengatur font header dan footer
		$pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
		$pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

		// Mengatur default monospaced font
		$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

		// Mengatur margin
		$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
		$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

		// Mengatur auto page breaks
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

		// Mengatur image scale factor
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

		// Menambahkan halaman
		$pdf->AddPage();
		$pdf->SetFont('helvetica', '', 8);

		$pdf->Ln(7);
		$title = <<<EOD
<h3>A. IDENTITAS</h3>
EOD;
		$pdf->writeHTMLCell(0, 0, '', '', $title, 0, 1, 0, true, 'C', true);

		// Mengambil data dari database
		$identitas = $this->Users_model->read_users_info($key);

		// Menyiapkan variabel untuk informasi identitas
		$namalengkap = '';
		$gender = '';
		$tgllahir = '';
		$agama = '';
		$notelp = '';
		$email = '';
		$alamat1 = '';
		$alamat2 = '';
		$nik = '';
		$foto = ''; // Pastikan variabel foto sudah ada dan diambil dari database atau diatur dengan benar

		foreach ($identitas as $r) {
			$namalengkap = $r->first_name . ' ' . $r->last_name;
			if (isset($r->tgl_lahir)) {
				$tgllahir = $this->formatIndonesianDate($r->tgl_lahir);
			} else {
				$tgllahir = '';
			}
			$gender = ($r->gender == 'Male') ? 'Laki - laki' : 'Perempuan';
			if ($r->agama == 1) {
				$agama = 'Islam';
			} elseif ($r->agama == 2) {
				$agama = 'Kristen';
			} elseif ($r->agama == 3) {
				$agama = 'Katolik';
			}

			$alamat1 = $r->address_1;
			$alamat2 = $r->address_2;
			$r_provinsiktp = '';
			$r_kotaktp = '';
			$r_kecktp = '';

			if ($r->provinsi_ktp) {
				$provinsi_ktp = $this->Users_model->get_wilayah($r->provinsi_ktp);
				$r_provinsiktp = $provinsi_ktp[0]->nama . ', ';
			}

			if ($r->kota_ktp) {
				$kota_ktp = $this->Users_model->get_wilayah($r->kota_ktp);
				$r_kotaktp = $kota_ktp[0]->nama . ', ';
			}

			if ($r->kecamatan_ktp) {
				$kec_ktp = $this->Users_model->get_wilayah($r->kecamatan_ktp);
				$r_kecktp = $kec_ktp[0]->nama . ', ';
			}
			$alamat_ktp = $r_provinsiktp . $r_kotaktp . $r_kecktp . $alamat1;

			if ($r->ktp == 1) {
				$alamat_dom = 'alamat sama seperti KTP';
			} else {
				$r_provinsidom = '';
				$r_kotadom = '';
				$r_kecdom = '';

				if (!empty($r->provinsi_dom)) {
					$provinsi_dom = $this->Users_model->get_wilayah($r->provinsi_dom);
					$r_provinsidom = $provinsi_dom[0]->nama . ', ';
				}

				if (!empty($r->kota_dom)) {
					$kota_dom = $this->Users_model->get_wilayah($r->kota_dom);
					$r_kotadom = $kota_dom[0]->nama . ', ';
				}

				if (!empty($r->kecamatan_dom)) {
					$kec_ktp = $this->Users_model->get_wilayah($r->kecamatan_dom);
					$r_kecdom = $kec_ktp[0]->nama . ', ';
				}
				$alamat_dom = $r_provinsidom . $r_kotadom . $r_kecdom . $alamat2;
			}


			$notelp = $r->contact_number;
			$email = $r->email;
			$nik = $r->nik;
			$foto = base_url('uploads/employers/' . $r->company_logo); // Menggunakan base_url
		}
        
		$pdf->SetTitle('Data '.$namalengkap);
		// Check if the photo file exists
		if (file_exists(FCPATH . 'uploads/employers/' . $r->company_logo)) {
			$imgTag = '<img src="' . $foto . '" style="width:150px;height:auto"/>';
		} else {
			error_log('Foto tidak ditemukan: ' . $foto);
			$imgTag = ''; // Handle missing image scenario
		}

		// Menggabungkan informasi identitas dalam tabel
		$tblidentitas = '<table cellspacing="0" cellpadding="4">
<tr>
    <td colspan="2">
        <table cellspacing="0" cellpadding="4">
            <tr><td>1. Nama Lengkap</td><td>: ' . $namalengkap . '</td></tr>
            <tr><td>2. Jenis Kelamin</td><td>: ' . $gender . '</td></tr>
            <tr><td>3. Tanggal Lahir</td><td>: ' . $tgllahir . '</td></tr>
            <tr><td>4. Agama</td><td>: ' . $agama . '</td></tr>
            <tr><td>5. Nomor HP</td><td>: ' . $notelp . '</td></tr>
            <tr><td>6. Alamat Email</td><td>: ' . $email . '</td></tr>
            <tr><td>8. Alamat KTP</td><td>: ' . $alamat_ktp . '</td></tr>
            <tr><td>7. Alamat Domisili</td><td>: ' . $alamat_dom . '</td></tr>
            <tr><td>9. Nomor KTP yang berlaku</td><td>: ' . $nik . '</td></tr>
        </table>
    </td>
    <td style="text-align: right;" rowspan="8">' . $imgTag . '</td>
</tr>
</table>';

		// Output HTML ke PDF
		$pdf->writeHTML($tblidentitas, true, false, true, false, '');


		$pdf->Ln(7);
		$title = <<<EOD
<h3>B. DOKUMEN</h3>
EOD;
		$pdf->writeHTMLCell(0, 0, '', '', $title, 0, 1, 0, true, 'C', true);

		$document = $this->Users_model->set_employer_documents($key);
		if ($document->num_rows() > 0) {
			$htmldocument = '<table border="1" cellpadding="4" cellspacing="0" style="width:100%">
            <thead>
                <tr style="background-color:#ff8b8b;">
                    <th style="width:5%;text-align:center">No</th>
                    <th style="width:35%;text-align:center">Jenis</th>
                    <th style="width:30%;text-align:center">Judul</th>
                    <th style="width:30%;text-align:center">Aksi</th>
                </tr>
            </thead>
            <tbody>';

			$no = 1;
			foreach ($document->result() as $r) {
				if ($r->document_type == 1) {
					$type = 'Ijazah';
				} elseif ($r->document_type == 2) {
					$type = 'Transkrip Nilai';
				} elseif ($r->document_type == 3) {
					$type = 'KTP';
				} elseif ($r->document_type == 4) {
					$type = 'Kartu Keluarga';
				} elseif ($r->document_type == 5) {
					$type = 'SIM';
				} elseif ($r->document_type == 6) {
					$type = 'Lain - lain';
				}

				$liat = base_url('uploads/document/' . $r->document_file); // Menggunakan base_url
				$htmldocument .= '<tr>
                <td style="width:5%;text-align:center">' . $no++ . '</td>
                <td style="width:35%;text-align:center">' . $type . '</td>
                <td style="width:30%;text-align:center">' . $r->document_name . '</td>
                <td style="width:30%;text-align:center"><a href="https://miedjoetek.com/hris/admin/download?type=document&filename=' . $r->document_file . '">download</a> || <a href="' . $liat . '" target="_blank">lihat</a></td>
              </tr>';
			}

			$htmldocument .= '</tbody></table>';
		} else {
			$htmldocument = '<p>Belum mengisi form document kerja.</p>';
		}
		// Output HTML to PDF
		$pdf->writeHTML($htmldocument, true, false, true, false, '');


		$pdf->Ln(7);
		$title = <<<EOD
<h3>C. SUSUNAN KELUARGA</h3>
EOD;
		$pdf->writeHTMLCell(0, 0, '', '', $title, 0, 1, 0, true, 'C', true);

		$family = $this->Users_model->set_employer_family($key);
		// Memeriksa apakah terdapat data pengalaman kerja
		if ($family->num_rows() > 0) {
			$htmlfamily = '<table border="1" cellpadding="4" style="width:100%; border-collapse: collapse;">
            <thead>
                <tr style="background-color:#ff8b8b;">
                    <th style="width:5%; text-align:center;">No</th>
                    <th style="width:25%; text-align:center;">Nama</th>
                    <th style="width:15%; text-align:center;">Status</th>
                    <th style="width:8%; text-align:center;">L/P</th>
                    <th style="width:15%; text-align:center;">Pendidikan</th>
                    <th style="width:17%; text-align:center;">Pekerjaan</th>
                    <th style="width:15%; text-align:center;">No Telepon</th>
                </tr>
            </thead>
            <tbody>';

			$no = 1;
			foreach ($family->result() as $r) {
				$nama = $r->name_family;
				$type = '';
				switch ($r->status) {
					case 1:
						$type = 'Ibu';
						break;
					case 2:
						$type = 'Ayah';
						break;
					case 3:
						$type = 'Saudara';
						break;
					case 4:
						$type = 'Istri';
						break;
					case 5:
						$type = 'Suami';
						break;
					case 6:
						$type = 'Anak';
						break;
					default:
						$type = '-';
						break;
				}

				$notelp = $r->notelp;
				$gender = ($r->gender == 1) ? 'L' : 'P';
				$pendidikan = $r->pendidikan;
				$pekerjaan = $r->pekerjaan;

				$htmlfamily .= '<tr>
                <td style="width:5%; text-align:center;">' . $no++ . '</td>
                <td style="width:25%; text-align:left; padding-left:5px;">' . $nama . '</td>
                <td style="width:15%; text-align:center;">' . $type . '</td>
                <td style="width:8%; text-align:center;">' . $gender . '</td>
                <td style="width:15%; text-align:left; padding-left:5px;">' . $pendidikan . '</td>
                <td style="width:17%; text-align:left; padding-left:5px;">' . $pekerjaan . '</td>
                <td style="width:15%; text-align:center;">' . $notelp . '</td>
              </tr>';
			}

			$htmlfamily .= '</tbody></table>';
		} else {
			$htmlfamily = '<p>Belum mengisi form pengalaman kerja.</p>';
		}
		// Output HTML to PDF
		$pdf->writeHTML($htmlfamily, true, false, true, false, '');


		$pdf->Ln(7);
		$title = <<<EOD
<h3>D. RIWAYAT PENDIDIKAN</h3>
EOD;
		$pdf->writeHTMLCell(0, 0, '', '', $title, 0, 1, 0, true, 'C', true);
		$pendidikan = $this->Users_model->set_employer_pendidikan($key);
		if ($pendidikan->num_rows() > 0) {
			$htmlpendidikan = '<table border="1" cellpadding="4" style="width:100%; border-collapse: collapse;">
            <thead>
                <tr style="background-color:#ff8b8b;">
                    <th style="width:5%; text-align:center;">No</th>
                    <th style="width:15%; text-align:center;">Tingkat</th>
                    <th style="width:30%; text-align:center;">Nama Sekolah</th>
                    <th style="width:30%; text-align:center;">Jurusan</th>
                    <th style="width:20%; text-align:center;">Periode</th>
                </tr>
            </thead>
            <tbody>';
			$no = 1;
			foreach ($pendidikan->result() as $r) {
				if ($r->tingkat == 1) {
					$type = 'SD/Sederajat';
				} elseif ($r->tingkat == 2) {
					$type = 'SMP/Sederajat';
				} elseif ($r->tingkat == 3) {
					$type = 'SMA/Sederajat';
				} elseif ($r->tingkat == 4) {
					$type = 'D3';
				} elseif ($r->tingkat == 5) {
					$type = 'S1';
				} elseif ($r->tingkat == 6) {
					$type = 'Lainnya';
				}
				$namasekolah = $r->name_pendidikan;
				$jurusan  = $r->jurusan;
				// Mengubah format tanggal
				$start_date = DateTime::createFromFormat('Y-m-d', $r->start_date)->format('j F Y');
				$end_date = DateTime::createFromFormat('Y-m-d', $r->end_date)->format('j F Y');
				$periode = $start_date . ' - ' . $end_date;

				$htmlpendidikan .= '<tr>
                <td style="width:5%; text-align:center;">' . $no++ . '</td>
                <td style="width:15%; text-align:center;">' . $type . '</td>
                <td style="width:30%; text-align:left; padding-left:5px;">' . $namasekolah . '</td>
                <td style="width:30%; text-align:left; padding-left:5px;">' . $jurusan . '</td>
                <td style="width:20%; text-align:center;">' . $periode . '</td>
              </tr>';
			}



			$htmlpendidikan .= '</tbody></table>';
		} else {
			$htmlpendidikan = '<p>Belum mengisi form pengalaman kerja.</p>';
		}

		// Output HTML to PDF
		$pdf->writeHTML($htmlpendidikan, true, false, true, false, '');


		$pdf->Ln(7);
		$title = <<<EOD
<h3>E. BAHASA ASING</h3>
EOD;
		$pdf->writeHTMLCell(0, 0, '', '', $title, 0, 1, 0, true, 'C', true);

		$bahasa = $this->Users_model->set_employer_bahasa($key);
		if ($bahasa->num_rows() > 0) {
			$htmlbahasa = '<table border="1" cellpadding="4" cellspacing="0" style="width:100%">
            <thead>
                <tr style="background-color:#ff8b8b;">
                    <th style="width:5%;text-align:center">No</th>
                    <th style="width:35%;text-align:center">Bahasa</th>
                    <th style="width:30%;text-align:center">Tulis</th>
                    <th style="width:30%;text-align:center">Bicara</th>
                </tr>
            </thead>
            <tbody>';

			$no = 1;
			foreach ($bahasa->result() as $r) {
				$tulis = '';
				$bicara = '';

				if ($r->tulis == 1) {
					$tulis = 'Kurang';
				} elseif ($r->tulis == 2) {
					$tulis = 'Cukup';
				} elseif ($r->tulis == 3) {
					$tulis = 'Baik';
				}

				if ($r->bicara == 1) {
					$bicara = 'Kurang';
				} elseif ($r->bicara == 2) {
					$bicara = 'Cukup';
				} elseif ($r->bicara == 3) {
					$bicara = 'Baik';
				}

				$bahasa_name = $r->name_bahasa;

				$htmlbahasa .= '<tr>
                <td style="width:5%;text-align:center">' . $no++ . '</td>
                <td style="width:35%;text-align:center">' . $bahasa_name . '</td>
                <td style="width:30%;text-align:center">' . $tulis . '</td>
                <td style="width:30%;text-align:center">' . $bicara . '</td>
              </tr>';
			}

			$htmlbahasa .= '</tbody></table>';
		} else {
			$htmlbahasa = '<p>Belum mengisi form pengalaman kerja.</p>';
		}
		// Output HTML to PDF
		$pdf->writeHTML($htmlbahasa, true, false, true, false, '');


		$pdf->Ln(7);
		$title = <<<EOD
<h3>F. PENGALAMAN KERJA</h3>
EOD;
		$pdf->writeHTMLCell(0, 0, '', '', $title, 0, 1, 0, true, 'C', true);

		$work = $this->Users_model->set_employer_work($key);
		// Memeriksa apakah terdapat data pengalaman kerja
		if ($work->num_rows() > 0) {
			$htmlwork = '<table border="1" cellpadding="4" style="width:100%; border-collapse: collapse;">
            <thead>
                <tr style="background-color:#ff8b8b;">
                    <th style="width:15%; text-align:center;">Nama Perusahaan</th>
                    <th style="width:15%; text-align:center;">Jenis</th>
                    <th style="width:20%; text-align:center;">Alamat</th>
                    <th style="width:15%; text-align:center;">Jabatan</th>
                    <th style="width:10%; text-align:center;">Gaji</th>
                    <th style="width:25%; text-align:center;">Periode</th>
                </tr>
            </thead>
            <tbody>';
			$no = 1;
			foreach ($work->result() as $r) {
				$namaperusahaan = $r->nama_perusahaan;
				$jenis  = $r->jenis_perusahaan;
				$alamat = $r->alamat_perusahaan;
				$jabatan = $r->jabatan;
				$gaji = $r->gaji;

				// Mengubah format tanggal
				$start_date = DateTime::createFromFormat('Y-m-d', $r->start_date)->format('j F Y');
				$end_date = DateTime::createFromFormat('Y-m-d', $r->end_date)->format('j F Y');

				if ($r->kerja == 1) {
					$periode = $start_date . ' - sekarang';
				} else {
					$periode = $start_date . ' - ' . $end_date;
				}

				$htmlwork .= '<tr>
                <td style="width:15%; text-align:left; padding-left:5px;">' . $namaperusahaan . '</td>
                <td style="width:15%; text-align:center;">' . $jenis . '</td>
                <td style="width:20%; text-align:left; padding-left:5px;">' . $alamat . '</td>
                <td style="width:15%; text-align:left; padding-left:5px;">' . $jabatan . '</td>
                <td style="width:10%; text-align:left; padding-left:5px;">' . $gaji . '</td>
                <td style="width:25%; text-align:center;">' . $periode . '</td>
              </tr>';
			}



			$htmlwork .= '</tbody></table>';
		} else {
			// Tidak ada data pengalaman kerja
			$htmlwork = '<p>Belum mengisi form pengalaman kerja.</p>';
		}
		// Output HTML to PDF
		$pdf->writeHTML($htmlwork, true, false, true, false, '');



		// Menambahkan halaman
		// 		$pdf->AddPage();

		// 		// Mengatur font
		// 		$pdf->SetFont('helvetica', '', 8);

		// Mencetak title
		// Mencetak title
		$title = <<<EOD
<h3>DAFTAR PERTANYAAN</h3>
EOD;
		$pdf->writeHTMLCell(0, 0, '', '', $title, 0, 1, 0, true, 'C', true);

		// Mengambil data dari database
		$pertanyaan = $this->Users_model->read_users_question();
		$answer = $this->Users_model->read_users_answer($key);

		// Mencetak pertanyaan dan jawaban
		$html = '';
		if (!empty($pertanyaan) && is_array($pertanyaan)) {
			foreach ($pertanyaan as $index => $r) {
				$jawaban = '';
				if (!empty($answer) && is_array($answer)) {
					foreach ($answer as $a) {
						if ($a->id_question == $r->id_question) {
							$jawaban = $a->answer;
							break;
						}
					}
				}

				if (empty($jawaban)) {
					$jawaban = '<em>Belum dijawab</em>';
				}

				$html .= '<p><strong>' . ($index + 1) . '. ' . $r->question . '</strong></p>';
				$html .= '<p>' . $jawaban . '</p>';
			}

			// Output HTML to PDF
			$pdf->writeHTML($html, true, false, true, false, '');
		}

		// Tutup dan output PDF
		ob_start();
		$pdf->Output('daftar_pertanyaan.pdf', 'I');
		ob_end_flush();
	}
}
