<?php
	require_once '../../../autoload.php';

	require( '../../GetDataFromDB.php' );
	

	$toProcess = true;

	$description 	= '';

	if ( isset ($_GET ['description'] ) )  		$description 	= $_GET['description'];

	$draw			= $_GET ['draw'];
	$start			= $_GET ['start'];
	$length			= $_GET ['length'];

	$columns 		= $_GET ['columns'];
	$order			= $_GET ['order'];
	$orderCol		= $order [0]['column'];
	$orderDir		= $order [0]['dir'];
	$orderColName	= $columns [$orderCol]['data'];
	$orderby		= " ORDER BY ".$orderColName." ".$orderDir;

	$limit = '';

	$to_add 	= '';
	$to_remove	= '';
	$to_add_str = '';

	if ( isset($_GET['to_add']) )
	{
     	$to_add = $_GET['to_add'];
     	$to_add = json_decode($to_add);
     	$add1 = array_map(function($item) {
    		return "'" . $item . "'";
		}, $to_add);

		$to_add_str = implode(',', $add1);
    }


    if ( isset($_GET['to_remove']) )
	{
     	$to_remove = $_GET['to_remove'];
     	$to_remove = json_decode($to_remove);
     	$remove1 = array_map(function($item) {
    		return "'" . $item . "'";
		}, $to_remove);

		$to_remove_str = implode(',', $remove1);
    }

    $modalitytitle = "";
    if ( isset($_GET['modalitytitle']) )
     	$modalitytitle = $_GET['modalitytitle'];

     $description_fr = "";
    if ( isset($_GET['description_fr']) )
     	$description_fr = $_GET['description_fr'];

     $rdescription = "";
    if ( isset($_GET['rdescription']) )
     	$rdescription = $_GET['rdescription'];


	if ( isset($_GET['start']) && $_GET['length'] != -1 )
	{
		$limit = " OFFSET ".intval($_GET['start'])." LIMIT ".intval($_GET['length']);
	}

	$desc_id = -1;
	if ( isset ( $_GET['desc_id'] ) )	$desc_id = $_GET['desc_id'];

	error_log ( "to_add : " .$to_add_str );
	error_log ( "to_remove : " .$to_remove_str );

	$description_filter = ( $description_fr != "" )? "description_fr ilike '%{$description_fr}%'" : "(description_fr is null or description_fr ilike '%{$description_fr}%')" ;

	$rdescription_filter = ( $rdescription != "" )? "rdescription ilike '%{$rdescription}%'" : "(rdescription is null or rdescription ilike '%{$rdescription}%')" ;

  	if ( $_GET['linked'] == '1' )
  	{
  		error_log ( "Linked." );
		$psql = "with t1 as (
				select distinct lrserid as rserd_id,modalitytitle,description_fr,mdescription,rdescription,mserd_id, alldata.desc_id from(
  select string_agg(rsd.rserd_id::text,',') over (PARTITION by m2.modalitytitle,rsd.mserd_id,rsd.description) as lrserid,
  case when msd.desc_id is null then msd.description else '['||msd.description||']' end as mdescription,
  m2.modalitytitle,rsd.rserd_id,rsd.description as rdescription,rsd.mserd_id,coalesce(rsd.desc_id,msd.desc_id) as desc_id
  from modality_identity mi, modality m2,(select distinct rserd_id,selected from raw_serie_description_link where selected = true) rsdl, raw_serie_description as rsd left join master_serie_description as msd on rsd.mserd_id = msd.mserd_id
  where rsdl.rserd_id = rsd.rserd_id and rsd.description != '' and mi.mod_id = m2.mod_id and mi.modident_id = rsd.modident_id
  ) as alldata left join description_afcn on description_afcn.desc_id = alldata.desc_id)
				select 0 as newrow, * from t1
					where
						{$description_filter} and
						{$rdescription_filter} and
						modalitytitle ilike'%{$modalitytitle}%' and
						t1.desc_id={$desc_id}";

		if ( $to_remove_str != "" )
			$psql .= " and 	t1.rserd_id not in ({$to_remove_str})";

		if ( $to_add_str != "" )
		{
			error_log ( "Add union...");
			$psql .= " union select 1 as newrow, * from t1 where {$rdescription_filter} and {$description_filter} and modalitytitle ilike'%{$modalitytitle}%' and t1.rserd_id in ({$to_add_str})";
		}

		error_log ( "Full request : " .$psql );
	}
	else
	{
		error_log ( "Not linked." );



  		$psql = "with t1 as (
				select distinct lrserid as rserd_id,modalitytitle,description_fr,mdescription,rdescription,mserd_id, alldata.desc_id from(
  select string_agg(rsd.rserd_id::text,',') over (PARTITION by m2.modalitytitle,rsd.mserd_id,rsd.description) as lrserid,
  case when msd.desc_id is null then msd.description else '['||msd.description||']' end as mdescription,
  m2.modalitytitle,rsd.rserd_id,rsd.description as rdescription,rsd.mserd_id,coalesce(rsd.desc_id,msd.desc_id) as desc_id
  from modality_identity mi, modality m2,(select distinct rserd_id,selected from raw_serie_description_link where selected = true) rsdl, raw_serie_description as rsd left join master_serie_description as msd on rsd.mserd_id = msd.mserd_id
  where rsdl.rserd_id = rsd.rserd_id and rsd.description != '' and mi.mod_id = m2.mod_id and mi.modident_id = rsd.modident_id
  ) as alldata left join description_afcn on description_afcn.desc_id = alldata.desc_id)
				select 0 as newrow, * from t1 where {$rdescription_filter} and {$description_filter} and modalitytitle ilike'%{$modalitytitle}%' and (t1.desc_id is null or t1.desc_id !=  {$desc_id})";

		if ( $to_add_str != "" )
			$psql .= " and 	t1.rserd_id not in ({$to_add_str})";

		if ( $to_remove_str != "" )
		{
			$psql .= " union select 1 as newrow, * from t1 where {$rdescription_filter} and {$description_filter} and modalitytitle ilike'%{$modalitytitle}%' and t1.rserd_id in ({$to_remove_str})";
		}
	}



		$recordsTotal 		= 1000;
		$recordsFiltered	= 0;

		$data				= Array ();

		if ( $toProcess == true )
				$data = GetDataFromDB ( $psql, $recordsFiltered, $limit, $orderby );

		$arr = array (
				"draw"            => intval( $draw ),
				"recordsTotal"    => intval( $recordsTotal ),
				"recordsFiltered" => intval( $recordsFiltered ),
				"data"            => $data,
				"sql"			  => $psql.$orderby.$limit
			);

		$result = json_encode ( $arr );

		echo $result;

?>





