<?php
ini_set('max_execution_time', 300);
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$ip = $_SERVER['HTTP_HOST'];
$baseUrl = $protocol.$ip;

$root = $_SERVER['DOCUMENT_ROOT'];
if (empty($root))
{
    $root = (__DIR__);
}

$root = str_replace("\\","/",$root);
$dir = (dirname(__FILE__));
$dir = str_replace("\\","/",$dir);

// get Base Directory
$baseDir = $dir;
for ($i=0;$i<10;$i++)
{
    $testDir = dirname($baseDir);
    $testDir = str_replace("\\","/",$testDir);
    
    $baseDir = str_replace("\\","/",$baseDir);
    if ($baseDir == $root)
    {
        break;
    }
    if ($testDir == $root)
    {
        break;
    }
    $baseDir = dirname($baseDir);
}
$currentDirectory = getcwd();

include_once $baseDir.'/common/connect.php';
$conn = dbConnection();

if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
    if (isset($_POST['upload_program']))
    {
        $uploadProgram = $_POST['upload_program'];
    }
    // Check if file was uploaded without errors
    if (isset($_FILES['excel_file']) && $_FILES['excel_file']['error'] == 0) 
    {
        $uploadedFile = $_FILES['excel_file']['tmp_name'];
        $destination = 'uploads/' . basename($_FILES['excel_file']['name']);

// Move the uploaded file to the designated folder
        if (move_uploaded_file($uploadedFile, $destination)) 
        {
            $filePath = $currentDirectory."/".$destination;
            try
            {
            // path to python.exe on the current server
                $pythonPath = "E:/python39/python.exe";
                $pythonFile = $uploadProgram;
                $pythonParms = '';
                $pythonParms = $conn['host'].' '.$conn['user'].' '.$conn['pwd'].' '.$conn['dbase'].' "'.$filePath.'" "'.$filter.'"';
                
                $command= escapeshellcmd($pythonPath." ".$pythonFile." ".$pythonParms);
                $output = shell_exec($command);
                error_log("upload.php-".$output);
                if (substr($output,0,2) == "FA")
                {
                    $response = $output;
                }
                if (substr($output,0,2) == "OK")
                {
                    $response = "OK  -<h2>Upload successful!</h2>";
                }
                if ($output == "")
                {
                    $response = ("FAIL-Connection Error".$pythonPath." ".$pythonFile." ".$pythonParms." ".$output);
                }
            }
            catch (Exception $e)
            {
                 $response = "FAIL-Confirm-".$e;
            }
        } 
        else 
        {
            $response = "Error moving the uploaded file.";
        }
    } 
    else 
    {
        $response = "Error uploading the file.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Excel File</title>
    <script src="../../../js/libs/xlsx/xlsx.full.min.js"></script>
    <style>
        :root {
            --primary-dark-purple: #4a3b4f;
            --header-gradient-start: #3a2d3f;
            --header-gradient-end: #5c4a61;
            --form-bg: #f4f4f7;
            --input-focus-bg: #f0e6c8;
            --text-light: #ffffff;
            --text-dark: #333333;
            --border-color: #d1d1d1;
        }

        .ok 
        {
            background-color: green;
            color: white;
        }
        .error 
        {
            background-color: red;
            color: white;
        }
        
        .upload-form-container 
        {
            background-color: var(--form-bg);
            background-image: url("data:image/svg+xml,%3Csvg width='600' height='600' viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' stroke='%23e5e5e5' stroke-width='1.5'%3E%3Cpath d='M -50,150 C -25,150 0,100 50,100 C 100,100 125,150 150,150 C 175,150 200,100 250,100' /%3E%3Cpath d='M -50,120 C -25,120 0,70 50,70 C 100,70 125,120 150,120 C 175,120 200,70 250,70' /%3E%3C/g%3E%3C/svg%3E");
            background-repeat: no-repeat;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
        }

        html, body 
        {
            height: 100%;
        }

        dialog 
        {
            border: none; /* Remove default border */
            border-radius: 8px;
            padding: 20px;
            height: 80%;
            width: 50%;
        }

        .close-button 
        {
            cursor: pointer;
            color: var(--text-light);
            font-size: 18px;
            float: right; /* Position close button */
        }

        .dialog-content 
        {
            margin-top: 5px;
        }
        
        .main-panel 
        {
            width: 100%;
            height:100%
            max-width: 550px;
            border-radius: 2px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            display: flex;
            flex-direction: column;
        }

        /* --- Header --- */
        .header 
        {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 20px;
            background: linear-gradient(90deg, var(--header-gradient-start), var(--header-gradient-end));
            color: var(--text-light);
        }

        .logo 
        {
            display: flex;
            align-items: center;
            font-weight: bold;
            font-size: 1.1em;
        }

        .logo-icon {
            font-weight: 900;
            font-style: italic;
            border: 2px solid var(--text-light);
            padding: 2px 5px;
            margin-right: 10px;
            transform: skewX(-10deg);
        }

        .header-controls {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .logon-button, .admin-button {
            background: none;
            border: none;
            color: var(--text-light);
            font-size: 0.9em;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .admin-icon {
            width: 24px;
            height: 24px;
            border: 1.5px solid var(--text-light);
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8em;
        }

        /* --- Form Body --- */
        .form-group {
            display: flex;
            align-items: center;
            border-bottom: 1px solid var(--border-color);
            padding: 10px 10px;
            transition: background-color 0.3s ease;
        }

        .form-group.focused {
            background-color: var(--input-focus-bg);
        }

        .form-group label {
            flex-shrink: 0;
            width: 70px; /* Adjusted width */
            color: var(--text-dark);
            font-size: 1em; /* Responsive font size */
        }

        .form-group input {
            flex-grow: 1;
            border: none;
            background: transparent;
            outline: none;
            font-size: 1.1em;
            padding: 10px 5px;
            color: var(--text-dark);
        }

        .form-group .arrow-icon {
            font-size: 1.5em;
            color: var(--text-dark);
            font-weight: bold;
        }

        #preview {
            margin-top: 5px;
            border: 1px solid #ccc;
            height:80%;
            padding: 5px;
            display: none; /* Initially hidden */
            background-color: #fff; /* Ensure it's visible */
            overflow: auto; /* Handle overflow if content is large */
        }

        /* Additional styles for better layout */
        .login-form-container {
            display: flex;
            flex-direction: column;
            gap: 20px; /* Space between input elements and preview */
        }
        
        #alert
        {
            position: fixed;
            visibility: hidden;
            transform: translate(-50%, 0px);
            z-index: 1000;
            width:auto;
            text-align:center;
            background:red;
            color: white;
            font-size: 1.4em;
            font-weight: 800;
            overflow-wrap: break-word;
            box-sizing: border-box;
            position: absolute;
            left: 50%;
            top: 65%;
        }
        
        #alert.show {
            visibility: visible;
            animation: slide-up 5s ease forwards;
        }
        
        @keyframes slide-up {
          0% {
            opacity: 0;
            top: 99%;
          }
          10% {
            opacity: 1;
          }
          90% {
            opacity: 1;
          }
          100% {
            opacity: 0;
            top: 5%;
          }
        }
        
        /* Spinner styles */
        #loading 
        {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1000;
        }

        .spinner 
        {
            border: 8px solid #f3f3f3; /* Light grey */
            border-top: 8px solid #3498db; /* Blue */
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin 
        {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div id="mainDialog" class="main-panel">
        <div class="dialog-content">
            <form id="uploadForm" action="" method="post" enctype="multipart/form-data">
                <div class="main-panel">
                    <header class="header">
                        <div class="logo"><span>VANTEC</span></div>
                        <div class="header-controls">
                            <div class="admin-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                                    <circle cx="12" cy="7" r="4"></circle>
                                </svg>
                            </div>
                            <span class="close-button" id="closeDialog">&times;</span>
                        </div>
                    </header>
                    <main id = "upload-form-container" class="upload-form-container">
                        <div class="form-group" id="user-group">
                            <h2 id="uploadFunction">upload function</h2>
                        </div>
                        <div class="form-group" id="user-group">
                            <input type="text" id="uploadProgram" name="upload_program" value="" readonly="readonly" />
                        </div>
                        <div class="form-group" id="user-group">
                            <label for="excelFile">Select</label>
                            <span class="arrow-icon">&gt;</span>
                            <input type="file" id="excelFile" name="excel_file" accept=".xls,.xlsx" required>
                        </div>
                        <input type="submit" value="Submit Upload">
                        <div id="preview"></div>
                    </main>
                </div>
            </form>
        </div>
    </div>
    
    <div id="loading">
        <div class="spinner"></div>
    </div>
    
    <div id="alert" class="alert">
    </div>
    <script>
    let uploadFunction = ""
    const acceptedTypes = '.xlsx,.xls';
    const dialog = document.getElementById('mainDialog');
    const closeDialogButton = document.getElementById('closeDialog');
// Close the dialog
    closeDialogButton.addEventListener('click', () => 
    {
        dialog.close(); // Close the dialog
    });
    
    const form = document.getElementById('uploadForm');
    form.addEventListener('submit', () =>
    {
        // Show the loading spinner
        document.getElementById('loading').style.display = 'block';
    });
    
    window.onload = function() 
    {
//        dialog.showModal();
        var href = (window.location.href).toLowerCase();
    
// look for initial Upload program
        var s = href.indexOf("function=");
        if (s > 0)
        {
            s = s+9;
            var e = href.indexOf("&",s);
            if (e < s)
                e = href.length;
            var l = e-s;
            uploadFunction = href.substring(s,e);
            document.getElementById("uploadFunction").innerHTML = uploadFunction;
            const fileInput = document.getElementById('excelFile');
            fileInput.setAttribute('accept', acceptedTypes);
        }
        var s = href.indexOf("program=");
        if (s > 0)
        {
            s = s+8;
            var e = href.indexOf("&",s);
            if (e < s)
                e = href.length;
            var l = e-s;
            uploadProgram = href.substring(s,e);
            document.getElementById("uploadProgram").value = uploadProgram;
        }
    }
    
    document.getElementById('excelFile').addEventListener('change', function(event) 
    {
        const file = event.target.files[0];
        if (file && !file.name.includes(uploadFunction)) 
        {
            showMessage('Please select a file that contains '+uploadFunction+' in its name.');
            document.getElementById('excelFile').value = '';
        }
        else
        {
            const reader = new FileReader();
            reader.onload = function(e) 
            {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];

                // Convert to HTML
                const html = XLSX.utils.sheet_to_html(worksheet);
                document.getElementById('preview').innerHTML = html;
                document.getElementById('preview').style.display = 'flex';
            };
            reader.readAsArrayBuffer(file);
        }
    });
    
    function showMessage(message) 
    {
        if (message !== "" && message !== undefined) 
        {
            try
            {
                var a = document.getElementById("alert");
                a.style.position = 'absolute';
                if (message.length > 50)
                    a.style.top = '65%';
                else
                    a.style.top = '70%';
                setTimeout(function(){ a.className = a.className.replace("show", ""); }, 5000);
                a.innerHTML=message;
                if (message.substr(0,2) == "FA")
                {
                    a.style.backgroundColor = "red";
                }
                else if(message.substr(0,2) == "OK")
                {
                    a.style.backgroundColor = "green";
                }
                a.className = "show";
            }
            catch(e)
            {
            }
        }
    }
    </script>
    <script>
        window.top.window.showMessage(<?php echo "'".$response."'"; ?>);
    </script>
</body>
</html>