<?php
defined(page_security_key) or exit;

$page = 'contract_manage';
//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
    header('location: index.php');
    exit;
}
//PAGE Security
$update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'C');

// Default input product values
$contract = [
    'rowID' => '',
    'type' => '',
    'status' => '',
    'accountID' => '',
    'start_date' => '',
    'duration' => '',
    'service_count' => '',
    'contract_details' => '',
    'created' => '',
    'createdby' => '',
    'updated' => '',
    'updatedby' => '',
    'billing_plan' => '',
    'pricing' => '',
    'reference' => '',
    'servicetool' => [],
    'assigned_users' => [],
    'accounthierarchy' => $_SESSION['partnerhierarchy'],
    'ignore_list' => []
];

$contract_ID = $_GET['rowID'] ?? '';

if ($contract_ID !=''){
    $url = 'index.php?page=contract&rowID='.$contract_ID.'';
} else {
    $url = 'index.php?page=contracts';
}

if (isset($_GET['rowID'])) {
    //CALL TO API
    $api_url = '/v1/contracts/rowID='.$contract_ID;
    $responses = ioServer($api_url,'');
    //Decode Payload
    if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;}
    
    $contract = json_decode(json_encode($responses[0]), true);

    if ($update_allowed === 1){
        if (isset($_POST['submit'])) {
            //GET ALL POST DATA
            $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            var_dump($data);
            //Secure data
            $payload = generate_payload($data);
        
            //API call
            $responses = ioServer('/v1/contracts', $payload);
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=contract&rowID='.$contract_ID.'&success_msg=2');
            exit;
            }
            
        }
    }
    
    if ($delete_allowed === 1){
        if (isset($_POST['delete'])) {
            //GET ALL POST DATA
            $data = json_encode($_POST , JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/contracts', $payload);
            // Redirect and delete product
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=contracts&success_msg=3');
            exit;
            }
        }
    }
   
} else {
    // Create a new product
    if (isset($_POST['submit']) && $create_allowed === 1) {
        //GET ALL POST DATA
        $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
        //Secure data
        $payload = generate_payload($data);
        //API call
        $responses = ioServer('/v1/contracts', $payload);
        if ($responses === 'NOK'){

        } else {
        header('Location: index.php?page=contracts&success_msg=1');
        exit;
        }
    }
}

template_header('Contract', 'contract', 'manage');

$view ='
<form action="" method="post">
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.$contract_h2.'</h2>
        <a href="'.$url.'" class="btn alt mar-right-2">'.$button_cancel.'</a>
';

if ($delete_allowed === 1){
    $view .= '<input type="submit" name="delete" value="Delete" class="btn red mar-right-2" onclick="return confirm(\'Are you sure you want to delete this contract?\')">';
}
if ($update_allowed === 1){
    $view .= '<input type="submit" name="submit" value="Save" class="btn">';
}
   
$view .= '</div>';

$view .= '<div class="tabs">
            <a href="#" class="active">'.$tab1 .'</a>
            <a href="#">'.$tab2.'</a>
            <a href="#">'.$tab3.'</a>
        </div>
    ';

$view .='<div class="content-block tab-content active">
            <div class="form responsive-width-100">
                <label for="">'.$contract_status.'</label>
                <select name="status">
                    <option value="0" '.($contract['status']==0?' selected':'').'>'.$contract_status0.'</option>
                    <option value="1" '.($contract['status']==1?' selected':'').'>'.$contract_status1.'</option>
                    <option value="2" '.($contract['status']==2?' selected':'').'>'.$contract_status2.'</option>
                </select>
            </div>
            <div class="form responsive-width-100">
                <label for="">'.$contract_type.'</label>
                <select name="type">
                    <option value="0" '.($contract['type']==0?' selected':'').'>'.$contract_type0.'</option>
                    <option value="1" '.($contract['type']==1?' selected':'').'>'.$contract_type1.'</option>
                    <option value="2" '.($contract['type']==2?' selected':'').'>'.$contract_type2.'</option>
                </select>
            </div>
             <div class="form responsive-width-100">
                <label for="">'.$contract_billinglabel.'</label>
                <select name="billing_plan">
                    <option value="4" '.($contract['billing_plan']==4?' selected':'').'>'.($contract_billing4 ?? 'Onetime Upfront').'</option>
                    <option value="0" '.($contract['billing_plan']==0?' selected':'').'>'.$contract_billing0.'</option>
                    <option value="1" '.($contract['billing_plan']==1?' selected':'').'>'.$contract_billing1.'</option>
                    <option value="2" '.($contract['billing_plan']==2?' selected':'').'>'.$contract_billing2.'</option>
                    <option value="3" '.($contract['billing_plan']==3?' selected':'').'>'.$contract_billing3.'</option>
                </select>
            </div>
            <div class="form responsive-width-100">
                <label for="">'.$contract_start_date.'</label>
                <input type="date" name="start_date" value="'.$contract['start_date'].'" required>
            </div>';

//Define end_date based on duration
if ($contract['duration'] !='' && $contract['start_date'] !=''){
    $date = date('Y-m-d', strtotime('+'.$contract['duration'].' months', strtotime($contract['start_date'])));

    $view .= '<div class="form responsive-width-100">
                <label for="">'.$contract_end_date.'</label>
                <input type="date" value="'.$date.'" readonly>
            </div>';
}
$view .=  '<div class="form responsive-width-100">
                <label for="">'.$contract_duration.'</label>
                <input type="number" name="duration" value="'.$contract['duration'].'" required>
            </div>
            <div class="form responsive-width-100">
                <label for="">'.$contract_service.'</label>
                <input type="number" name="service_count" value="'.$contract['service_count'].'">
            </div>
            <div class="form responsive-width-100">
                <label for="">'.$contract_reference.'</label>
                <input type="text" name="reference" value="'.$contract['reference'].'" >
            </div>';

$view .= '<div class="form responsive-width-100">
                <label for="">'.$contract_servicetool.' <button type="button" class="btn2" onclick="addField(\'assigned_servicetools\',\'servicetool[]\');" style="width:5%;background-color:#bed4ea;"> + </button></label>';
 //Check for assigned servicetools
$assigned_servicetools = (empty($contract['servicetool']))? '' :json_decode($contract['servicetool'],true);                       
   
    if (!empty($assigned_servicetools || $assigned_servicetools !='')){
        foreach ($assigned_servicetools as $tool){
            $view .=  '<input id="assigned_servicetools" type="text" name="servicetool[]" placeholder="'.$contract_servicetool.'" value="'.$tool.'">';
        }
        if (count($assigned_servicetools) == 0){
        $view .=  '<input id="assigned_servicetools" type="text" name="servicetool[]" placeholder="'.$contract_servicetool.'" value="">';
        }
    } else {
        $view .=  '<input id="assigned_servicetools" type="text" name="servicetool[]" placeholder="'.$contract_servicetool.'" value="">';

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

$view .=' <div class="form responsive-width-100">
                <label for="">'.$contract_assigned_users.' <button type="button" class="btn2" onclick="addField(\'assigned_users\',\'assigned_users[]\');" style="width:5%;background-color:#bed4ea;"> + </button></label>';

//Check for assigned users
$assigned_users = (empty($contract['assigned_users']))? '' :json_decode($contract['assigned_users'],true);                     
  
    if (!empty($assigned_users) || $assigned_users != ''){
        foreach ($assigned_users as $user){
            $view .=  '<input id="assigned_users" type="text" name="assigned_users[]" placeholder="'.$contract_assigned_users.'" value="'.$user.'">';
        }  
        if (count($assigned_users) == 0){
        $view .=  '<input id="assigned_users" type="text" name="assigned_users[]" placeholder="'.$contract_assigned_users.'" value="">';
        }
    } else {
        $view .=  '<input id="assigned_users" type="text" name="assigned_users[]" placeholder="'.$contract_assigned_users.'" value="">';
    }

$view .='   </div>';

$view .=' <div class="form responsive-width-100">
                <label for="">'.$contract_ignore_serial.' <button type="button" class="btn2" onclick="addField(\'ignore_lists\',\'ignore_list[]\');" style="width:5%;background-color:#bed4ea;"> + </button></label>';

//Check for assigned users
$ignore_lists = (empty($contract['ignore_list']))? '' :json_decode($contract['ignore_list'],true);                     
  

    if (!empty($ignore_lists) || $ignore_lists != ''){
        foreach ($ignore_lists as $list){
            $view .=  '<input id="ignore_lists" type="text" name="ignore_list[]" placeholder="'.$contract_ignore_serial.'" value="'.$list.'">';
        }    
        if (count($ignore_lists) == 0){
            $view .=  '<input id="ignore_lists" type="text" name="ignore_list[]" placeholder="'.$contract_ignore_serial.'" value="">';
        }
    } else {
        $view .=  '<input id="ignore_lists" type="text" name="ignore_list[]" placeholder="'.$contract_ignore_serial.'" value="">';
    }

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

//GET PARTNERDATA
$partner_data = json_decode($contract['accounthierarchy']);

//BUID UP DROPDOWNS
$salesid_dropdown = listPartner('salesid',$_SESSION['permission'],$partner_data->salesid,'');
$soldto_dropdown = listPartner('soldto',$_SESSION['permission'],$partner_data->soldto,'');
$shipto_dropdown = listPartner('shipto',$_SESSION['permission'],$partner_data->shipto,'');
$location_dropdown = listPartner('location',$_SESSION['permission'],$partner_data->location,'');

//DISPLAY
$view .= '<div class="content-block tab-content">
            <div class="form responsive-width-100">
';
$view .= '<label for="status">'.$general_salesid.'</label>';
$view .= $salesid_dropdown;
$view .= '<label for="status">'.$general_soldto.'</label>';
$view .= $soldto_dropdown;
$view .= '<label for="status">'.$general_shipto.'</label>';
$view .= $shipto_dropdown;
$view .= '<label for="status">'.$general_location.'</label>';
$view .= $location_dropdown;

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

$view .= '<div class="content-block tab-content">
        <div class="form responsive-width-100">
            <label for="">'.$general_created.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_created.'" value="'.$contract['created'].'" readonly>
            <label for="">'.$general_createdby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_createdby.'" value="'.$contract['createdby'].'" readonly>
             <label for="productcode">'.$general_updated.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updated.'" value="'.$contract['updated'].'" readonly>
            <label for="productcode">'.$general_updatedby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updatedby.'" value="'.$contract['updatedby'].'" readonly>
           <input id="name" type="hidden" name="rowID" value="'.$contract['rowID'].'" readonly>
        </div>
    </div>';


$view .= '</form>';


//Output
echo $view;

template_footer()?>