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

class ControllerDoctor extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('nano_health_model');
	}

	public function index()
	{
		if ($this->isLogged()){
			$data['active'] = "dashboard";
			$data['network_id'] = $data['id_network'] = $this->session->userdata('network_id');

			if ($this->input->get('history')) {
				$history_type = $this->input->get('history');
				$id = $this->input->get('id');
				if($history_type == 'invoices' && !empty($id)){
					$data['active'] = "invoices";
					$data['invoice'] = $this->nano_health_model->getInfosInvoiceById($id);
					$data['agent'] = $this->db->get_where('agent_plus',['code_membre'=> $data['invoice']->institution_code ?? null])->first_row();
					$data['health_care_sheets'] = $this->db->get_where('nh_infos_health_care_sheets',['invoice_id'=> $id]);
					$this->load->view('nano_health/controller_doctor/header', $data);
					$this->load->view('nano_health/controller_doctor/infos_invoice', $data);
					$this->load->view('footer');
				}else{
					$this->historique($this->input->get('d'), $this->input->get('f'), $this->input->get('history'), $data);
				}
			}else{

				$data['count_accepted'] = $this->nano_health_model->getCountInvoices(null,$this->session->userdata('agent_id'), 'ACCEPTED');
				$data['count_accepted_modified'] = $this->nano_health_model->getCountInvoices(null, $this->session->userdata('agent_id'), 'ACCEPTED_MODIFIED');
				$data['count_rejected'] = $this->nano_health_model->getCountInvoices(null,$this->session->userdata('agent_id'), 'REJECTED');
				$data['count_under_validation'] = $this->nano_health_model->getCountInvoices($data['network_id'],null, 'UNDER_VALIDATION');

				$this->load->view('nano_health/controller_doctor/header', $data);
				$this->load->view('nano_health/controller_doctor/dashboard', $data);
				$this->load->view('footer');
			}
		}

	}

	private function historique($startDate, $endDate,$type , $data)
	{

		$format = $this->session->userdata('site_lang') === 'french' ? 'd-m-Y' : 'Y-m-d';
		$data['startDate'] = $startDate ? date($format, strtotime($startDate)) : null;
		$data['endDate'] = $endDate ? date($format, strtotime($endDate)) : null;
		$endDate = Date('Y-m-d', strtotime($endDate . "+1 day"));

		if ($type == 'invoices')
			$data['active'] = 'invoices';

		$this->load->view('nano_health/controller_doctor/header', $data);
		if ($type == 'invoices')
			$this->load->view('nano_health/controller_doctor/invoices');
		$this->load->view('footer');
	}

	private function isLogged()
	{
		if (!$this->session->userdata('email')) {
			$this->session->set_flashdata('error', 'log in first');

			$data['alert'] = "ok";
			$data['message'] = "Login first!";

			redirect('index.php', $data);
			return false;
		}
		return true;
	}
}
