<?php
defined(page_security_key) or exit;

if (debug && debug_id == $_SESSION['id']){
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);  
}
include_once './assets/functions.php';
include_once './settings/settings_redirector.php';

//SET ORIGIN FOR NAVIGATION
$prev_page = $_SESSION['prev_origin'] ?? '';
$page = 'contract';

//create backbutton to prev_origin
$back_btn_orgin =  ($prev_page != '')? '<a href="'.$prev_page.'" class="btn alt mar-right-2">'.$button_back.'</a>':'';

//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
    header('location: index.php');
    exit;
}

//GET PARAMETERS && STORE in SESSION for FURTHER USE/NAVIGATION
$pagination_page = $_SESSION['p'] = isset($_GET['p']) ? $_GET['p'] : 1;

//PAGE Security
$page_manage = 'contract_manage';
$update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U');
$update_allowed_edit = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'U');
$delete_allowed = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'D');
$create_allowed = isAllowed($page_manage ,$_SESSION['profile'],$_SESSION['permission'],'C');
$view_equipment =  isAllowed('equipment' ,$_SESSION['profile'],$_SESSION['permission'],'R');

//GET Details from URL
$GET_VALUES = urlGETdetails($_GET) ?? '';
$contract_ID = $_GET['rowID'] ?? '';

//CALL TO API FOR General information
$api_url = '/v1/contracts/rowID='.$contract_ID;;
$responses = ioServer($api_url,'');
//Decode Payload
if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;}
$responses = $responses[0];

//------------------------------
//Variables
//------------------------------
$contract_status_text = 'contract_status'.$responses->status ?? '';
$contract_type_text = 'contract_type'.$responses->type ?? '';
$contract_billingplan_text = 'contract_billing'.$responses->billing_plan ?? '';

$servicetools = json_decode($responses->servicetool,true) ?? ''; 
$assigned_users = json_decode($responses->assigned_users,true) ?? ''; 
$ignore_lists = json_decode($responses->ignore_list,true) ?? ''; 

//Partnerdata
$partner_data = json_decode($responses->accounthierarchy);
$salesid = getPartnerName($partner_data->salesid) ?? $not_specified;
$soldto = getPartnerName($partner_data->soldto) ?? '-';
$shipto = getPartnerName($partner_data->shipto) ?? '-';
$location = getPartnerName($partner_data->location) ?? '-';

// Handle success messages
if (isset($_GET['success_msg'])) {
    if ($_GET['success_msg'] == 1) {
        $success_msg = $message_contract_1;
    }
    if ($_GET['success_msg'] == 2) {
        $success_msg = $message_contract_2;
    }
    if ($_GET['success_msg'] == 3) {
        $success_msg = $message_contract_3;
    }
}

template_header('Contract', 'contract', 'view');
$view = '
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.$responses->rowID.'</h2>
        <a href="index.php?page='.$_SESSION['origin'].'&p='.$_SESSION['p'].'" class="btn alt mar-right-2">'.$button_cancel.'</a>
';


//------------------------------------
//
//------------------------------------
if ($update_allowed_edit === 1){
    $view .= '<a href="index.php?page=contract_manage&rowID='.$_GET['rowID'].'" class="btn">Edit</a>';
}

$view .= '</div>';

if (isset($success_msg)){
    $view .= ' <div class="msg success">
                    <i class="fas fa-check-circle"></i>
                    <p>'.$success_msg.'</p>
                    <i class="fas fa-times"></i>
                </div>';
}

$view .= '<div class="content-block-wrapper">';

$view .= '  <div class="content-block order-details">
                <div class="block-header">
                <i class="fa-solid fa-circle-info"></i></i>'.($product_data ?? '').'
                </div>
                <div class="order-detail">
                    <h3>'.$contract_id.'</h3>
                    <p>'.$responses->rowID.'</p>
                </div>
                <div class="order-detail">
                    <h3>'.$contract_status.'</h3>
                    <p>'.(($responses->status == 1)? '<span class="status enabled">': (($responses->status == 3) ? '<span class="status disabled">': '<span class="status">')).''.$$contract_status_text.'</span></p>
                </div>
                <div class="order-detail">
                    <h3>'.$contract_type.'</h3>
                    <p><span class="status id'.$responses->type.'">'.$$contract_type_text.'</span></p>
                </div>
                 <div class="order-detail">
                    <h3>'.$contract_billinglabel.'</h3>
                    <p><span class="status id'.$responses->billing_plan.'">'.($$contract_billingplan_text ?? '').'</span></p>
                </div>
                <div class="order-detail">
                    <h3>'.$contract_start_date.'</h3>
                    <p>'.$responses->start_date.'</p>
                </div>
                <div class="order-detail">
                    <h3>'.$contract_duration.'</h3>
                     <p>'.$responses->duration.'</p>
                </div>
            '; 
            if ($responses->duration !='' && $responses->start_date !=''){
                $date = date('Y-m-d', strtotime('+'.$responses->duration.' months', strtotime($responses->start_date)));
            
                $view .= '
                <div class="order-detail">
                    <h3>'.$contract_end_date.'</h3>
                    <p>'.$date.'</p>
                </div>
                 <div class="order-detail">
                    <h3>'.$contract_service.'</h3>
                    <p>'.$responses->service_count.'</p>
                </div>
                ';

            }
   
$view .='                
            </div>
';

$view .='<div class="content-block order-details">
            <div class="block-header">
                <i class="fa-solid fa-user fa-sm"></i>'.$view_asset_partners.'
            </div>
            <div class="order-detail">
                    <h3>'.$general_salesid.'</h3>
                    <p>'.$salesid.'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$general_soldto.'</h3>
                    <p>'.$soldto.'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$general_shipto.'</h3>
                    <p>'.$shipto.'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$general_location.'</h3>
                    <p>'.$location.'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$contract_reference.'</h3>
                     <p>'.$responses->reference.'</p>
            </div>

        </div>';
$view .= '</div>';

//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 = '/v1/application/type=ServiceReport&serialnumber='.substr($url_input,0,-1).$ignored_serialnumbers.'&between='.$responses->start_date.'||'.$date.'/contract_usage_servicereports';
$contract_usage_servicereports = ioServer($api_url,'');

//Decode Payload
if (!empty($contract_usage_servicereports)){$contract_usage_servicereports = decode_payload($contract_usage_servicereports);}else{$contract_usage_servicereports = null;}

$contract_usage_servicereports = json_decode(json_encode($contract_usage_servicereports),true);

$service_events = usageView($contract_usage_servicereports);

$view .= '<div class="content-block">
            <div class="block-header">
                <i class="fa-solid fa-bars fa-sm"></i>'.$menu_service_reports.'
            </div>
             <div class="table order-table">
            '.$service_events.'
            </div>
        </div>
    ';

$usage_billing = usageBilling($contract_usage_servicereports);

$view .= '<div class="content-block">
    <div class="block-header">
        <i class="fa-solid fa-bars fa-sm"></i>'.$contract_billinglabel.'
    </div>
    <div class="table order-table">
        <table>
            <head>
                <tr>
                    <th>'.$general_year.'</th>
                    <th>'.$general_total.'</th>
                    <th '.(($responses->billing_plan && $responses->billing_plan == 2) ? '' :'style="display:none;"').'>'.$general_quarter.'</th>
                    <th '.(($responses->billing_plan && $responses->billing_plan == 2) ? '' :'style="display:none;"').'>'.$general_total.'</th>
                    <th '.(($responses->billing_plan && $responses->billing_plan == 1) ? '' :'style="display:none;"').'>'.$general_month.'</th>
                    <th '.(($responses->billing_plan && $responses->billing_plan == 1) ? '' :'style="display:none;"').'>'.$general_total.'</th>
                </tr>
            </head>
            <tbody>';

            foreach($usage_billing as $key => $value){
                $view .= ' 
                <tr>
                    <td>'.$key.'</td>
                    <td>'.$value['total'].'</td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
                ';
                foreach ($value['quarters'] as $key => $value){
                        $view .= ' 
                        <tr '.(($responses->billing_plan && $responses->billing_plan == 2) ? '' :'style="display:none;"').'>
                            <td></td>
                            <td></td>
                            <td>'.$key.'</td>
                            <td>'.$value['total'].'</td>
                            <td '.(($responses->billing_plan && $responses->billing_plan == 1) ? '' :'style="display:none;"').'></td>
                            <td '.(($responses->billing_plan && $responses->billing_plan == 1) ? '' :'style="display:none;"').'></td>
                        </tr>
                        ';
                    
                    foreach($value['months'] as $key => $value){
                        //CONVERT KEY TO MONTH NAME
                        $monthObj   = DateTime::createFromFormat('!m', $key);
                        $key = $monthObj->format('F');

                        $view .= ' 
                        <tr '.(($responses->billing_plan && $responses->billing_plan == 1) ? '' :'style="display:none;"').'>
                            <td></td>
                            <td></td>
                            <td '.(($responses->billing_plan && $responses->billing_plan == 2) ? '' :'style="display:none;"').'></td>
                            <td '.(($responses->billing_plan && $responses->billing_plan == 2) ? '' :'style="display:none;"').'></td>
                            <td '.(($responses->billing_plan && $responses->billing_plan == 1) ? '' :'style="display:none;"').'>'.$key.'</td>
                            <td '.(($responses->billing_plan && $responses->billing_plan == 1) ? '' :'style="display:none;"').'>'.$value.'</td>
                        </tr>
                        ';
                    }
                }
            }

$view .= '</tbody>
        </table>
    </div>
</div>
';

$view .= '<div class="content-block">
            <div class="block-header">
                <i class="fa-solid fa-bars fa-sm"></i>'.$contract_assigned_users.'
            </div>
             <div class="table order-table">
             <table class="sortable">
             <tbody>';
            //Check for assigned users                      
            foreach ($assigned_users as $user){
                $view .=  '<tr><td>'.$user.'</td><tr>';
                }
$view .= ' 
                    </tbody>
                </table>
            </div>
        </div>
    ';

   
$view .= '<div class="content-block">
    <div class="block-header">
        <i class="fa-solid fa-bars fa-sm"></i>'. $contract_servicetool.'
    </div>
    <div class="table order-table">
             <table class="sortable">
             <tbody>';
            //Check for assigned tools
            foreach ($servicetools as $tools){
                $view .=  '<tr><td>'.(($view_equipment == 1)? '<a href="index.php?page=equipment&serialnumber='.$tools.'" class="btn2">'.$tools.'</a>':$tools).'</td><tr>';
                }
$view .= ' 
                    </tbody>
                </table>
    </div>
</div>
';

$view .= '<div class="content-block">
    <div class="block-header">
        <i class="fa-solid fa-bars fa-sm"></i>'. $contract_ignore_serial.'
    </div>
    <div class="table order-table">
             <table class="sortable">
             <tbody>';
            //Check for ignore list
            foreach ($ignore_lists as $list){
                $view .=  '<tr><td>'.(($view_equipment == 1)? '<a href="index.php?page=equipment&serialnumber='.$list.'" style="text-decoration:none;color: inherit;">'.$list.'</a>':$list).'</td><tr>';

                }
$view .= ' 
                    </tbody>
                </table>
    </div>
</div>
';

$view .= '<div class="content-block">
    <div class="block-header">
        <i class="fa-solid fa-bars fa-sm"></i>'.$tab3.'
    </div>
    <div class="table order-table">
        <table>
            <tr>
                <td style="width:25%;">'.$general_created.'</td>
                <td>'.getRelativeTime($responses->created).'</td>
            </tr>
            <tr>
                <td style="width:25%;">'.$general_createdby.'</td>
                <td>'.$responses->createdby.'</td>
            </tr>
            <tr>
                <td style="width:25%;">'.$general_updated.'</td>
                <td>'.getRelativeTime($responses->updated).'</td>
            </tr>
            <tr>
                <td style="width:25%;">'.$general_updatedby.'</td>
                <td>'.$responses->updatedby.'</td>
            </tr> 
        </table>
    </div>
</div>
';

$view .='</div>';

//OUTPUT
echo $view;    

template_footer()

?>