<?php 
defined(page_security_key) or exit;

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

if ($create_allowed === 1 && $_POST){
 
    $log_results = [];
    $tableName = json_decode($_POST['table'],true);   
    $contents = json_decode($_POST['data'],true);

    
    foreach ($contents as $content){

        switch ($tableName) {

            case 'text_variables':
                //CHECK IF VARIABLE EXISTS
                $text_variable = ioServer('/v2/translations/variable='.$content['variable'],'');
                if (!empty($text_variable)){$text_variable = json_decode($text_variable,true);}else{$text_variable = null;}

                //IF NO ERRORS PROCES IT
                if (is_array($text_variable)){     

                    if (count($text_variable) == 0){
                        //VARIABLE NOT FOUND -> CREATE
                        $payload = json_encode(array("variable" => $content['variable']), JSON_UNESCAPED_UNICODE);
                        //API call
                        $text_variable_new = ioServer('/v2/translations',$payload);
                        //returns results
                        $text_variable_new   = json_decode($text_variable_new  ,true);
                        //Provide feedback
                        $log_results[$content['variable']]['rowID'] = $text_variable_new['rowID'].' created';
                    } 

                    $text_variable = $text_variable[0] ?? 'new';
                    //VARIABLE ROWID 
                    $text_variable_rowid = ($text_variable != 'new') ? $text_variable['rowID'] : $text_variable_new['rowID'];
                    
                    foreach ($content as $key => $var){
                        
                        if ($var != $content['variable']){
                            $language_key = strtoupper($key);

                            //check if variable_id and language_key combination already exists
                            $text_translation = ioServer('/v2/translations_details/variable_ID='.$text_variable_rowid.'&language_key='.$language_key,'');
                            if (!empty($text_translation)){$text_translation = json_decode($text_translation,true);}else{$text_translation = null;}
                            
                            
                            if (count($text_translation) == 0){
                                //TRANSLATION NOT FOUND ->CREATE
                                $payload = json_encode(array("variable_ID" => $text_variable_rowid, "language_key" => $language_key, "translation" => $var), JSON_UNESCAPED_UNICODE);
                                $text_translation_new = ioServer('/v2/translations_details',$payload);
                                $text_translation_new = json_decode($text_translation_new  ,true);
                                //Provide feedback
                                $log_results[$content['variable']][$language_key] = $text_translation_new['rowID'].' created';
                            }
                            elseif(count($text_translation) > 0){
                                
                                $text_translation = $text_translation[0];
                                //TRANSLATION FOUND -> UPDATE
                                $payload = json_encode(array("rowID" => $text_translation['rowID'] , "translation" => $var), JSON_UNESCAPED_UNICODE);
                                $text_translation_update = ioServer('/v2/translations_details',$payload);
                                $text_translation_update  = json_decode($text_translation_update ,true);
                                //Provide feedback
                                $log_results[$content['variable']][$language_key] = $text_translation['rowID'].' updated';

                            } else {
                                $log_results[$content['variable']][$language_key] = 'not updated';
                            }

                        }
                    }
                } else {
                    $log_results[$content['variable']] = 'error';
                }
                break;
            
            case 'dealers':
                
                //SEND CONTENT TO API
                $payload = json_encode($content, JSON_UNESCAPED_UNICODE);
                //API call
                $api_call = ioServer('/v2/dealers',$payload);
                //returns results
                $api_response   = json_decode($api_call ,true);
                //Provide feedback
                $log_results[$content['name']] = $api_response['rowID'].' '.$api_response['status'];

                break;
        }
        
    }
    
    print_r($log_results);   
    return $log_results; 
} 
template_header('Uploader', 'uploader', 'manage');

$view ='
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        h1, h2 {
            color: #2c3e50;
        }
        textarea {
            width: 100%;
            min-height: 150px;
            margin-bottom: 15px;
            padding: 8px;
            border: 1px solid #ddd;
        }
        .btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            cursor: pointer;
            font-size: 16px;
            border-radius: 4px;
        }
        .btn:hover {
            background-color: #2980b9;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
            position: sticky;
            top: 0;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .table-container {
            max-height: 500px;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        .info {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 4px;
        }
        .controls {
            margin: 15px 0;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
    </style>

    <div class="container">
        <h1>Excel Data Processor</h1>
        
        <div class="info">
            Copy data from Excel and paste it into the textarea below. 
            Use Ctrl+C in Excel and Ctrl+V here to preserve the tab/column formatting.
        </div>
        
        <div>
            <textarea id="excelData" placeholder="Paste Excel data here..."></textarea>
            <button type="button" id="convertBtn" class="btn">Convert to Table</button>
        </div>
        
        <div id="tableOutput" style="display:none;">
            <h2>Table Preview</h2>
            <div class="controls">
                <select name="table_name" id="table_name" class="form-control" required>
                    <option value="text_variables">'.($menu_translations ?? 'Translations').'</option>
                    <option value="dealers">'.($menu_dealers ?? 'Dealers').'</option>
                </select>
                <button id="processDataBtn" class="btn">Process Data</button>
                <button id="downloadCsvBtn" class="btn">Download as CSV</button>
            </div>
            <div class="table-container">
                <table id="dataTable">
                    <!-- Table will be inserted here -->
                </table>
            </div>
            
            <div id="processingResults" style="display:none;">
                <h2>Processing Results</h2>
                <div id="resultsContent"></div>
            </div>
        </div>
    </div>
    
    <script>
        document.addEventListener(\'DOMContentLoaded\', function() {
            const convertBtn = document.getElementById(\'convertBtn\');
            const excelData = document.getElementById(\'excelData\');
            const tableOutput = document.getElementById(\'tableOutput\');
            const dataTable = document.getElementById(\'dataTable\');
            const processDataBtn = document.getElementById(\'processDataBtn\');
            const processingResults = document.getElementById(\'processingResults\');
            const resultsContent = document.getElementById(\'resultsContent\');
            const downloadCsvBtn = document.getElementById(\'downloadCsvBtn\');
            
            // Convert pasted Excel data to HTML table
            convertBtn.addEventListener(\'click\', function() {
                const data = excelData.value.trim();
                if (!data) {
                    alert(\'Please paste some data first.\');
                    return;
                }
                
                // Split by newlines to get rows
                const rows = data.split(/\r?\n/);
                let tableHtml = \'\';
                
                rows.forEach((row, rowIndex) => {
                    // Split by tabs to get cells
                    const cells = row.split(\'\t\');
                    
                    if (rowIndex === 0) {
                        // Create header row
                        tableHtml += \'<thead><tr>\';
                        cells.forEach(cell => {
                            tableHtml += `<th>${cell}</th>`;
                        });
                        tableHtml += \'</tr></thead><tbody>\';
                    } else {
                        // Create data rows
                        tableHtml += \'<tr>\';
                        cells.forEach(cell => {
                            tableHtml += `<td>${cell}</td>`;
                        });
                        tableHtml += \'</tr>\';
                    }
                });
                
                tableHtml += \'</tbody>\';
                dataTable.innerHTML = tableHtml;
                tableOutput.style.display = \'block\';
            });
            
            // Process the data using AJAX
            processDataBtn.addEventListener(\'click\', function() {
                // Collect table data as array of arrays (simpler format)
                const tableData = [];
                const headers = [];
                
                // Get headers
                const headerCells = dataTable.querySelectorAll(\'thead th\');
                headerCells.forEach(cell => {
                    headers.push(cell.textContent);
                });
                
                // Get rows
                const rows = dataTable.querySelectorAll(\'tbody tr\');
                rows.forEach(row => {
                    const rowData = {};
                    const cells = row.querySelectorAll(\'td\');
                    
                    cells.forEach((cell, index) => {
                        if (index < headers.length) {
                            rowData[headers[index]] = cell.innerHTML;
                        }
                    });
                    
                    tableData.push(rowData);
                });
                // GET TABLE NAME
                const tableName = document.getElementById(\'table_name\').value;
                
                // Use standard form submission approach instead of JSON
                const form = new FormData();
                form.append(\'table\', JSON.stringify(tableName));
                form.append(\'data\', JSON.stringify(tableData));
                
                fetch(window.location.href, {
                    method: \'POST\',
                    body: form
                })
                .then(response => response.text())
                .then(data => {
                    processingResults.style.display = \'block\';
                    resultsContent.innerHTML = data;
                })
                .catch(error => {
                    console.error(\'Error:\', error);
                    alert(\'Error processing data: \' + error);
                });
            });
            
            // Download as CSV
            downloadCsvBtn.addEventListener(\'click\', function() {
                const rows = dataTable.querySelectorAll(\'tr\');
                const csvContent = [];
                
                rows.forEach(row => {
                    const rowData = [];
                    const cells = row.querySelectorAll(\'th, td\');
                    
                    cells.forEach(cell => {
                        // Properly escape cells for CSV format
                        let value = cell.textContent;
                        value = value.replace(/"/g, \'""\'); // Double quotes need to be escaped with double quotes
                        rowData.push(`"${value}"`);
                    });
                    
                    csvContent.push(rowData.join(\',\'));
                });
                
                const csvString = csvContent.join(\'\n\');
                const blob = new Blob([csvString], { type: \'text/csv;charset=utf-8;\' });
                const url = URL.createObjectURL(blob);
                const link = document.createElement(\'a\');
                link.setAttribute(\'href\', url);
                link.setAttribute(\'download\', \'exported_data.csv\');
                link.style.visibility = \'hidden\';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            });
        });
    </script>
';

//Output
echo $view;

template_footer();
?>