<?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);  
}

$page = 'equipment_manage';
$page_edit = 'equipment_manage_edit';
//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');
$update_allowed_special = isAllowed($page_edit ,$_SESSION['profile'],$_SESSION['permission'],'U');

// Default input product values
$equipment = [
    'rowID' => '',
    'productrowid' => '',
    'created' => '',
    'createdby' => $_SESSION['username'],
    'status' => 1,
    'accounthierarchy' => $_SESSION['partnerhierarchy'],
    'serialnumber' => '',
    'hw_version' => '',
    'sw_version' => '',
    'service_date' => $date,
    'warranty_date' => $date,
    'order_ref' => '',
    'geolocation' => [],
    'updated' =>'',
    'updatedby' =>''
];

$equipment_ID = $_GET['equipmentID'] ?? '';




if ($equipment_ID !=''){
    $url = 'index.php?page=equipment&equipmentID='.$equipment_ID.'';
} else {
    $url = 'index.php?page=equipments';
    //ALLOW UPDATES AT CREATION
    $update_allowed_special = 1;
}

//GET PRODUCTS
$api_url = '/v1/products/list=';
$responses = ioServer($api_url,'');
//Decode Payload
if (!empty($responses)){$products = decode_payload($responses);}else{$products = null;}

if (isset($_GET['equipmentID'])) {
    // ID param exists, edit an existing product
    //CALL TO API
    $api_url = '/v1/equipments/equipmentID='.$equipment_ID;
    $responses = ioServer($api_url,'');
    //Decode Payload
    if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;}
    
    $equipment = json_decode(json_encode($responses[0]), true);

    //GET PRODUCTS_SOFTWARE
    $api_url = '/v1/products_software/productrowid='.$equipment['productrowid'].'&status=1';
    $products_software = ioServer($api_url,'');
    //Decode Payload
    if (!empty($products_software)){$products_software = decode_payload($products_software);}else{$products_software = null;}

    //------------------------------------
    //CHECK IF USER IS ALSO CREATOR OF RECORD THEN OVERRIDE UPDATE_ALLOWED
    //------------------------------------
    $equipment_owner = (($equipment['createdby'] == $_SESSION['username'])? 1 : 0);
    
    if ($update_allowed === 1 || $equipment_owner === 1 || $update_allowed_special === 1){
        if (isset($_POST['submit'])) {
            //GEOLOCATION ARRAY convert to JSON
            $_POST['geolocation'] = json_encode($_POST['geolocation'],JSON_UNESCAPED_UNICODE);
            //GET ALL POST DATA
            $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/equipments', $payload);
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=equipment&equipmentID='.$equipment_ID.'&success_msg=2');
            exit;
            }
        }
    }
    
    if ($delete_allowed === 1 || $equipment_owner === 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/equipments', $payload);
            // Redirect and delete equipment
            if ($responses === 'NOK'){

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

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

template_header('Equipment', 'equipment', 'manage');

$label_h2 = (($equipment_ID !='')? $manage_asset_h2 : $button_create_asset);
$view ='
<form action="" method="post">
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100"><?=$page?>'.$label_h2.'</h2>
        <a href="'.$url.'" class="btn alt mar-right-2">'.$button_cancel.'</a>
';



if ($delete_allowed === 1 || $equipment_owner === 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 asset?\')">';
}
if ($update_allowed === 1 || $equipment_owner === 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>
    ';

//create product option list
$product_option_list ='';
foreach ($products as $product){
    $product_option_list .= '<option value="'.$product->rowID.'" '.($equipment['productrowid']==$product->rowID?' selected':'').'>'.$product->productcode.' - '.(${$product->productname} ?? $product->productname).'</option>
   ';
}    

//create products_software list
$product_software_list ='';
if (isset($products_software) && $products_software !=''){
    $product_software_list = '
        <label for="sw_version_upgrade">'.($equipment_sw_version_upgrade ?? 'sw_version_upgrade').'</label>
        <select id="sw_version_upgrade" name="sw_version_upgrade" '.($update_allowed_special==0? 'disabled':'').'>
            <option></option>
        ';
        foreach ($products_software  as $products_soft ){
            if ($products_soft->hw_version == $equipment['hw_version']){
                $product_software_list .= '<option value="'.$products_soft->rowID.'" '.($equipment['sw_version_upgrade']==$products_soft->rowID?' selected':'').'>'.$products_soft->version.' - '.$products_soft->software.'</option>
                ';
            }
    }    
    $product_software_list .= '</select>';
}

$view .= '<div class="content-block tab-content active">
            <div class="form responsive-width-100">
                <label for="status">'.$equipment_label3.'</label>
                <select id="status" name="status" '.($update_allowed_special==0? 'disabled':'').'>
                    <option value="0" '.($equipment['status']==0?' selected':'').'>'.$status0_text .'</option>
                    <option value="1" '.($equipment['status']==1?' selected':'').'>'.$status1_text .'</option>
                    <option value="2" '.($equipment['status']==2?' selected':'').'>'.$status2_text .'</option>
                    <option value="3" '.($equipment['status']==3?' selected':'').'>'.$status3_text .'</option>
                    <option value="4" '.($equipment['status']==4?' selected':'').'>'.$status4_text .'</option>
                    <option value="5" '.($equipment['status']==5?' selected':'').'>'.$status5_text .'</option>
                </select>
                <label for="productrowid">'.$equipment_label4.'</label>
                <select id="productrowid" name="productrowid" '.($update_allowed_special==0? 'disabled':'').'>
                <option value="'.$equipment['productrowid'].'">'.(${$equipment['productname']} ?? $equipment['productname']).'</option>
                '.$product_option_list.'
                </select>
                <label for="serialnumber">'.$equipment_label2.'</label>
                <input id="name" type="text" name="'.($update_allowed_special==1? 'serialnumber':'').'" placeholder="'.$equipment_label2.'" value="'.$equipment['serialnumber'].'" '.($update_allowed_special==0? 'readonly':'required').'>
                <label for="hardware">'.$equipment_label5.'</label>
                <input id="name" type="text" name="hw_version" placeholder="'.$equipment_label5.'" value="'.$equipment['hw_version'].'" '.($update_allowed_special==0? 'readonly':'').'>
                <label for="hardware">'.$equipment_label6.'</label>
                <input id="name" type="text" name="sw_version" placeholder="'.$equipment_label6.'" value="'.$equipment['sw_version'].'" '.($update_allowed_special==0? 'readonly':'').'>
                '.$product_software_list.'
                <label for="service_date">'.$equipment_label7.'</label>
                <input id="name" type="date" name="'.($update_allowed_special==1? 'warranty_date':'').'" placeholder="'.$equipment_label7.'" value="'.$equipment['warranty_date'].'" style="width:80%;" '.($update_allowed_special==0? 'readonly':'').'>
                <label for="service_date">'.$equipment_label8.'</label>
                <input id="name" type="date" name="'.($update_allowed_special==1? 'service_date':'').'" placeholder="'.$equipment_label8.'" value="'.$equipment['service_date'].'" style="width:80%;" '.($update_allowed_special==0? 'readonly':'').'>
                <input type="hidden" name="rowID" value="'.$equipment_ID.'">
                <input type="hidden" name="old_status" value="'.$equipment['status'].'">   
            </div>
        </div>';

        

//GET PARTNERDATA
$partner_data = json_decode($equipment['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,'');
if (isset($partner_data->section)){$section = getPartnerName($partner_data->section) ?? 'Not specified';} else {$section = 'Not specified';}


//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 .= '<label for="status">'.$general_section.'</label>
        <input id="name" type="text" name="section" placeholder="'.$general_section.'" value="'.$section.'"">';
$view .= '
        <input type="hidden" name="old_salesid" value="'.$partner_data->salesid.'">   
        <input type="hidden" name="old_soldto" value="'.$partner_data->soldto.'">   
        <input type="hidden" name="old_shipto" value="'.$partner_data->shipto.'">   
        <input type="hidden" name="old_location" value="'.$partner_data->location.'">   
    </div>
</div>';

$changelog = showlog('equipment',$equipment_ID)?? '';

//GEOLOCATION
$geo_details = (is_string($equipment['geolocation']))? json_decode($equipment['geolocation']) : ''; 
if (is_array($geo_details)) {                      
    $geodetails_lat = $geo_details[0];
    $geodetails_lon = $geo_details[1];
} else{
    $geodetails_lat = '';
    $geodetails_lon = '';
}

$view .= '<div class="content-block tab-content">
        <div class="form responsive-width-100">
            <label for="productcode">'.$general_created.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_created.'" value="'.$equipment['created'].'" readonly>
            <label for="productcode">'.$general_createdby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_createdby.'" value="'.$equipment['createdby'].'" readonly>
            <label for="productcode">'.$general_updated.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updated.'" value="'.$equipment['updated'].'" readonly>
            <label for="productcode">'.$general_updatedby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updatedby.'" value="'.$equipment['updatedby'].'" readonly>
            <label for="productcode">'.$equipment_label11.'</label>
            <input id="name" type="text" name="order_ref" placeholder="'.$equipment_label11.'" value="'.$equipment['order_ref'].'">
            <label for="productcode">'.$equipment_label12.'</label>
            <input id="name" type="text" name="geolocation[]" placeholder="'.$equipment_label12.'" value="'.$geodetails_lat.'">
            <input id="name" type="text" name="geolocation[]" placeholder="'.$equipment_label12.'" value="'.$geodetails_lon.'">
            '.($update_allowed_special==1? $changelog:'').'
        </div>      
    </div>';


$view .= '</form>';

//Output
echo $view;
template_footer()?>