<?php
session_start();
ob_start();

require_once './config.php';
require_once './_pdo.php';

require_once './config.php';
require_once './src/D2Functions.php';
require_once './src/D2ByteReader.php';
require_once './src/D2BitReader.php';

//error_reporting(E_ALL);
set_time_limit(-1);
ini_set('max_input_time', '-1');
ini_set('max_execution_time', '0');

define('DB_FILE', $_SESSION['modname'] . ".db");
try {
    PDO_Connect("sqlite:" . DB_FILE);
} catch (Exception $e) {
    echo "Connection error: " . $e->getMessage();
}

$query = "SELECT Id,LevelName FROM levels WHERE Name != 'Expansion' AND Name != ''";
$levels = PDO_FetchAssoc($query);

$query = "SELECT * FROM levels WHERE Name != 'Expansion' AND Name != ''";
$levelsAll = PDO_FetchAll($query);

$query = "SELECT Id,Name FROM lvlwarp";
$lvlwarp = PDO_FetchAssoc($query);

$query = "SELECT monstats.Id, strings.String AS Name
FROM monstats
LEFT JOIN strings ON monstats.NameStr = strings.Key;";
$monstats = PDO_FetchAssoc($query);

//ddump($monstats);


$query = "SELECT LevelName,Vis0,Vis1,Vis2,Vis3,Vis4,Vis5,Vis6,Vis7 FROM levels WHERE Name != 'Expansion' AND Name != ''";
$res = PDO_FetchAll($query);

$output = [];

foreach ($res as $key => $item) {
    $newItem = [];
    $newItem['LevelName'] = $item['LevelName'];  // Copy the LevelName to new item
    foreach ($levelsAll[$key] as $levelsKey => $levelsValue) {
        $newItem[$levelsKey] = isset($monstats[$levelsValue]) ? $monstats[$levelsValue] : $levelsValue;
    }


    $foundLevels = [];  // Store found level names to avoid duplicates

    foreach ($item as $subKey => $subItem) {
        // Check if the key starts with 'Vis', has a corresponding level, is non-empty, and is not a duplicate
        if (strpos($subKey, 'Vis') === 0 && isset($levels[$subItem]) && $levels[$subItem] !== '' && !in_array($levels[$subItem], $foundLevels)) {
            $newItem[$subKey] = $subItem;
            $foundLevels[] = $levels[$subItem];  // Add to found levels
        }
    }
    $output[] = array_filter($newItem);  // Add the modified item to the output array
}


unset($output[0]);
?>


<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Level Viz/Warp Editor</title>
        <link rel="stylesheet" href="/res/bootstrap.min.css">
        <script src="/res/jquery-3.5.1.min.js"></script>
        <script src="/res/popper.min.js"></script>
        <script src="/res/bootstrap.min.js"></script>
        <style>
            .viz {
                background-color: #fafafa;
            }
            .warp {
                background-color: #eef;
            }
        </style>

    </head>

    <body>
        <table class="table table-bordered table-striped">
            <thead class="thead-dark">
                <tr>
                    <th>Id</th>
                    <th>LevelName</th>
                    <th>Name</th>
                    <?php for ($i = 0; $i <= 7; $i++): ?>
                        <th>Vis<?php echo $i; ?></th>
                    <?php endfor; ?>
                    <?php for ($i = 0; $i <= 7; $i++): ?>
                        <th>Warp<?php echo $i; ?></th>
                    <?php endfor; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($output as $level): ?>
                    <tr>
                        <td><?php echo $level['Id']; ?></td>
                        <td><?php echo $level['LevelName']; ?></td>
                        <td><?php echo $level['Name']; ?></td>
                        <?php for ($i = 0; $i <= 7; $i++): ?>
                            <td class="viz">
                                <select name="Vis<?php echo $i; ?>" data-id="<?php echo $level['Id']; ?>">
                                    <?php foreach ($levels as $key => $value): ?>
                                        <option value="<?php echo $key; ?>" <?php if (isset($level["Vis$i"]) && $level["Vis$i"] == $key) echo 'selected'; ?>>
                                            <?php echo "$key - $value"; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        <?php endfor; ?>

                        <?php for ($i = 0; $i <= 7; $i++): ?>
                            <td class="warp">
                                <select name="Warp<?php echo $i; ?>" data-id="<?php echo $level['Id']; ?>">
                                    <?php foreach ($lvlwarp as $key => $value): ?>
                                        <option value="<?php echo $key; ?>">
                                            <?php echo "$key - $value"; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        <?php endfor; ?>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <script>
            $("select[name^='Vis'], select[name^='Warp']").change(function () {
                var levelId = $(this).data('id');
                var selectName = $(this).attr('name');
                var selectedValue = $(this).val();

                // For demonstration purposes, console log the data that will be posted
                console.log(`Level ID: ${levelId}, ${selectName}: ${selectedValue}`);

                // Define the data to be sent
                var dataToSend = {
                    'levelId': levelId,
                    'selectName': selectName,
                    'selectedValue': selectedValue
                };

                // Send the POST request
                $.post("LevelsEditor_Process.php", dataToSend)
                        .done(function (response) {
                            console.log("Data sent successfully");
                            console.log("Server Response: ", response); // Logging server's response for debugging
                        })
                        .fail(function () {
                            console.log("Error sending data");
                        });
            });
        </script>
    </body>
</html>