<?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';
//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';
}

// 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) ?? '';

//------------------------------
//Variables
//------------------------------
$status_text = 'rma_status'.$rma['status'].'_text';
$rma_status_text = 'rma_return_reason'.$rma['status'].'_text';

// Handle success messages
if (isset($_GET['success_msg'])) {
    if ($_GET['success_msg'] == 1) {
        $success_msg = $message_rma_1;
    }
    if ($_GET['success_msg'] == 2) {
        $success_msg = $message_rma_2;
    }
    if ($_GET['success_msg'] == 3) {
        $success_msg = $message_rma_3;
    }
}     

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

$view = '
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.($rma_h2 ?? 'Return Material Request').' - '.$_GET['rowID'].'</h2>
        <a href="index.php?page=rmas" class="btn alt mar-right-2">'.$button_cancel.'</a>
';

if ($update_allowed === 1){
    $view .= '<a href="index.php?page=rma_manage&rowID='.$_GET['rowID'].'" class="btn">Edit</a>';
}
     
$view .= '</div>';

if (isset($success_msg)){
    $view .= ' <div class="msg success">
                    <i class="fas fa-check-circle"></i>
                    <p>'.$success_msg.'</p>
                    <i class="fas fa-times"></i>
                </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_label3.'</h3>
                    <p><span class="status id'.$rma['status'].'">'.$$status_text.'</span></p>
                </div>
                <div class="order-detail">
                    <h3>'.$equipment_label2.'</h3>
                    <p>'.$rma_header['serialnumber'].'</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>'.$rma_header['rowID'].'</p>
                </div>
                <div class="order-detail">
                    <h3>'.($rma_sw_version_latest ?? 'Latest software version').'</h3>
                    <p>'.(($rma_header['sw_version_latest']==0) ? $general_no: $general_yes).'</p>
                </div>
                <div class="order-detail">
                    <h3>'.($rma_servicereport_latest ?? 'Servicereport created last 7days').'</h3>
                    <p>'.(($rma_header['servicereport_available']==0) ? $general_no: $general_yes).'</p>
                </div>';

                if (isset($rma_questions['equipmentID'])){
                $view .='
                    <div class="order-detail">
                        <h3>'.$servicereport_details.'</h3>
                        <p><a href="index.php?page=servicereport&equipmentID='.$rma_questions['equipmentID'].'&historyID='.$rma_questions['historyID'].'" class="btn_link">'.$general_view.'</a></p>   
                    </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>'.($rma_header['soldto'] ?? '').'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$general_shipto.'</h3>
                    <p>'.($rma_header['shipto'] ?? '').'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$general_location.'</h3>
                    <p>'.($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 .= '<a href="#">'.($general_actions ?? 'Actions').'</a>
          <a href="#">'.($tab3 ?? 'Log').'</a>
    </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>'.$$rma_status_text.'</p>
                    </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>';

    if($rma_header['servicereport_available'] == 0 ){
        $view .= '<div class="content-block tab-content">
            <div class="form responsive-width-100">';
           
                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 class="content-block tab-content active">
        <div class="form responsive-width-100">
             
        </div>
    </div>';

$view .= '<div class="content-block tab-content active">
    <div class="form responsive-width-100">
 
    </div>
</div>';

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

';

//OUTPUT
echo $view;

template_footer();
?>