<?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/systemcartest.php';

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

//CALL TO API FOR cartest
$api_url = '/v1/cartests/rowID='.$_GET['rowID'];
$cartest = ioServer($api_url,'');

//Decode Payload
if (!empty($cartest)){$cartest = decode_payload($cartest);}else{$cartest = null;}
$cartest = $cartest[0];

//CHECK FOR CARTEST APP OR PORTAL
$version = str_contains($cartest->questions,'GoToP')?0:1;
//GET TEST DETAILS
$cartest_header = json_decode($cartest->header,true) ?? '';
$cartest_questions = json_decode($cartest->questions,true) ?? '';
$cartest_datapoints = json_decode($cartest->datapoints,true) ?? '';

// Handle success messages
if (isset($_GET['success_msg'])) {
    if ($_GET['success_msg'] == 1) {
        $success_msg = $message_ct_1;
    }
    if ($_GET['success_msg'] == 2) {
        $success_msg = $message_ct_2;
    }
    if ($_GET['success_msg'] == 3) {
        $success_msg = $message_ct_3;
    }
}

if (isset($_GET['download'])){
    downloadToExcel('cartests',$cartest);
}

template_header('Cartest', 'cartest', 'view');
$view = '
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.$cartest_h2.' - '.$_GET['rowID'].'</h2>
        <a href="index.php?page=cartests" class="btn alt mar-right-2">'.$button_cancel.'</a>
';

if ($update_allowed === 1 && $version != 0){
    $view .= '<a href="index.php?page=cartest_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>'.$cartest_information.'
                </div>
                <div class="order-detail">
                    <h3>'.$cartest_carbrand.'</h3>
                    <p>'.$cartest->carbrand.'</p>
                </div>
                <div class="order-detail">
                    <h3>'.$cartest_cartype.'</h3>
                    <p>'.$cartest->cartype.'</p>
                </div>
                <div class="order-detail">
                    <h3>'.$general_year.'</h3>
                    <p>'.(isset($cartest_header['year']) ? $cartest_header['year']: '').'</p>
                </div>
                <div class="order-detail">
                    <h3>'.$cartest_carvin.'</h3>
                    <p>'.$cartest_header['CarVIN'].'</p>
                </div>
              </div>
';

$view .='<div class="content-block order-details">
            <div class="block-header">
                <i class="fa-solid fa-user fa-sm"></i>'.$cartest_details_text.'
            </div>
            <div class="order-detail">
                    <h3>'.$cartest_created.'</h3>
                    <p>'.$cartest->created.'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$cartest_tester.'</h3>
                    <p>'.$cartest_header['NameTester'].'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$cartest_device.'</h3>
                    <p>'.$cartest_header['SN'].'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$cartest_device_hw.'</h3>
                    <p>'.$cartest_header['HW'].'</p>
            </div>
            <div class="order-detail">
                    <h3>'.$cartest_device_sw.'</h3>
                    <p>'.$cartest_header['FW'].'</p>
            </div>
        </div>';

$view .= '</div>';
$view .= '<div class="content-block">
            <div class="block-header">
                <i class="fa-solid fa-bars fa-sm"></i>'.$cartest_questions_text.'
            </div>
             <div class="table order-table">
            <table>';
            
            //Retrieve questions and awnsers
           
                if ($version == 0){

                    foreach ($cartest_questions as $key => $value){
                        $view .= '<tr>
                                    <td style="width:25%;">'.$key.'</td>
                                    <td>'.((!empty($value)|| $value !='')?$value:$not_specified).'</td>
                                </tr>';
                    }
                } else {
                    //CREATE OUTPUT BASED ON ARRAY
                    $view .= '<div class="tabs">';
                    foreach($arrayQuestions_cartest as $group){
                        if ($group['Group_sequence'] == 1){
                            $view .= '<a href="#" class="active">'.$group['Group'].'</a>';
                        } else {
                            $view .= '<a href="#">'.$group['Group'].'</a>';
                        }
                    }
                    $view .= '</div>';    
                        
                    foreach($arrayQuestions_cartest as $group){    
                    
                        if ($group['Group_sequence'] == 1){
                            $view .= '<div class="content-block tab-content active">
                                        <div class="form responsive-width-100">';
                         } else {
                            $view .= '<div class="content-block tab-content">
                                        <div class="form responsive-width-100">';
                        }
                        
                        foreach($group['Questions_in_group'] as $question){
                        
                        //SHOW QUESTION FROM ARRAY
                        $view .= '<label for="" id="'.$question['QuestionID'].'">'.$question['Question'].'</label>';
                        
                        //GET RESPONSE FROM DATABASE
                            foreach ($cartest_questions as $key => $value){
                                
                                if ($question['QuestionID'] == $key){

                                    switch ($question['Type']) {
                                        case 'dropdown':
                                            $view .= '<p>'.((!empty($value) || $value !="")?${'cartest_allowed_label'.$value}:$not_specified).'</p>';
                                            break;
                                        
                                        case 'textarea':
                                            $view .= '<p>'.((!empty($value) || $value !="")?$value:$not_specified).'</p>';
                                            break;
                                        
                                        case 'file':
                                            $view .= '<p><img src="'.$value.'" width="150px"/></p>';
                                            break;
                                    }
                                   
                                }
                            }
                        }
                    $view .= '    </div>
                                </div>';
                    } 
            
                }
            $view .= '
            </table>    
            </div>
        </div>
    ';

if (isset($cartest_datapoints) && $cartest_datapoints !=''){
$view .= '<div class="content-block">
    <div class="block-header">
        <i class="fa-solid fa-bars fa-sm"></i>'.$cartest_charts.'';
         
        //CREATE ARRAYS FOR DATAPOINTS
         $VCP = []; //for VCP values
         $VPP1 = []; //for VPP1 values
         $VPP2 = []; //for VPP2 values
         $VBAT = []; //for VBAT values
         $PWM = []; //for PWM values
         $STATE= []; //for state values
         $xaxis= []; //values for xaxis
         $x = 0;

         if ($version == 0){
            foreach ($cartest_datapoints as $datapoint){        
                    $VCP[] = $datapoint['vcp'];
                    $VPP1[] = $datapoint['vpp1'];
                    $VPP2[] = $datapoint['vpp2'];
                    $VBAT[] = $datapoint['vbat'];
                    $PWM[] = $datapoint['pwm'];

                    switch ($datapoint['state']) {
                        case 'FULL_CONNECT':
                            $STATE[] = 5;
                            break;
                        case 'REACTIVATE':
                            $STATE[] = 3;
                            break;
                        case 'DISCONNECTED':
                            $STATE[] = 0;
                            break;
                    }
                    

                    //Add to x-axis
                    $xaxis[] = $x;
                    $x++;
                }
         } else {
            $cartest_datapoints = is_array($cartest_datapoints)? $cartest_datapoints : json_decode($cartest_datapoints, true);
            $VCP = $cartest_datapoints['VCP']['VCP'];
            $VPP1 = $cartest_datapoints['VPP1']['VPP1'];
            $VPP2 = $cartest_datapoints['VPP2']['VPP2'];
            $VBAT = $cartest_datapoints['VBAT']['VBAT'];
            $PWM = $cartest_datapoints['PWM']['PWM'];
            $STATE = $cartest_datapoints['STATE']['STATE'];
            $xaxis = $cartest_datapoints['xChart']['xChart'];
         }
        $view.= '
        <div>
            <canvas id="chart_VCP" style="width:400px;max-width:100%"></canvas></div>
            <p><small>STATE: 0 = DISCONNECTED, 3 = REACTIVATE, 5 = FULL_CONNECT</small></p>
    
        <script>
                const xValues = '.json_encode($xaxis).'; //xChart;
                new Chart("chart_VCP", {
                type: "line",
                data: {
                    labels: xValues,
                    datasets: [{ 
                    label: "VCP",
                    data: '.json_encode($VCP).',
                    borderColor: "red",
                    fill: false
                    },
                    { 
                        label: "VBAT",
                        data: '.json_encode($VBAT).',
                        borderColor: "black",
                        fill: false
                    },{ 
                        label: "VPP1",
                        data: '.json_encode($VPP1).',
                        borderColor: "green",
                        fill: false
                        }, { 
                        label: "VPP2",
                        data: '.json_encode($VPP2).',
                        borderColor: "blue",
                        fill: false
                        },
                        {
                            label: "PWM",
                            data: '.json_encode($PWM).',
                            backgroundColor: "yellow",
                            fill: false
                        },
                        {
                            label: "STATE",
                            data: '.json_encode($STATE).',
                            backgroundColor: "purple",
                            fill: false
                        }
                ]
                },
                options: {
                    legend: {display: true}
                }
                });
        </script>';
    
$view .= '</div></div>';
}
//OUTPUT
echo $view;    

template_footer()

?>