<?php
defined($security_key) or exit;

//------------------------------------------
// contracts_billing
//------------------------------------------

//NEW ARRAY
$criterias = [];   
//ADD DEFAULT VALUES TO STRING
$GET_VALUES = 'status=1&p=all';  //STATUS = ACTIVE

//Check for $_GET variables and build up GET VALUES
if(isset($get_content) && $get_content!=''){    
    //GET VARIABLES FROM URL
    $requests = explode("&", $get_content);     
    //Check for keys and values
    foreach ($requests as $y){
        $v = explode("=", $y);
        //INCLUDE VARIABLES IN ARRAY
        $criterias[$v[0]] = $v[1];  
        if ($v[0] == 'p' || $v[0] == 'page' || $v[0] =='totals' || $v[0] =='list' || $v[0] =='history' || $v[0] =='success_msg' || $v[0] =='year' || $v[0] =='month'){
        //do nothing
        } 
        else{
            //exclude empty values
            if ($v[1] != '' || !empty($v[1]))
            $GET_VALUES .= '&'.$v[0].'='.$v[1]; 
        }
    }
} 

//SET DEFAULT VALUES
$ye = ((isset($criterias['year']) && $criterias['year'] !='' )? $criterias['year'] : $curYear);
$mo = ((isset($criterias['month']) && $criterias['month'] !='')? $criterias['month'] : $curMonth);
$qu = ((isset($criterias['month']) ? (int)ceil($mo / 3): $curQuarter));
$da = $ye.'-'.$mo.'-'.date("d");

//CALL TO API TO GET ALL ACTIVE CONTRACTS
$api_url = '/v2/contracts/'.$GET_VALUES;
$responses = ioAPIv2($api_url,'',$user_data['userkey']);

//Decode Payload
if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = null;}
$output = [];

foreach ($responses as $response){    
    //CALCULATE CONTRACT END DATE
    $date = date('Y-m-d', strtotime('+'.$response['duration'].' months', strtotime($response['start_date'])));
    
    //CHECK IF SEARCH CRITERIA YEAR, QUARTER, MONTH FALL IN CONTRACT PERIOD
    $inrange = dateInRange($response['start_date'], $date, $da) ?? 0;
    
    if ($inrange == 1){
        $servicetools = json_decode($response['servicetool'] ?? '',true) ?? ''; 
        $ignore_lists = json_decode($response['ignore_list'] ?? '',true) ?? ''; 
    
        //get all assigned serialnumbers
        $url_input = '';
        foreach($servicetools as $service_tool){
            $url_input .= $service_tool.',';
        }
        //get ignore list
        $ignored_serialnumbers = '';
        if (!empty($ignore_lists)){ 
            foreach($ignore_lists as $list){
                $ignored_serialnumbers .= $list.',';
            }
            $ignored_serialnumbers = '&ignore='.substr($ignored_serialnumbers,0,-1);
        }

        //Return report_usage_servicereports
        $api_url = '/v2/application/type=ServiceReport&serialnumber='.substr($url_input,0,-1).$ignored_serialnumbers.'&between='.$response['start_date'].'||'.$date.'/contract_usage_servicereports';
        $contract_usage_servicereports = ioAPIv2($api_url,'',$user_data['userkey']);
        
        //Decode Payload
        if (!empty($contract_usage_servicereports)){$contract_usage_servicereports = json_decode($contract_usage_servicereports,true);}else{$contract_usage_servicereports = null;}

        $usage_billing = usageBilling($contract_usage_servicereports);

        //Initial billing_run value
        $billing_run = 0;
        $period = 'n/a';
        
        switch ($response['billing_plan']) {
        case 1:
            # month
            //CONVERT KEY TO MONTH NAME
            $monthObj   = DateTime::createFromFormat('!m', $mo);   
            $period = $monthObj->format('F');

            if (isset($usage_billing[$ye]['quarters'][$qu]['months'][$mo])){
                $billing_run =  $usage_billing[$ye]['quarters'][$qu]['months'][$mo];     
            }
            break;
        case 2:
            # quarter
            $period = 'Q'.$qu;

            if (isset($usage_billing[$ye]['quarters'][$qu]['total'])){
                $billing_run = $usage_billing[$ye]['quarters'][$qu]['total'];
            }
            break;
        case 3:
            # year
            $period = $ye;

            if (isset($usage_billing[$ye]['total'])){
                $billing_run =  $usage_billing[$ye]['total'];
            }
            break;      
        }

        //Variable translation
        $status = 'contract_status' . $response['status'];
        $type = 'contract_type'.$response['type'];
        $contract_billingplan_text = 'contract_billing'.$response['billing_plan'] ?? '';
        //calculate enddate from duration
        $date = date('Y-m-d', strtotime('+'.$response['duration'].' months', strtotime($response['start_date'])));
        
        //GetPartnerDetails
        $partner_data = json_decode($response['accounthierarchy'],true);

        //SHOW USAGE PERCENTAGE
        $usage_service_count = ($response['service_count'] > 0) ? $response['service_count']:1;
        $usage_percentage = ($billing_run != 0) ? round((($billing_run/$usage_service_count)*100),2) : 0;                    
        $usage_per_status = ($usage_percentage < 100) ? 'enabled' : 'disabled';

        $output[] = array(
            "#" => $response['rowID'] ,
            "Status" => $$status,
            "Account" => $partner_data['soldto'],
            "Type" => $$type,
            "Billingplan" =>$$contract_billingplan_text,
            "Start date" =>$response['start_date'],
            "End date" => $date,
            "Reference" =>$response['reference'],
            "Consumed" =>$billing_run,
            "Contracted" =>$response['service_count'],
            "Deviation" => $usage_percentage,
            "Snapshot_date" => $da,
            "Period" => $period

        );   
    }
}

$total = count( $output );

//SEND TOTALS WHEN REQUESTED
if(isset($criterias['totals']) && $criterias['totals'] ==''){
    
    $messages = json_encode($total, JSON_UNESCAPED_UNICODE);
} 
else {
    
    //------------------------------------------
    //Paging
    //------------------------------------------
    $current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
    $offset = ($current_page - 1) * $page_rows_contracts;
    $output = array_slice( $output, $offset, $page_rows_contracts );
    
    //------------------------------------------
    //JSON_ENCODE
    //------------------------------------------
    $messages = json_encode($output, JSON_UNESCAPED_UNICODE);
}

//Send results
echo $messages;
?>