<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: capp
 * Date: 29/05/2018
 * Time: 15:49
 */


class Nano_health_model extends CI_Model
{

	public function createConfig($id_network){
		$this->db->insert('nh_networks_configs', ['network_id' => $id_network]);
		return $this->db->insert_id();
	}

	public function getConfig($id_network){
		return $this->db->get_where('nh_networks_configs',['network_id'=> $id_network]);
	}

	public function updateConfig($configId, $data){
		$this->db->where('id', $configId);
//		$data = formatDBData($data);
		return $this->db->update('nh_networks_configs', $data);
	}

	public function getConfigYearsPricesGrid($configId){
		return $this->db->get_where('nh_years_prices_grid',['nh_network_config_id'=> $configId]);
	}

	public function getConfigMonthsPricesGrid($configId){
		return $this->db->order_by('id','ASC')->get_where('nh_months_prices_grid',['nh_network_config_id'=> $configId]);
	}

	public function getConfigActs($configId){
		return $this->db->get_where('nh_acts',['nh_network_config_id'=> $configId]);
	}

	// Classes de prestataires
	public function getProviderClasses($configId)
	{
		return $this->db->get_where('nh_provider_classes',['nh_network_config_id'=> $configId]);
	}

	public function getInfosInsuranceSubscriptionById($insuranceSubscriptionId){
		return $this->db->select('s.*, pg.payment_period , pg.number_of_fractions')
				->from('nh_infos_insurances_subscriptions s')->join('nh_months_prices_grid pg', 'pg.id = s.months_grid_id')
			    ->where('s.insurance_subscription_id',$insuranceSubscriptionId)->get()->row();
	}

	public function getNhValidatingAgentSubscriptionHistory($agentId , $state){
		return $this->db->from('nh_insurances_subscriptions_history')->where('nh_validating_agent_id',  $agentId)
			->where('insurance_subscription_state', $state)->count_all_results();
	}

	public function getNhInsurancesSubscriptionCount($networkId, $state){
		return $this->db->from('nh_insurances_subscriptions')->where('network_id', $networkId)
			->where('state', $state)->count_all_results();
	}

	public function getInfosInsuredById($insuredId){
		return $this->db->get_where('nh_infos_insurances',['insured_id'=> $insuredId])->first_row();
	}

	public function getInsurancePaymentTransactions($insuredId){
		return $this->db->select('p.* , in.invoice_id')
			->from('nh_insurances_payments p')->join('nh_insurances_invoices in', 'in.id = p.invoice_id')
			->where('in.insurance_id',$insuredId)->order_by('p.created_at','desc')->get();
	}

	public function getInsuranceInvoices($insuredId , $state =  null){
		$query = $this->db->select('i.* , is.insurance_subscription_id, SUM(p.amount) as paid_amount')
			->from('nh_insurances_invoices i')->join('nh_insurances in', 'in.id = i.insurance_id')
			->join('nh_insurances_subscriptions is', 'is.id = i.subscription_id','left')
			->join('nh_insurances_payments p', 'i.id = p.invoice_id','left')
			->where('in.insured_id',$insuredId);
		if(!empty($state)){
			$query =$query->where('i.state',$state);
		}

		return  $query->group_by('i.id')->order_by('i.created_at','desc')->get();
	}

	public function getInsuranceInvoiceTotalPaidAmount($insuredId){
		 $amount = $this->db->select('SUM(p.amount) as total_paid_amount')
			->from('nh_insurances_invoices i')->join('nh_insurances in', 'in.id = i.insurance_id')
			->join('nh_insurances_payments p', 'i.id = p.invoice_id')
			->where('i.insurance_id',$insuredId)->group_by('i.id')->get()->row_array();

		return isset($amount) ? $amount['total_paid_amount'] : 0;
	}

	public function getInsuranceInvoiceTotalAmount($insuredId){
		$amount = $this->db->select('SUM(i.amount) as total_amount')
			->from('nh_insurances_invoices i')->join('nh_insurances in', 'in.id = i.insurance_id')
			->where('i.insurance_id',$insuredId)->group_by('i.id')->get()->row_array();
		return isset($amount) ? $amount['total_amount'] : 0;
	}

	public function getSubscriptionBeneficiaries($subscriptionId){
		return  $this->db->select('b.*')
			->from('nh_having_rights b')->join('nh_insurances_having_rights i', 'b.id = i.having_right_id')
			->where('i.deleted_at IS NULL')
			->where('i.insurance_subscription_id',$subscriptionId)->order_by('i.created_at','asc')->get();
	}

	public function getInsuranceBeneficiaries($insuranceId){
		return  $this->db->select('b.*')
			->from('nh_having_rights b')->join('nh_insurances_having_rights i', 'b.id = i.having_right_id')
			->where('i.deleted_at IS NULL')
			->where('i.insurance_id',$insuranceId)->order_by('i.created_at','asc')->get();
	}

	public function getInfosHealthCareSheetById($healthCareSheetId){
		return $this->db->get_where('nh_infos_health_care_sheets',['health_care_sheet_id'=> $healthCareSheetId])->first_row();
	}

	public function getHealthCareSheetPerformances($healthCareSheetId){
		return  $this->db->select('p.* , a.code as act_code , a.name as act_name')
			->from('nh_performances p')->join('nh_health_care_sheets_performances sp', 'p.id = sp.performance_id')
			->join('nh_acts a', 'a.id = p.act_id')
			->where('sp.sheet_id',$healthCareSheetId)->order_by('sp.created_at','asc')->get();
	}

	public function getHealthCareSheetExams($healthCareSheetId){
		return  $this->db->select('e.* , a.code as act_code , a.name as act_name , a.unit_value as act_unit_value')
			->from('nh_exams e')->join('nh_health_care_sheets_exams se', 'e.id = se.exam_id')
			->join('nh_acts a', 'a.id = e.act_id')
			->where('se.sheet_id',$healthCareSheetId)->order_by('se.created_at','asc')->get();
	}

	public function getHealthCareSheetPrescriptions($healthCareSheetId){
		return  $this->db->select('p.* , d.code as drug_or_device_code , d.name as drug_or_device_name')
			->from('nh_medical_prescriptions p')->join('nh_health_care_sheets_prescriptions sp', 'p.id = sp.prescription_id')
			->join('nh_drugs_and_devices d', 'd.id = p.drug_or_device_id')
			->where('sp.sheet_id',$healthCareSheetId)->order_by('sp.created_at','asc')->get();
	}

	public function getDrugAndDevices($networkId)
	{
		return $this->db->get_where('nh_drugs_and_devices',['network_id'=> $networkId]);
	}

	public function calculateSheetAmountsParts($healthCareSheetId , $healthCareSheetType){
		$insurerAmount = 0;
		$insuredAmount = 0;

		if ($healthCareSheetType == 'CONSULTATION') {
			$query = $this->db->query("SELECT SUM(moderator_ticket) as moderator_ticket , SUM(insurance_amount) as insurance_amount FROM nh_performances p INNER JOIN
    nh_health_care_sheets_performances hp ON p.id = hp.performance_id WHERE hp.sheet_id = $healthCareSheetId LIMIT 1");
			if ($query->num_rows() > 0) {
				$insuredAmount += $query->first_row()->moderator_ticket;
				$insurerAmount += $query->first_row()->insurance_amount;
			}
		} else {
			$query = $this->db->query("SELECT SUM(insured_paid_amount) as insured_paid_amount , SUM(insurer_paid_amount) as insurer_paid_amount FROM nh_medical_prescriptions p INNER JOIN
    nh_health_care_sheets_prescriptions hp ON p.id = hp.prescription_id WHERE hp.sheet_id = $healthCareSheetId LIMIT 1");
			if ($query->num_rows() > 0) {
				$insuredAmount += $query->first_row()->insured_paid_amount;
				$insurerAmount += $query->first_row()->insurer_paid_amount;
			}

			$query = $this->db->query("SELECT SUM(insured_paid_amount) as insured_paid_amount , SUM(insurer_paid_amount) as insurer_paid_amount FROM nh_exams e INNER JOIN
    nh_health_care_sheets_exams he ON e.id = he.exam_id WHERE he.sheet_id = $healthCareSheetId LIMIT 1");
			if ($query->num_rows() > 0) {
				$insuredAmount += $query->first_row()->insured_paid_amount;
				$insurerAmount += $query->first_row()->insurer_paid_amount;
			}
		}

		return [$insuredAmount, $insurerAmount];
	}

	public function getCountCareRequests($network_id , $validating_agent_id, $state){
		$query = $this->db->from('nh_infos_authorization_of_care_requests')->where('state',$state);
		if(!empty($validating_agent_id)){
			$query = $query->where('validating_agent_id', $validating_agent_id);
		}

		if(!empty($network_id)){
			$query = $query->where('network_id', $network_id);
		}
		return $query->count_all_results();
	}

	public function getBeneficiariesDeletionHistory($insuranceId){
		return  $this->db->select('b.* , i.deleted_at')
			->from('nh_having_rights b')->join('nh_insurances_having_rights i', 'b.id = i.having_right_id')
			->where('i.deleted_at IS NOT NULL')
			->where('i.insurance_id',$insuranceId)->order_by('i.deleted_at','desc')->get();
	}

	public function getInfosInvoiceById($id){
		return $this->db->get_where('nh_infos_invoices',['id'=> $id])->first_row();
	}

	public function getCountInvoices($network_id , $validating_agent_id, $state){
		$query = $this->db->from('nh_infos_invoices')->where('state',$state);
		if(!empty($validating_agent_id)){
			$query = $query->where('validating_agent_id', $validating_agent_id);
		}

		if(!empty($network_id)){
			$query = $query->where('network_id', $network_id);
		}
		return $query->count_all_results();
	}

	public function getExclusion($id_network){
		return $this->db->get_where('nh_exclusions',['network_id'=> $id_network]);
	}
}
