<?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 PAGE ORIGIN FOR NAVIGATION AND SECURITY
$prev_page = $_SESSION['prev_origin'] ?? '';
$page = $_SESSION['origin'] = 'report_healthindex';

//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;
$status = $_SESSION['status'] = isset($_GET['status']) ? '&status='.$_GET['status'] : '';
$sort = $_SESSION['sort'] = isset($_GET['sort']) ? '&sort='.$_GET['sort'] : '';
$search = $_SESSION['search'] = isset($_GET['search']) ? '&search='.$_GET['search'] : '';
$software = $_SESSION['firmware'] = isset($_GET['firmware']) ? '&firmware='.$_GET['firmware'] : '';
$servicedate = $_SESSION['servicedate'] = isset($_GET['servicedate']) ? '&servicedate='.$_GET['servicedate'] : '';
$warrantydate = $_SESSION['warrantydate'] = isset($_GET['warrantydate']) ? '&warrantydate='.$_GET['warrantydate'] : '';
$partnerid = $_SESSION['partnerid'] = isset($_GET['partnerid']) ? '&partnerid='.$_GET['partnerid'] : '';
$productselected = $_SESSION['productcode'] = isset($_GET['productcode']) ? '&productcode='.$_GET['productcode'] : '';
$serialnumber_input = $_SESSION['serialnumber'] = isset($_GET['serialnumber']) ? '&serialnumber='.$_GET['serialnumber'] : '';

//GET PARAMETERS FOR FILTERS
$filter = urlGETdetailsFilter($_GET) ?? '';

// Determine the URL
$url = 'index.php?page=report_healthindex'.$status.$search.$software.$servicedate.$warrantydate.$partnerid.$sort.$productselected.$serialnumber_input;
//GET Details from URL
$GET_VALUES = urlGETdetails($_GET) ?? '';
//CALL TO API
$api_url = '/v2/equipment_healthindex/'.$GET_VALUES;
$responses = ioServer($api_url,'');
//Decode Payload
if (!empty($responses)){$responses = json_decode($responses);}else{$responses = null;}

//Return QueryTotal from API
$api_url = '/v2/equipment_healthindex/'.$GET_VALUES.'&totals=';
$query_total = ioServer($api_url,'');
//Decode Payload
if (!empty($query_total)){$query_total = $query_total;}else{$query_total = null;}

//Get Products related to assets
$api_url = '/v1/equipments/'.$GET_VALUES.'&products=';
$query_products = ioServer($api_url,'');
//Decode Payload
if (!empty($query_products)){$query_products = decode_payload($query_products);}else{$query_products = null;}

//BUILD LIST OF PRODUCTS
$product_list = '';

if ($query_products != null){   
    $product_list = '
    <select name="productcode">
    <option value="" disabled selected>'.$equipment_label4.'</option>';
    foreach ($query_products as $product){
        $product_list .= '<option value="'.$product->productcode.'">'.(${$product->productname} ?? $product->productname).'</option>';
    }
    $product_list .= '</select>';
}

if (isset($_GET['download'])){
    downloadToExcel('equipment_healthindex',$responses);
}

template_header('Healthindex', 'healthindex','view');
$view = '
<div class="content-title">
    <div class="title">
        <i class="fa-solid fa-database"></i>
        <div class="txt">
            <h2>'.$view_asset_data_ranking.' ('.$query_total.')</h2>
            <p></p>
        </div>
    </div>
    '.$back_btn_orgin.'
</div>';


$view .= '
<div class="content-header responsive-flex-column pad-top-5">';

$view .= '    
    <form action="" method="get">
        '.$filter.'
        <div class="filters">
            <a href="#"><i class="fa-solid fa-filter"></i>'.$general_filters.'</a>
            <div class="list">
                <select name="status">
                <option value="" disabled selected>'.$equipment_label3.'</option>
                <option value="0"'.($status==0?' selected':'').'>'.$status0_text.'</option>
                <option value="1"'.($status==1?' selected':'').'>'.$status1_text.'</option>
                <option value="2"'.($status==2?' selected':'').'>'.$status2_text.'</option>
                <option value="3"'.($status==3?' selected':'').'>'.$status3_text.'</option>
                <option value="4"'.($status==4?' selected':'').'>'.$status4_text.'</option>
                <option value="5"'.($status==5?' selected':'').'>'.$status5_text.'</option>
                </select>
                '.$product_list.'
                <button type="submit">'.$button_apply.'</button>
                <a class="cancel_link" style="color: #FFFFFF;text-decoration: none;" href="index.php?page=report_healthindex">'.$general_filters_clear.'</a>
            </div>
        </div>
          <div class="sort">
            <a href="#"><i class="fa-solid fa-sort"></i>'.$general_sort.'</a>
            <div class="list">
                <select name="sort">
                <option value="" disabled selected>'.$general_sort.'</option>
                <option value="1"'.($sort==1?' selected':'').'>'.$equipment_label2.' '.$general_sort_type_1.'</option>
                <option value="2"'.($sort==2?' selected':'').'>'.$equipment_label2.' '.$general_sort_type_2.'</option>
                <option value="3"'.($sort==3?' selected':'').'>'.$equipment_label3.' '.$general_sort_type_1.'</option>
                <option value="4"'.($sort==4?' selected':'').'>'.$equipment_label3.' '.$general_sort_type_2.'</option>
                <option value="5"'.($sort==5?' selected':'').'>'.$warranty_status.' '.$general_sort_type_1.'</option>
                <option value="6"'.($sort==6?' selected':'').'>'.$warranty_status.' '.$general_sort_type_2.'</option>
                <option value="7"'.($sort==7?' selected':'').'>'.$service_status.' '.$general_sort_type_1.'</option>
                <option value="8"'.($sort==8?' selected':'').'>'.$service_status.' '.$general_sort_type_2.'</option>
                <option value="9"'.($sort==9?' selected':'').'>'.$view_asset_data_ranking .' '.$general_sort_type_2.'</option>
                <option value="10"'.($sort==10?' selected':'').'>'.$view_asset_data_ranking .' '.$general_sort_type_1.'</option>
                </select>
                <button type="submit">'.$button_apply.'</button>
            </div>
        </div>
        ';

//SHOW DOWNLOAD TO EXCELL OPTION ONLY TO ADMIN USERS
if ($_SESSION['permission'] == 3 || $_SESSION['permission'] == 4){
    $view .='<div class="filters">
                <a href="index.php?page=report_healthindex&download="><i class="fa-solid fa-download"></i></a>        
            </div>';
}
$view .= '<div class="search">
            <label for="search">
                <input id="search" type="text" name="search" placeholder="'.$equiment_search.'" value="" class="responsive-width-100">
                <i class="fas fa-search"></i>
            </label>
        </div>
    </form>
</div>
';

$view .= '
<div class="content-block">
    <div class="table">
        <table class="sortable">
            <thead>
                <tr>
                    <th class="responsive-hidden">'.$view_asset_data_ranking.'</th>
                    <th class="responsive-hidden">'.$equipment_label1.'</th>
                    <th>'.$equipment_label2.'</th>
                    <th>'.$equipment_label3.'</th>
                    <th>'.$equipment_label4.'</th>
                    <th class="responsive-hidden"></th>  
                    <th class="responsive-hidden">'.$general_soldto.'</th>
                    <th class="responsive-hidden">'.$general_shipto.'</th>
                    <th>'.$view_asset_actions.'</th>
                </tr>
            </thead>
            <tbody>
            ';

            if (empty($responses)){

                $view .= '
                <tr>
                    <td colspan="8" style="text-align:center;">'.$message_no_assets.'</td>
                </tr>';
            }

foreach ($responses as $response){
//Translate status INT to STR
$status_text = 'status'.$response->status.'_text';
//GetPartnerDetails
$partner_data = json_decode($response->accounthierarchy);
$soldto = getPartnerName($partner_data->soldto) ?? $not_specified;
$shipto = getPartnerName($partner_data->shipto) ?? $not_specified;

//Additional items
$picture = glob("./assets/images/products/".$response->productcode.".{jpg,jpeg,png,gif}", GLOB_BRACE);
$indicators = overviewIndicators($response->warranty_date,$response->service_date,$response->sw_version,$response->hw_version);

$view .= '<tr>
            <td class="responsive-hidden"><span class="status '.(($response->healthindex >= 85) ?'enabled' : (($response->healthindex <= 50)? 'disabled' : 'id2')).'">'.$response->healthindex.'</span></td>
            <td class="responsive-hidden">'.$indicators.'</td>
            <td>'.$response->serialnumber.'</td>
            <td><span class="status id'.$response->status.'">'.$$status_text.'</span></td>
            <td>'.$response->productcode.'-'.(${$response->productname} ?? $response->productname).'</td>';
$view .= '  <td class="responsive-hidden">';
    if (!empty($picture)){
        $view .='    
            <img style="border-radius: 4px;height: 40px;" src="'.$picture[0].'" alt="">
            '; 
        }
$view .= ' </td>
            <td class="responsive-hidden">'.$soldto.'</td>
            <td class="responsive-hidden">'.$shipto.'</td>
            <td><a href="index.php?page=equipment&equipmentID='.$response->equipmentid.'" class="btn_link">'.$general_view .'</a></td>
        </tr>
      ';
 }
 $view .= ' 
     </tbody>
    </table>
    </div>
</div>
';

$view.='<div class="pagination">';
if ($pagination_page > 1) {
    $page = $pagination_page-1;
    $view .= '<a href="'.$url.'&p=1">'.$general_first.'</a>';
    $view .= '<a href="'.$url.'&p='.$page.'">'.$general_prev.'</a>';
}
$totals = ceil($query_total / $page_rows_equipment) == 0 ? 1 : ceil($query_total / $page_rows_equipment);
$view .= '<span> '.$general_page.$pagination_page.$general_page_of.$totals.'</span>';
if ($pagination_page * $page_rows_equipment < $query_total){
    $page = $pagination_page+1;
    $view .= '<a href="'.$url.'&p='.$page.'">'.$general_next.'</a>';
    $view .= '<a href="'.$url.'&p='.$totals.'">'.$general_last.'</a>';
}

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

template_footer();
?>