<?php


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

class Studentreport extends Admin_Controller
{
	public $load;
	public $session;
	public $lang;
	public $data;
	public $form_validation;
	public $input;
	public $studentrelation_m;
	public $uri;
	public $classes_m;
	public $section_m;
	public $phpspreadsheet;
	/*
| -----------------------------------------------------
| PRODUCT NAME: 	INILABS SCHOOL MANAGEMENT SYSTEM
| -----------------------------------------------------
| AUTHOR:			INILABS TEAM
| -----------------------------------------------------
| EMAIL:			info@inilabs.net
| -----------------------------------------------------
| COPYRIGHT:		RESERVED BY INILABS IT
| -----------------------------------------------------
| WEBSITE:			http://inilabs.net
| -----------------------------------------------------
*/
	protected $_bloodArray = array(
		'0' => 'A+',
		'1' => 'A-',
		'2' => 'B+',
		'3' => 'B-',
		'4' => 'AB+',
		'5' => 'AB-',
		'6' => 'O+',
		'7' => 'O-',
		'8' => 'Unknown',
	);

	function __construct()
	{
		parent::__construct();
		$this->load->model('section_m');
		$this->load->model("classes_m");
		$this->load->model("studentrelation_m");
		$language = $this->session->userdata('lang');
		$this->lang->load('studentreport', $language);
	}

	public function index()
	{
		$this->data['headerassets'] = array(
			'css' => array(
				'assets/datepicker/datepicker.css',
				'assets/select2/css/select2.css',
				'assets/select2/css/select2-bootstrap.css'
			),
			'js' => array(
				'assets/datepicker/datepicker.js',
				'assets/select2/select2.js'
			)
		);

		$this->data['classes'] = $this->classes_m->general_get_classes();

		$this->data["subview"] = "report/student/StudentReportView";
		$this->load->view('_layout_main', $this->data);
	}

	public function rules($reportfor = 'blood')
	{
		$rules = array(
			array(
				'field' => 'reportfor',
				'label' => $this->lang->line("studentreport_routine_for"),
				'rules' => 'trim|required|xss_clean|callback_unique_data'
			)
		);

		if ($reportfor == "blood") {
			$rules[] = array(
				'field' => 'blood',
				'label' => $this->lang->line("studentreport_blood"),
				'rules' => 'trim|required|xss_clean|callback_unique_data'
			);
		} elseif ($reportfor == "country") {
			$rules[] = array(
				'field' => 'country',
				'label' => $this->lang->line("studentreport_country"),
				'rules' => 'trim|required|xss_clean|callback_unique_data'
			);
		} elseif ($reportfor == 'gender') {
			$rules[] = array(
				'field' => 'gender',
				'label' => $this->lang->line("studentreport_gender"),
				'rules' => 'trim|required|xss_clean|callback_unique_data'
			);
		} elseif ($reportfor == 'birthday') {
			$rules[] = array(
				'field' => 'birthdaydate',
				'label' => $this->lang->line("studentreport_birthdaydate"),
				'rules' => 'trim|required|xss_clean|callback_date_valid'
			);
		}

		$rules[] = array(
			'field' => 'classesID',
			'label' => $this->lang->line("studentreport_class"),
			'rules' => 'trim|xss_clean'
		);

		$rules[] = array(
			'field' => 'sectionID',
			'label' => $this->lang->line("studentreport_section"),
			'rules' => 'trim|xss_clean'
		);

		return $rules;
	}

	public function send_pdf_to_mail_rules($reportfor = 'blood')
	{
		$rules = array(
			array(
				'field' => 'reportfor',
				'label' => $this->lang->line("studentreport_routine_for"),
				'rules' => 'trim|required|xss_clean|callback_unique_data'
			),
			array(
				'field' => 'to',
				'label' => $this->lang->line("studentreport_to"),
				'rules' => 'trim|required|xss_clean|valid_email'
			),
			array(
				'field' => 'subject',
				'label' => $this->lang->line("studentreport_subject"),
				'rules' => 'trim|required|xss_clean'
			),
			array(
				'field' => 'message',
				'label' => $this->lang->line("studentreport_message"),
				'rules' => 'trim|xss_clean'
			)
		);

		if ($reportfor == "blood") {
			$rules[] = array(
				'field' => 'bloodID',
				'label' => $this->lang->line("studentreport_blood"),
				'rules' => 'trim|required|xss_clean'
			);
		} elseif ($reportfor == "country") {
			$rules[] = array(
				'field' => 'country',
				'label' => $this->lang->line("studentreport_country"),
				'rules' => 'trim|required|xss_clean|callback_unique_data'
			);
		} elseif ($reportfor == 'gender') {
			$rules[] = array(
				'field' => 'gender',
				'label' => $this->lang->line("studentreport_gender"),
				'rules' => 'trim|required|xss_clean|callback_unique_data'
			);
		} elseif ($reportfor == 'birthday') {
			$rules[] = array(
				'field' => 'birthdaydate',
				'label' => $this->lang->line("studentreport_birthdaydate"),
				'rules' => 'trim|required|xss_clean|callback_date_valid'
			);
		}

		$rules[] = array(
			'field' => 'classesID',
			'label' => $this->lang->line("studentreport_class"),
			'rules' => 'trim|xss_clean'
		);

		$rules[] = array(
			'field' => 'sectionID',
			'label' => $this->lang->line("studentreport_section"),
			'rules' => 'trim|xss_clean'
		);
		return $rules;
	}

	public function date_valid($date)
	{
		if ($date) {
			if (strlen((string) $date) < 10) {
				$this->form_validation->set_message("date_valid", "%s is not valid dd-mm-yyyy.");
				return FALSE;
			} else {
				$arr = explode("-", (string) $date);
				$dd = $arr[0];
				$mm = $arr[1];
				$yyyy = $arr[2];
				if (checkdate($mm, $dd, $yyyy)) {
					return TRUE;
				} else {
					$this->form_validation->set_message("date_valid", "%s is not valid dd-mm-yyyy.");
					return FALSE;
				}
			}
		}
		return TRUE;
	}

	public function unique_data($data)
	{
		if ($data != "") {
			if ($data == "0") {
				$this->form_validation->set_message('unique_data', 'The %s field is required.');
				return FALSE;
			}
			return TRUE;
		}
		return TRUE;
	}

	public function getStudentReport()
	{
		$retArray['status'] = FALSE;
		$retArray['render'] = '';

		if (permissionChecker('studentreport')) {
			if ($_POST !== []) {
				$reportfor     = $this->input->post('reportfor');
				$blood         = $this->input->post('blood');
				$country       = $this->input->post('country');
				$birthdaydate  = $this->input->post('birthdaydate');
				$gender        = $this->input->post('gender');
				$classesID     = $this->input->post('classesID');
				$sectionID     = $this->input->post('sectionID');

				$rules = $this->rules($reportfor);
				$this->form_validation->set_rules($rules);
				if ($this->form_validation->run() == FALSE) {
					$retArray = $this->form_validation->error_array();
					$retArray['status'] = FALSE;
					echo json_encode($retArray);
					exit;
				} else {
					$this->data['reportfor'] = $reportfor;
					$bloodArray = array_flip($this->_bloodArray);
					$this->data['bloodID'] = isset($bloodArray[$blood]) ? $bloodArray[$blood] : '0';
					$this->data['country'] = $country;
					$this->data['birthdaydate'] = $birthdaydate;
					$this->data['gender'] = $gender;
					$this->data['classesID'] = $classesID;
					$this->data['sectionID'] = $sectionID;

					$queryArray = [];
					$this->getArray($queryArray, $this->input->post());


					$this->data['students'] = $this->studentrelation_m->general_get_order_by_student($queryArray);


					$retArray['render'] = $this->load->view('report/student/StudentReport', $this->data, true);
					$retArray['status'] = true;
					echo json_encode($retArray);
					exit;
				}
			} else {
				echo json_encode($retArray);
				exit;
			}
		} else {
			echo json_encode($retArray);
			exit;
		}
	}

	private function getArray(&$queryArray, $post)
	{
		$classesID 		= $post['classesID'];
		$sectionID 		= $post['sectionID'];
		$reportfor  	= $post['reportfor'];

		$schoolyearID = $this->session->userdata('defaultschoolyearID');
		$queryArray['srschoolyearID'] = $schoolyearID;

		if ($classesID > 0) {
			$queryArray['srclassesID'] = $classesID;
		}
		if ($sectionID != '' && $sectionID != '0') {
			$queryArray['srsectionID'] = $sectionID;
		}

		if (isset($post['reportfor']) && $post['reportfor'] == 'blood') {
			$queryArray['bloodgroup'] = $post['blood'];
			$this->data['reportTitle'] = $post['blood'];
		}

		if (isset($post['reportfor']) && $post['reportfor'] == 'country') {
			$queryArray['country'] = $post['country'];
			$this->data['reportTitle'] = $this->data['allcountry'][$post['country']];
		}

		if (isset($post['reportfor']) && $post['reportfor'] == 'gender') {
			$queryArray['sex'] = $post['gender'];
			$this->data['reportTitle'] = $post['gender'];
		}

		if (isset($post['reportfor']) && $post['reportfor'] == 'birthday') {
			$queryArray['dob'] = date('Y-m-d', strtotime((string) $post['birthdaydate']));
			$this->data['reportTitle'] = date('d F Y', strtotime((string) $post['birthdaydate']));
		}

		$this->data['classes'] 	= pluck($this->classes_m->general_get_classes(), 'obj', 'classesID');
		$this->data['sections'] = pluck($this->section_m->general_get_section(), 'obj', 'sectionID');
	}


	public function pdf()
	{
		if (permissionChecker('studentreport')) {
			$reportfor      = htmlentities((string) escapeString($this->uri->segment(3)));
			$bloodID        = htmlentities((string) escapeString($this->uri->segment(4)));
			$country        = htmlentities((string) escapeString($this->uri->segment(5)));
			$gender         = htmlentities((string) escapeString($this->uri->segment(6)));
			$birthdaydate   = htmlentities((string) escapeString($this->uri->segment(7)));
			$classesID      = htmlentities((string) escapeString($this->uri->segment(8)));
			$sectionID      = htmlentities((string) escapeString($this->uri->segment(9)));

			$this->data['reportfor'] = $reportfor;

			if (isset($bloodID)) {
				$this->data['blood'] = isset($this->_bloodArray[$bloodID]) ? $this->_bloodArray[$bloodID] : 8;
				$blood = $this->data['blood'];
			}

			$this->data['country'] = $country;
			$this->data['gender'] = $gender;
			$this->data['birthdaydate'] = date('Y-m-d', $birthdaydate);
			$this->data['classesID'] = $classesID;
			$this->data['sectionID'] = $sectionID;

			$reportforArray = array('blood', 'country', 'gender', 'birthday');

			if ((string) $reportfor && ((int) $blood || $blood >= 0) && ((int) $country || $country >= 0) && ((int) $gender || $gender >= 0) && ((int) $birthdaydate || $birthdaydate >= 0) && ((int) $classesID || $classesID >= 0) && ((int) $sectionID || $sectionID == NULL || $sectionID >= 0)) {
				if (in_array(strtolower($reportfor), $reportforArray)) {
					if ($bloodID <= 7) {
						$allCountry = $this->getAllCountry();
						$allCountry[0] = 'Select One';

						if (array_key_exists(strtoupper($country), $allCountry)) {
							if (isset($transport)) {
								$transportss = $this->transport_m->get_transport($transport);
							}

							if ($gender == 'Male' || $gender = 'Female' || $gender == 0) {
								if (isset($classesID)) {
									$classesIDs = $this->classes_m->general_get_single_classes(array('classesID' => $classesID));
								}

								if (customCompute($classesIDs) || $classesID == 0) {
									if (isset($sectionID)) {
										$sectionIDs = $this->section_m->general_get_single_section(array('sectionID' => $sectionID));
									}
									if (customCompute($sectionIDs) || $sectionID == '0' || $sectionID == NULL) {
										$queryArray = [];
										$this->getArray($queryArray, $this->data);

										$this->data['students'] = $this->studentrelation_m->general_get_order_by_student($queryArray);


										$this->reportPDF('studentreport.css', $this->data, 'report/student/StudentReportPDF');
									} else {
										$this->data["subview"] = "error";
										$this->load->view('_layout_main', $this->data);
									}
								} else {
									$this->data["subview"] = "error";
									$this->load->view('_layout_main', $this->data);
								}
							} else {
								$this->data["subview"] = "error";
								$this->load->view('_layout_main', $this->data);
							}
						} else {
							$this->data["subview"] = "error";
							$this->load->view('_layout_main', $this->data);
						}
					} else {
						$this->data["subview"] = "error";
						$this->load->view('_layout_main', $this->data);
					}
				} else {
					$this->data["subview"] = "error";
					$this->load->view('_layout_main', $this->data);
				}
			} else {
				$this->data["subview"] = "error";
				$this->load->view('_layout_main', $this->data);
			}
		} else {
			$this->data["subview"] = "error";
			$this->load->view('_layout_main', $this->data);
		}
	}

	private function uriChecker()
	{
		$totalUri = customCompute($this->uri->segment_array());
		if ($totalUri == 10 || $totalUri == 11) {
			return TRUE;
		}
		$this->errorHandeler();
	}

	private function errorHandeler($data = FALSE)
	{
		$this->data["subview"] = "error";
		$this->load->view('_layout_main', $this->data);
	}

	public function getSection()
	{
		$id = $this->input->post('id');
		if ((int)$id !== 0) {
			$allSection = $this->section_m->general_get_order_by_section(array('classesID' => $id));
			echo "<option value='0'>", $this->lang->line("studentreport_please_select"), "</option>";
			if (customCompute($allSection)) {
				foreach ($allSection as $value) {
					echo "<option value=\"$value->sectionID\">", $value->section, "</option>";
				}
			}
		}
	}

	public function send_pdf_to_mail()
	{
		$retArray = ['status' => FALSE, 'message' => ''];

		if (!permissionChecker('studentreport')) {
			$retArray['message'] = $this->lang->line('studentreport_permission');
			echo json_encode($retArray);
			return;
		}

		if (empty($_POST)) {
			$retArray['message'] = $this->lang->line('studentreport_permissionmethod');
			echo json_encode($retArray);
			return;
		}

		$to           = $this->input->post('to', TRUE);
		$subject      = $this->input->post('subject', TRUE);
		$message      = $this->input->post('message', TRUE);
		$reportfor    = $this->input->post('reportfor', TRUE);
		$bloodID      = $this->input->post('bloodID', TRUE);
		$country      = $this->input->post('country', TRUE);
		$birthdaydate = $this->input->post('birthdaydate', TRUE);
		$gender       = $this->input->post('gender', TRUE);
		$classesID    = $this->input->post('classesID', TRUE);
		$sectionID    = $this->input->post('sectionID', TRUE);

		$rules = $this->send_pdf_to_mail_rules($reportfor);
		$this->form_validation->set_rules($rules);

		if ($this->form_validation->run() === FALSE) {
			$retArray = $this->form_validation->error_array();
			$retArray['status'] = FALSE;
			echo json_encode($retArray);
			return;
		}

		$this->data['reportfor'] = $reportfor;
		$this->data['blood'] = $this->_bloodArray[$bloodID] ?? 8;
		$this->data['country'] = $country;
		$this->data['birthdaydate'] = $birthdaydate;
		$this->data['gender'] = $gender;
		$this->data['classesID'] = $classesID;
		$this->data['sectionID'] = $sectionID;

		if (!in_array(strtolower((string)$reportfor), ['blood', 'country', 'gender', 'birthday'])) {
			$retArray['message'] = $this->lang->line('studentreport_invalid_reportfor');
			echo json_encode($retArray);
			return;
		}

		if ($bloodID > 7) {
			$retArray['message'] = $this->lang->line('studentreport_invalid_blood');
			echo json_encode($retArray);
			return;
		}

		$allCountry = $this->getAllCountry();
		$allCountry[0] = 'Select One';

		if (!array_key_exists(strtoupper((string)$country), $allCountry)) {
			$retArray['message'] = $this->lang->line('studentreport_invalid_country');
			echo json_encode($retArray);
			return;
		}

		if (!in_array($gender, ['Male', 'Female', 0])) {
			$retArray['message'] = $this->lang->line('studentreport_permission');
			echo json_encode($retArray);
			return;
		}

		$classes = $this->classes_m->general_get_single_classes(['classesID' => $classesID]);
		if (!customCompute($classes) && $classesID != 0) {
			$retArray['message'] = $this->lang->line('studentreport_class_not_found');
			echo json_encode($retArray);
			return;
		}

		$section = $this->section_m->general_get_single_section(['sectionID' => $sectionID]);
		if (!customCompute($section) && $sectionID != '0' && $sectionID !== NULL) {
			$retArray['message'] = $this->lang->line('studentreport_section_not_found');
			echo json_encode($retArray);
			return;
		}

		$queryArray = [];
		$this->getArray($queryArray, $this->data);
		$this->data['students'] = $this->studentrelation_m->general_get_order_by_student($queryArray);

		$this->reportSendToMail('studentreport.css', $this->data, 'report/student/StudentReportPDF', $to, $subject, $message);

		$retArray['status'] = TRUE;
		echo json_encode($retArray);
	}
}
