<?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';
include_once './settings/systemrma.php';

$page = 'rma_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');

$view_product =  isAllowed('product' ,$_SESSION['profile'],$_SESSION['permission'],'R');
$view_history =  isAllowed('history' ,$_SESSION['profile'],$_SESSION['permission'],'C');

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

if ($rowID !=''){
    $url = 'index.php?page=rma&rowID='.$rowID.'';
} else {
    $url = 'index.php?page=rmas';
}

// Default input product values
$serial_input = '';
$rma = [
    'rowID' => '',
    'status' => 0,
    'header' => [
        'rowID'=> '',
        'accounthierarchy'=> '',
        'serialnumber'=>'',
        'hw_version'=>'',
        'sw_version'=>'',
        'service_date'=>'',
        'warranty_date'=> '',
        'order_ref'=>'',
        'sw_version_latest'=>'',
        'servicereport_available' => '',
        'productrowid' => '',
        'productcode'=> '',
        'productname'=> '',
        'return_reason' => '',
        'return_reason_note' => ''
    ],
    'questions' => [],
    'created' => '',
    'createdby' => '',
    'updated' => '',
    'updatedby' => '',
    'accounthierarchy' => ''
];

if (isset($_GET['rowID'])) {
    // ID param exists, edit an existing product
       //CALL TO API
       $api_url = '/v2/rma/rowID='.$_GET['rowID'];
       $responses = ioServer($api_url,'');
       //Decode Payload
       if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = null;}
       $rma = json_decode(json_encode($responses[0]), true);
      
       //GET DETAILS
       $rma['header'] = json_decode($rma['header'],true) ?? '';
       $rma['questions'] = json_decode($rma['questions'],true) ?? '';
       $serial_input = '<input type="text" name="header[serialnumber]" value="'.$rma['header']['serialnumber'].'">';

    if ($update_allowed === 1){
        if (isset($_POST['save'])) {
            //UPLOAD ALL PICTURES
            foreach ($_FILES["fileToUpload"]["name"] as $key => $value){
                //ONLY UPDATE PICTURES IF SOMETHING IS RETURNED
                if($value !='' || !empty($value)){
                    uploadrequest($key);
                }
             }   
            
             //GET ALL POST DATA
            $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            
            //API call
            $responses = ioServer('/v2/rma', $payload);
            if ($responses === 'NOK'){

            } else {
                header('Location: index.php?page=rma&rowID='.$_GET['rowID'].'&success_msg=2');
                exit;
            }
        }
    }
    
    if ($delete_allowed === 1){
        if (isset($_POST['delete'])) {
            //GET ALL POST DATA
            $payload = json_encode($_POST , JSON_UNESCAPED_UNICODE);

            //API call
            $responses = ioServer('/v2/rma', $payload);
            // Redirect and delete equipment
            if ($responses === 'NOK'){

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

    if (isset($_POST['assetID'])){       
        //GET RELATED DATA
        $api_url = '/v2/equipments/serialnumber='.$_POST['assetID'];
        $equipment = ioServer($api_url,'');
        //Decode Payload
        if (!empty($equipment)){$equipment = json_decode( $equipment,true);}else{$equipment = null;}
        
        if (isset($equipment[0]['rowID'])){
        //CHECK FOR LATEST SERVICEREPORT
        $servicereport_date = date("Y-m-d", strtotime("-457 days"));

        $api_url = '/v2/history/equipmentid='.$equipment[0]['rowID'].'&type=servicereport&created='.$servicereport_date;
        $servicereport = ioServer($api_url,'');
        //Decode Payload
        if (!empty($servicereport)){$servicereport = json_decode( $servicereport,true);}else{$servicereport = null;}
        
        //GetPartnerDetails
        $partner_data = json_decode($equipment[0]['accounthierarchy'],true) ?? '';
        if (is_array($partner_data)){
            $soldto = getPartnerName($partner_data['soldto']) ?? '-';
            $shipto = getPartnerName($partner_data['shipto']) ?? '-';
            $location = getPartnerName($partner_data['location']) ?? '-';
        }

        $rma = [
            'rowID' => '',
            'status' => 0,
            'header' => [
                'rowID'=> $equipment[0]['rowID'],
                'serialnumber'=> $equipment[0]['serialnumber'],
                'hw_version'=> $equipment[0]['hw_version'],
                'sw_version'=>$equipment[0]['sw_version'],
                'service_date'=> date('Y-m-d', strtotime($equipment[0]['service_date']. ' + 365 days')),
                'warranty_date'=> date('Y-m-d', strtotime($equipment[0]['warranty_date']. ' + 365 days')),
                'order_ref'=>$equipment[0]['order_ref'],
                'sw_version_latest'=>$equipment[0]['sw_version_latest'],
                'servicereport_available' => ((count($servicereport) !=0) ? 1 : 0),
                'productrowid'=> $equipment[0]['productrowid'],
                'productcode'=> $equipment[0]['productcode'],
                'productname'=> $equipment[0]['productname'],
                'return_reason' => '',
                'return_reason_note' => '',
                'soldto'=> $soldto,
                'shipto'=> $shipto,
                'location'=> $location
            ],
            'questions' => [],
            'created' => '',
            'createdby' => '',
            'updated' => '',
            'updatedby' => '',
            'accounthierarchy' => ''
        ];

            $serial_input = '<input type="text" name="header[serialnumber]" value="'.$rma['header']['serialnumber'].'">';
        
        } else {
            $serial_input = '<input type="text" name="header[serialnumber]" value="'.$_POST['assetID'].'">';
        }
    } else {
        //GET RELATED SERIALNUMBERS
        //CALL TO API
        $api_url = '/v2/equipments/list=';
        $assets_keys = ioServer($api_url,'');
        
        //Decode Payload
        if (!empty($assets_keys)){$assets_keys = json_decode($assets_keys,true);}else{$assets_keys = null;}
            //CREATE SERIALNUMBER DROPDOWN
            $serial_input ='<input type="text" list="serialnumbers" name="assetID" class="datalist" onchange="this.form.submit();">
                            <datalist id="serialnumbers">';
                                foreach ($assets_keys as $assets_key) {
                                $serial_input .= '<option>'.$assets_key['serialnumber'].'</option>';
            }
            $serial_input .= '</datalist>';
            //END DROPDOWN
    }

    // Create a new equipment
    if (isset($_POST['save'])) {
        
        //UPLOAD ALL PICTURES
        foreach ($_FILES["fileToUpload"]["name"] as $key => $value){
            //ONLY UPDATE PICTURES IF SOMETHING IS RETURNED
            if($value !='' || !empty($value)){
                uploadrequest($key);
            }
        }
        
        //GET ALL POST DATA
        $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);

        //API call
        $responses = ioServer('/v2/rma', $payload);
        if ($responses === 'NOK'){

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

template_header('RMA', 'rma','manage');

$view ='
<form action="" method="post" enctype="multipart/form-data">
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100"><?=$page?>'.($rma_h2 ?? 'Return Material Request').'</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 request?\')">';
}
if ($update_allowed === 1){
    $view .= '<input type="submit" name="save" value="Save" class="btn">';
}
    
$view .= '</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>'.($rma_information ?? 'RMA details').'
                </div>
                <div class="order-detail">
                    <h3>'.$equipment_label2.'</h3>
                    <p>'.$serial_input.'</p>
                </div>
                <div class="order-detail">
                    <h3>'.$equipment_label3.'</h3>
                    <p><select id="status" name="status" >
                        <option value="0" '.($rma['status']==0?' selected':'').'>'.$rma_status0_text .'</option>
                        <option value="1" '.($rma['status']==1?' selected':'').'>'.$rma_status1_text .'</option>
                        <option value="2" '.($rma['status']==2?' selected':'').'>'.$rma_status2_text .'</option>
                        <option value="3" '.($rma['status']==3?' selected':'').'>'.$rma_status3_text .'</option>
                        <option value="4" '.($rma['status']==4?' selected':'').'>'.$rma_status4_text .'</option>
                    </select></p>
                </div>
                <div class="order-detail">
                    <h3>'.$product_code.'</h3>
                    <p>'.(($view_product == 1)? '<a href="index.php?page=product&rowID='.$rma['header']['productrowid'].'" class="btn2">'.$rma['header']['productcode'].'</a>':'<input type="text" name="header[productcode]" value="'.$rma['header']['productcode'].'">').'</p>
                </div>  
                <div class="order-detail">
                    <h3>'.$product_name.'</h3>
                    <p>'.(($view_product == 1)? '<a href="index.php?page=product&rowID='.$rma['header']['productrowid'].'" class="btn2">'.(${$rma['header']['productname']} ?? $rma['header']['productname']).'</a>':'<input type="text" name="header[productname]" value="'.(${$rma['header']['productname']} ?? $rma['header']['productname']).'">').'</p>
                </div>
                <div class="order-detail">
                    <h3>'.$equipment_label10.'</h3>
                    <p><input type="text" name="header[rowID]" value="'.$rma['header']['rowID'].'"></p>
                </div>
                <div class="order-detail">
                    <h3>'.($rma_sw_version_latest ?? 'Latest software version').'</h3>
                        <p><select id="sw_version_latest" name="header[sw_version_latest]">
                                <option value="0" '.($rma['header']['sw_version_latest']==0?' selected':'').'>'.$general_no .'</option>
                                <option value="1" '.($rma['header']['sw_version_latest']==1?' selected':'').'>'.$general_yes .'</option>
                            </select>  
                        </p> 
                </div>
                <div class="order-detail">
                    <h3>'.($rma_servicereport_latest ?? 'Servicereport created last 7days').'</h3>
                        <p><select id="servicereport_available" name="header[servicereport_available]">
                                <option value="0" '.($rma['header']['servicereport_available']==0?' selected':'').'>'.$general_no .'</option>
                                <option value="1" '.($rma['header']['servicereport_available']==1?' selected':'').'>'.$general_yes .'</option>
                            </select>  
                        </p> 
                </div>
                <input type="hidden" name="header[productrowid]" value="'.$rma['header']['productrowid'].'" readonly>
                <input type="hidden" name="header[rowID]" value="'.$rma['header']['rowID'].'" readonly>
                <input type="hidden" name="header[productcode]" value="'.$rma['header']['productcode'].'" readonly>
                <input type="hidden" name="header[productname]" value="'.(${$rma['header']['productname']} ?? $rma['header']['productname']).'" readonly>
                <input type="hidden" name="rowID" value="'.$rma['rowID'].'" readonly>
                ';

                if ($rma['header']['servicereport_available']==1){
                    $view .='
                    <div class="order-detail">
                        <h3>'.$service_report_id.'</h3>
                        <p><input type="text" name="questions[historyID]" value="'.(isset($rma['questions']['historyID'])?$rma['questions']['historyID']:$servicereport[0]['historyID']).'"></p>
                        <input type="hidden" name="questions[equipmentID]" value="'.(isset($rma['questions']['equipmentID'])?$rma['questions']['equipmentID']:$servicereport[0]['equipmentID']).'" readonly>
                    </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_soldto.'</h3>
                    <p><input type="text" name="header[soldto]" value="'.($rma['header']['soldto'] ?? '').'"></p>
            </div>
            <div class="order-detail">
                    <h3>'.$general_shipto.'</h3>
                    <p><input type="text" name="header[shipto]" value="'.($rma['header']['shipto'] ?? '').'"></p>
            </div>
            <div class="order-detail">
                    <h3>'.$general_location.'</h3>
                    <p><input type="text" name="header[location]" value="'.($rma['header']['location'] ?? '').'"></p>
            </div>
        </div>';

$view .= '</div>';
// -------------------------------
//BUILD TO INPUT FORM BASED ON ARRAY
// ------------------------------
//
$view .='<div class="tabs">
            <a href="#" class="active">'.($rma_return_tab1 ?? 'Return reason').'</a>';

if($rma['header']['servicereport_available'] == 0 ){
      $view .='<a href="#">'.($rma_return_tab2 ?? 'Questions').'</a>';
}

$view .= '</div>';    
    
$view .= '<div class="content-block tab-content active">
            <div class="form responsive-width-100">
                 <div class="order-detail">
                    <h3>'.($rma_return_reason ?? 'Return reason').'</h3>
                    <p><select id="return_reason" name="header[return_reason]">
                            <option value="0" '.($rma['header']['return_reason']==0?' selected':'').'>'.$status0_text .'</option>
                        </select>  
                    </p> 
                </div>
                <div class="order-detail">
                    <h3>'.($rma_return_reason_note ?? 'Return reason note').'</h3>
                    <p><textarea id="return_reason_note" name="header[return_reason_note]" placeholder="'.($rma_return_reasons_notes ?? 'Return reason note').'" style="width: 100%;height: 150px;">'.$rma['header']['return_reason_note'].'</textarea>
                    </p> 
                </div>
            </div>
        </div>';

$view .= '<div class="content-block tab-content">
            <div class="form responsive-width-100">';
if($rma['header']['servicereport_available'] == 0 ){
    foreach($arrayQuestions_rma as $group){ 
        foreach($group['Questions_in_group'] as $question){
        
        switch ($question['Type']) {
            case 'dropdown':
            $view .= '<label for="" id="'.$question['QuestionID'].'">'.$question['Question'].'</label>';
            $view .= '<select id="" name="questions['.$question['QuestionID'].']" required>';
            $view .= '<option value=>'.$cartest_allowed_label0.'</option>';  
            foreach ($question['Response'] as $response){
                        $view .= '<option value="'.$response['responseID'].'" '.((isset($rma['questions'][$question['QuestionID']]) && $rma['questions'][$question['QuestionID']] == $response['responseID'])? 'selected':'').'>'.$response['Response'].'</option>';  
            }
            $view .= '</select>';
            break;

            case 'textarea':
            $view .= '<label for="" id="'.$question['QuestionID'].'">'.$question['Question'].'</label>';
            $view .= '<textarea id="QuestionID" name="questions['.$question['QuestionID'].']" placeholder="">'.(isset($rma['questions'][$question['QuestionID']])?$rma['questions'][$question['QuestionID']]:'').'</textarea>';
            break;

            case 'file';
                $view .= '<label for="" id="">'.$question['Question'].'</label>';

                if ($question['QuestionID'] !=''){
                    $view .= '<input type="hidden" name="questions['.$question['QuestionID'].']" value="'.$rma['questions'][$question['QuestionID']].'" />
                            <input type="file" name="fileToUpload['.$question['QuestionID'].']" onchange="preview('.$question['QuestionID'].')" style="width: 30%;padding: 50px 0 0 0;height: 10px;"><img id="'.$question['QuestionID'].'" src="'.$rma['questions'][$question['QuestionID']].'" width="150px"/>';
                } else {
                    $view .= '<input type="file" name="fileToUpload['.$question['QuestionID'].']" onchange="preview('.$question['QuestionID'].')" style="width: 30%;padding: 50px 0 0 0;height: 10px;" required><img id="'.$question['QuestionID'].'" src="" width="150px"/>';
                }
            
                break;
        }
        }
    }
} 

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

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

';

//OUTPUT
echo $view;

template_footer();
?>