<?php

require '../../../db.php';
require '../../auth/auth_functions.php';
require '../../helper_functions/data_request.php';

if (!currentUserHasAccess($pdo, 'admin_panel', 'write')) {
    if (isset($_SESSION['userid'])) {
        echo "Access denied.";
        if (!headers_sent()) {
            header( "refresh:5;url=../../dashboard.php" );
        }
        exit();
    }else {
        if (!headers_sent()) {
            header("Location: ../../login.php");
        }
        exit();
    }
}

function parseConfigFile($configData) {
    $sections = [];
    $lines = explode("\n", $configData);
    $currentSection = null;

    foreach ($lines as $line) {
        $line = trim($line);

        if (preg_match('/\[(.*)\]/', $line, $matches)) {
            $currentSection = $matches[1];
            $sections[$currentSection] = [];
        } elseif ($currentSection && strpos($line, '=') !== false) {
            $parts = explode('=', $line, 2);
            if (count($parts) === 2) {
                preg_match('/(\d+)\\\\/', $parts[0], $numMatches);
                if (isset($numMatches[1])) {
                    $number = $numMatches[1];
                    $key = str_replace($number . '\\', '', $parts[0]);
                    if (!isset($sections[$currentSection][$number])) {
                        $sections[$currentSection][$number] = [];
                    }
                    $sections[$currentSection][$number][$key] = trim($parts[1], '"');
                }
            }
        }
    }

    return $sections;
}

function generateConfigContent($sections) {
    $output = '';
    
    foreach ($sections as $section => $groups) {
        $output .= "[$section]\n";
        foreach ($groups as $number => $entries) {
            foreach ($entries as $key => $value) {
                $output .= "$number\\$key=$value\n";
            }
        }
        $output .= "\n";
    }

    return $output;
}

$smsioConfig = fetchData('hardware_configs', ['hardware' => 'smsio']);

$configFile = $smsioConfig[0]['base_config'];
$sections = parseConfigFile($configFile);
$saved = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['filename'])) {
    $filename = $_POST['filename'] . '.dat';
    header('Content-Type: text/plain');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    foreach ($sections as $section => &$groups) {
        foreach ($groups as $number => &$entries) {
            foreach ($entries as $key => &$value) {
                if (isset($_POST[$section][$number][$key])) {
                    $value = $_POST[$section][$number][$key];
                }
            }
        }
    }

    $config = generateConfigContent($sections);

    // need to add links 
    $hwProperty = 1;
    $hardware = 'smsio';

    $configFileD = [
        'filename'=>$filename,
        'config'=>$config,
        'property'=>$hwProperty,
        'hardware'=>$hardware,
    ];

    insertData('config_files', $configFileD);

    echo $config;
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Config</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        fieldset {
            margin-bottom: 20px;
            border: 1px solid #ccc;
            padding: 10px;
        }
        legend {
            font-weight: bold;
        }
        .collapsible {
            background-color: #f9f9f9;
            cursor: pointer;
            padding: 10px;
            width: 100%;
            border: none;
            text-align: left;
            outline: none;
            font-size: 15px;
        }
        .content {
            padding: 0 18px;
            display: none;
            overflow: hidden;
            background-color: #f1f1f1;
            margin-bottom: 10px;
        }
        label {
            display: block;
            margin-bottom: 10px;
        }
        input[type="text"] {
            width: 100%;
            padding: 8px;
            margin-top: 5px;
            box-sizing: border-box;
        }
        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: black;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .success {
            color: green;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <h1>Configuration</h1>
    <form method="POST">
        <label>
            File Name:
            <input type="text" name="filename" required placeholder="Enter filename without extension">
        </label>
        <?php foreach ($sections as $section => $groups): ?>
            <fieldset>
                <legend><?php echo htmlspecialchars($section); ?></legend>
                <?php foreach ($groups as $number => $entries): ?>
                    <button type="button" class="collapsible"><?php echo "Group $number"; ?></button>
                    <div class="content">
                        <?php foreach ($entries as $key => $value): ?>
                            <label>
                                <?php echo htmlspecialchars($key); ?>:
                                <input type="text" name="<?php echo htmlspecialchars($section); ?>[<?php echo htmlspecialchars($number); ?>][<?php echo htmlspecialchars($key); ?>]" value="<?php echo htmlspecialchars(html_entity_decode($value)); ?>">                            </label>
                        <?php endforeach; ?>
                    </div>
                <?php endforeach; ?>
            </fieldset>
        <?php endforeach; ?>
        <button type="submit">Download</button>
    </form>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            var coll = document.getElementsByClassName("collapsible");
            for (var i = 0; i < coll.length; i++) {
                coll[i].addEventListener("click", function() {
                    this.classList.toggle("active");
                    var content = this.nextElementSibling;
                    if (content.style.display === "block") {
                        content.style.display = "none";
                    } else {
                        content.style.display = "block";
                    }
                });
            }
        });
    </script>
</body>
</html>
