<?php
defined(page_security_key) or exit;

$page = 'contract';
//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' => '',
    'billing_plan' => '',
    'pricing' => '',
    'reference' => '',
    'servicetool' => '',
    'assigned_users' => []
];

$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);

            //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=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="index.php?page=contracts" 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_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_reference.'</label>
                <input type="number" name="reference" value="'.$contract['reference'].'" >
            </div>
        </div>';


//DISPLAY
$view .= '<div class="content-block tab-content">
            <div class="form responsive-width-100">
                <label for="">'.$contract_account.'</label>
                <input id="name" type="text" name="accountID" placeholder="'.$contract_account.'" value="'.$contract['accountID'].'" required>
            </div>
            <div class="form responsive-width-100">
                <label for="">'.$contract_servicetool.'</label>
                <input id="name" type="text" name="servicetool" placeholder="'.$contract_servicetool.'" value="'.$contract['servicetool'].'">
            </div>
            <div class="form responsive-width-100">
                <label for="">'.$contract_assigned_users.'</label>';


//Check for assigned users
$assigned_users = json_decode($contract['assigned_users']) ?? ''; 

if (is_array($assigned_users)) {                        
    foreach ($assigned_users as $user){
    $view .=  '<input id="assigned_users" type="text" name="assigned_users" placeholder="'.$contract_assigned_users.'" value="'.$user.'">';
    }
} else{
    $view .=  '<input id="assigned_users" type="text" name="assigned_users[]" placeholder="'.$contract_assigned_users.'" value="">';
}

$view .='   </div>
            <button type="button" class="btn" onclick="addField(\'assigned_users\',\'assigned_users[]\');"> + </button> <small>'.$contract_assigned_users_add.'</small>
</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>
            <input id="name" type="hidden" name="rowID" value="'.$contract['rowID'].'" readonly>
        </div>
    </div>';


$view .= '</form>';


//Output
echo $view;

template_footer()?>