<?php
defined(page_security_key) or exit;

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

// Default input product values
$products_software = [
    'rowID' => '',
    'productrowid' => '',
    'status' => '',
    'version' => '',
    'hw_version' => '',
    'software' => '',
    'created' => '',
    'createdby' => $_SESSION['username'],
    'mandatory' => '',
    'latest' => ''
];

//productrowid is required by api
$productrowid = $_GET['productrowid'] ?? '';

if (isset($_GET['rowID'])) {
    // ID param exists, edit an existing product
    //CALL TO API
    $api_url = '/v1/products_software/rowID='.$_GET['rowID'].'&productrowid='.$productrowid;
    $responses = ioServer($api_url,'');

    //Decode Payload
    if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = null;}

    $products_software = json_decode(json_encode($responses[0]), true);

    
    if ($update_allowed === 1){
        if (isset($_POST['submit'])) {

            //CHECK FOR FIRMWARE FILE
            $firmware_file = $_FILES["fileToUpload"]["name"] ?? '';  

            if($firmware_file !='' || !empty($firmware_file)){

                $extension = strtolower(pathinfo($firmware_file, PATHINFO_EXTENSION));
                $target_dir = dirname(__FILE__)."/firmware/";

                if ($extension == 'hex'){
                    //READ FILE
                    $contents = file_get_contents($_FILES["fileToUpload"]["tmp_name"]);
                    //firmwarename
                    $firmware_name = pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_FILENAME);
                    $commitCode = compareCommitCodes($firmware_name,"");

                    //IF COMMITCODE IS EMPTY THEN RETURN HEX_FW
                    $fw_name = ($commitCode != '' || !empty($commitCode)) ? $commitCode : $firmware_name;
                    
                    //Filename
                    $input_file = $target_dir . $firmware_name.'.HEX';
                    //store firmware file
                    file_put_contents($input_file, $contents);
                    $_POST['version'] = $fw_name;

                } else {
                    $target_file = $target_dir . $firmware_file;
                    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
                    $firmware_name = $firmware_file;
                }

                //Use firmwarefile name as software version
                    $_POST['software'] = $firmware_name;   
            }

            //GET ALL POST DATA
            $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/products_software', $payload);
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=product&rowID='.$productrowid.'&success_msg=2');
            exit;
            
            }
        }
    }
    
    if ($delete_allowed === 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/products_software', $payload);
            if ($responses === 'NOK'){

            } else {
            // Redirect and delete product
            header('Location: index.php?page=product&rowID='.$productrowid.'&success_msg=3');
            exit;
            }
        }
    }
   
} else {
    // Create a new product
    if (isset($_POST['submit']) && $create_allowed === 1) {
        
        //CHECK FOR FIRMWARE FILE
        $firmware_file = $_FILES["fileToUpload"]["name"] ?? '';  

        if($firmware_file !='' || !empty($firmware_file)){

            $extension = strtolower(pathinfo($firmware_file, PATHINFO_EXTENSION));
            $target_dir = dirname(__FILE__)."/firmware/";

            if ($extension == 'hex'){
                //READ FILE
                $contents = file_get_contents($_FILES["fileToUpload"]["tmp_name"]);
                //firmwarename
                $firmware_name = pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_FILENAME);
                $commitCode = compareCommitCodes($firmware_name,"");

                //IF COMMITCODE IS EMPTY THEN RETURN HEX_FW
                $fw_name = ($commitCode != '' || !empty($commitCode)) ? $commitCode : $firmware_name;
                //Filename
                $input_file = $target_dir . $firmware_name.'.HEX';
                //store firmware file
                file_put_contents($input_file, $contents);
                
                $_POST['version'] = $fw_name;

                $firmware_name = $firmware_name.'.HEX';

            } else {
                $target_file = $target_dir . $firmware_file;
                move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
                $firmware_name = $firmware_file;
            }

            //Use firmwarefile name as software version
                $_POST['software'] = $firmware_name;   
        }

        //GET ALL POST DATA
        $data = json_encode($_POST , JSON_UNESCAPED_UNICODE);
        //Secure data
        $payload = generate_payload($data);
        //API call
        $responses = ioServer('/v1/products_software', $payload);
        if ($responses === 'NOK'){

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

template_header('Products software', 'products_software', '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">'.$product_version_software.'</h2>
        <a href="index.php?page=product&rowID='.$productrowid.'" 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 product?\')">';
}
if ($update_allowed === 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="#">'.$tab3.'</a>
         </div>
    ';

$view .= '<div class="content-block tab-content active">
            <div class="form responsive-width-100">
                <label for="status">'.$product_status.'</label>
                <select id="status" name="status">
                    <option value="1" '.($products_software['status']==1?' selected':'').'>'.$prod_status_1 .'</option>
                    <option value="0" '.($products_software['status']==0?' selected':'').'>'.$prod_status_0 .'</option>
                </select>
                <label for=""><i class="required">*</i>'.$product_version_version.'</label>
                <input id="name" type="text" name="version" placeholder="'.$product_version_version.'" value="'.$products_software['version'].'" >
                <label for=""><i class="required">*</i>'.$equipment_label5.'</label>
                <input id="name" type="text" name="hw_version" placeholder="'.$equipment_label5.'" value="'.$products_software['hw_version'].'" >
                ';             
 if ($products_software['software'] !=''){
    $view .= '    
                <label for=""><i class="required">*</i>'.$product_version_software.'</label>
                <input id="name" type="text" name="software" placeholder="'.$product_version_software.'" value="'.$products_software['software'].'">
    ';
 }               
 $view .= '     <label for=""><i class="required">*</i>'.ucfirst($register_mandatory).'</label>
                <select id="mandatory" name="mandatory">
                    <option value="0" '.($products_software['mandatory']==0?' selected':'').'>'.$general_no.'</option>
                    <option value="1" '.($products_software['mandatory']==1?' selected':'').'>'.$general_yes.'</option>
                </select>';

 if ($products_software['software'] !=''){
     $view .= ' 
                <label for=""><i class="required">*</i>'.ucfirst($general_sort_type_3).'</label>
                <select id="latest" name="latest">
                    <option value="0" '.($products_software['latest']==0?' selected':'').'>'.$general_no.'</option>
                    <option value="1" '.($products_software['latest']==1?' selected':'').'>'.$general_yes.'</option>
                </select>
            ';
}               
$view .= ' 
                <label for=""></label>
                <input type="file" name="fileToUpload" id="fileToUpload" accept=".hex, .HEX, .bin,.BIN,.exe,.EXE" style="width: 30%;padding: 50px 0 0 0;height: 10px;">         
                <input type="hidden" name="rowID" value="'.$products_software['rowID'].'"> 
                <input type="hidden" name="productrowid" value="'.$productrowid.'">   
            </div>
        </div>';

$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="'.$products_software['created'].'" readonly>
            <label for="productcode">'.$general_createdby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_createdby.'" value="'.$products_software['createdby'].'" readonly>
        </div>
    </div>';
$view .= '</form>';

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