<?php
defined(page_security_key) or exit;

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

// Default input product values
$text_variable = [
    'rowID' => '',
    'variable' => '',
    'created' => '',
    'createdby' => '',
    'updated' => '',
    'updatedby' => '',
    'accounthierarchy' => ''
];

if (isset($_GET['rowID'])) {
    //CALL TO API
    $api_url = '/v2/translations/rowID='.$_GET['rowID'];
    $responses = ioServer($api_url,'');
    //Decode Payload
    if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = null;}
    
    $text_variable = json_decode(json_encode($responses[0]), true);

    //CALL TO API FOR RELATED TRANSLATIONS
    $api_url = '/v2/translations_details/variable_ID='.$_GET['rowID'];
    $text_variable_translations = ioServer($api_url,'');
    //Decode Payload
    if (!empty($text_variable_translations)){$text_variable_translations = json_decode($text_variable_translations,true);}else{$text_variable_translations = null;}

    if ($update_allowed === 1){
        if (isset($_POST['submit'])) {
           
            //GET ALL POST DATA
            $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //API call
            $responses = ioServer('/v2/translations', $payload);

            if ($responses === 'NOK'){

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

        if (isset($_POST['add'])) {
      
            //GET ALL POST DATA
            $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //API call
            $responses = ioServer('/v2/translations_details', $payload);

            if ($responses === 'NOK'){

            } else {
                if ($_SESSION['permission'] == 4){
                    generateLanguageFile($_POST['language_key'],$_SESSION['userkey']);
                }
                header('Location: index.php?page=translation_manage&rowID='.$_GET['rowID'].'');
            exit;
            }
        
        }
        if (isset($_POST['update']) && isset($_POST['item'])) {
            //Indicator if update has errors
            $NOK_error = 0;

            //RUN through all POST items
            foreach ($_POST['item'] as $attr){
                
                
                //GET ALL POST DATA
                $payload = json_encode($attr, JSON_UNESCAPED_UNICODE);

                //API call
                $responses = ioServer('/v2/translations_details', $payload);

                if ($responses === 'NOK'){
                    //NOT correct exit procedure
                    $NOK_error++; 
                    exit;
                } else {
                    $attr_language = $attr['language_key'];
                }
            }

            if ($NOK_error == 0){
                //NO errors generatelanguagefile
                if ($_SESSION['permission'] == 4){
                    generateLanguageFile($attr_language,$_SESSION['userkey']);
                }
            }

            header('Location: index.php?page=translation_manage&rowID='.$_GET['rowID'].'');
            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/translations', $payload);
            // Redirect and delete product
            if ($responses === 'NOK'){

            } else {
            header('Location: index.php?page=translations&success_msg=3');
            exit;
            }
        }
    }
   
} else {
    // Create a new variable
    if (isset($_POST['submit']) && $create_allowed === 1) {
        //GET ALL POST DATA
        $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);
          //API call
        $responses = ioServer('/v2/translations', $payload);
  
        if ($responses === 'NOK'){

        } else {
            //GET ROWID OF CREATED ITEM
            $variable_rowID = json_decode($responses,true);
            header('Location: index.php?page=translation_manage&rowID='.$variable_rowID['rowID'].'');
            exit;
        }
    }
}
//EMPTY VIEW
$view = '';

// Handle success messages
if (isset($_GET['success_msg'])) {
    if ($_GET['success_msg'] == 0) {
        $success_msg = $error_msg_0;
    }
}

template_header('Translation', 'translation', 'manage');

if (isset($success_msg)){
    $view .= ' <div class="msg error">
                    <i class="fas fa-check-circle"></i>
                    <p>'.$success_msg.'</p>
                    <i class="fas fa-times"></i>
                </div>';
}

$view .='
<form action="" method="post">
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.($text_variables_h2 ?? '').'</h2>
        <a href="index.php?page=translations" 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 variable?\')">';
}
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>
    ';

//Define Service and User enabled
$view .= '<div class="content-block tab-content active">
            <div class="form responsive-width-100">
            <label for="variable">'.($text_variable_name ?? '').'</label>
            <input id="variable" type="text" name="variable" placeholder="'.($text_variable_name ?? '').'" value="'.$text_variable['variable'].'" pattern="^\S+$" required">
            <input type="hidden" name="rowID" value="'.$text_variable['rowID'].'" readonly>
        ';

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

$view .= '<div class="content-block tab-content">
        <div class="form responsive-width-100">
            <label for="">'.$general_created.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_created.'" value="'.getRelativeTime($text_variable['created']).'" readonly>
            <label for="">'.$general_createdby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_createdby.'" value="'.$text_variable['createdby'].'" readonly>
            <label for="productcode">'.$general_updated.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updated.'" value="'.getRelativeTime($text_variable['updated']).'" readonly>
            <label for="productcode">'.$general_updatedby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updatedby.'" value="'.$text_variable['updatedby'].'" readonly>
        </div>
    </div>';
$view .= '</form>';


$view .= '
<div class="content-block">
    <button class="btn2" onClick="addNewRow()" > + </button>
    <form action="" id="update" method="post"></form>
    <form action="" id="new" method="post"></form>

    <div class="table">
        <table>
            <thead>
                <tr>
                    <th>'.($text_variable_translation_languagekey ?? '').'</th>
                    <th>'.($text_variable_translation_translation ?? '').'</th>
                    <th>'.$general_created.'</th>
                    <th>'.$general_actions.'</th>
                </tr>
            </thead>
            <tbody id="tableBody">
            ';

            if (empty($text_variable_translations)){
                $view .= '
             
                <tr>
                    <td colspan="8" style="text-align:center;">'.($message_no_text_variables ?? '').'</td>
                </tr>';
            }
            else {
                foreach ($text_variable_translations as $translation){
                $view .= '
                
                <tr>  
                    <td>    
                     <select form="update" id="language" name="item['.$translation['rowID'].'][language_key]">';
                        foreach ($supportedLanguages as $language){
                        $view .='<option value="'.$language.'" '.(($translation['language_key'] == $language)?' selected':'').'>'.$language.'</option>';
                    }   
           $view .='</select></td>
                    <td><textarea form="update" type="text" name="item['.$translation['rowID'].'][translation]" placeholder="'.($text_variable_translation_translation ?? '').'" style="width: 100%;height: 150px;">'.$translation['translation'].'</textarea></td>
                    <td>'.getRelativeTime($translation['created']).'</td>
                    <td><input form="update" type="submit" name="update" value="&" class="btn"></td>
                    <input form="update" type="hidden" name="item['.$translation['rowID'].'][rowID]" value="'.$translation['rowID'].'" readonly>
                    <input form="update" type="hidden" name="item['.$translation['rowID'].'][variable_ID]" value="'.$text_variable['rowID'].'" readonly>
                </tr>
                </form>';
                }
            }
$view .= ' 
            </tbody>
        </table>
        
        <script>
            let rowCounter = 1;

            function addNewRow() {
            rowCounter++;
            const tbody = document.getElementById(\'tableBody\');
            const newRow = document.createElement(\'tr\');
            
            newRow.innerHTML = `
                    <td><select form="new" id="language" name="language_key">';
                        foreach ($supportedLanguages as $language){
                            $view .= '<option value="'.$language.'">'.$language.'</option>';
                        } 
            $view .='</select>
                    </td>
                    <td><textarea form="new" type="text" name="translation" placeholder="'.($text_variable_translation_translation ?? '').'" style="width: 100%;height: 150px;"> </textarea></td>
                    <td><input form="new" type="submit" name="add" value="+" class="btn"></td>
                    <input form="new" type="hidden" name="rowID" value="" readonly>
                    <input form="new" type="hidden" name="variable_ID" value="'.$text_variable['rowID'].'" readonly>
            `;
            
            tbody.appendChild(newRow);
            }
        </script>
    </div>
</div>
';



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