<?php
// Function to delete a file
if (isset($_POST['delete_file'])) {
    $file_to_delete = $_POST['delete_file'];
    if (file_exists($file_to_delete) && pathinfo($file_to_delete, PATHINFO_EXTENSION) == 'json') {
        unlink($file_to_delete);
    }
    // Redirect to prevent re-submission on refresh
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// Function to create a new session file
if (isset($_POST['new_session_name'])) {
    $new_session_name = trim($_POST['new_session_name']);
    if (!empty($new_session_name)) {
        // Sanitize to create a valid filename, remove .json if user added it
        $filename_base = preg_replace('/\.json$/i', '', $new_session_name);
        $filename = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $filename_base) . '.json';

        if (!file_exists($filename)) {
            // Create an empty but valid JSON file as a placeholder
            file_put_contents($filename, '{}');
        }
        // Redirect to show the new file in the list and avoid form resubmission
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
}

$files = scandir('.');
$json_files = array_filter($files, function ($file) {
    return pathinfo($file, PATHINFO_EXTENSION) == 'json';
});

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sesiones Co.Laborando</title>
    <link rel="stylesheet" href="js/jquery-ui.min.css">
    <style>
        body {
            font-family: sans-serif;
        }

        table {
            border-collapse: collapse;
            width: 50%;
            margin-top: 20px;
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .delete-btn,
        .crear-btn {
            background-color: #f44336;
            color: white;
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .delete-btn:hover {
            background-color: #da190b;
        }

        a {
            text-decoration: none;
            color: #007BFF;
        }

        a:hover {
            text-decoration: underline;
        }

        /* jQuery UI Dialog styles from colaborando2.php */
        .ui-dialog-titlebar {
            background-color: crimson;
            color: white;
        }

        .ui-widget.ui-widget-content {
            border-color: crimson;
            border-width: 5px;
        }

        .ui-dialog .ui-dialog-content {
            font-size: 16px;
            font-weight: bold;
            text-align: center;
        }

        .ui-dialog .ui-dialog-buttonpane button {
            font-size: 17px;
        }
    </style>
</head>

<body>

    <h2>Sesiones de Co.Laborando</h2>

    <div style="margin-bottom: 20px; padding: 10px; border: 1px solid #ccc; background-color: #f9f9f9;">
        <h3>Crear Nueva Sesión</h3>
        <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="display:inline-block;">
            <input type="text" name="new_session_name" placeholder="Nombre de la nueva sesión" size="40" required>
            <button type="submit" class="crear-btn">Crear Sesión</button>
        </form>
    </div>

    <p>
        <a href="<?php echo $_SERVER['PHP_SELF']; ?>">Refrescar lista</a>
    </p>

    <table style="width:500px">
        <thead>
            <tr>
                <th style="width:80%">Sesión</th>
                <th style="width:20%"> </th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($json_files)): ?>
                <tr>
                    <td colspan="2">No se encontraron archivos JSON.</td>
                </tr>
            <?php else: ?>
                <?php foreach ($json_files as $file): ?>
                    <?php
                    $session_name = basename($file, '.json');
                    $is_new = filesize($file) <= 2; // Check for empty file {}
                    $link = "colaborando2.php?n=" . urlencode($session_name);
                    if ($is_new) {
                        $link .= "&NS=1";
                    }
                    ?>
                    <tr>
                        <td>
                            <a href="<?php echo $link; ?>" target="_blank">
                                <?php echo htmlspecialchars($session_name); ?>
                                <?php if ($is_new): ?>
                                    <span style="color: #28a745; font-style: italic;"> (Nueva, haz clic para inicializar)</span>
                                <?php endif; ?>
                            </a>
                        </td>
                        <td>
                            <form class="delete-form" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="display:inline;">
                                <input type="hidden" name="delete_file" value="<?php echo htmlspecialchars($file); ?>">
                                <button type="button" class="delete-btn" data-file="<?php echo htmlspecialchars($file); ?>">Eliminar</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

    <script src="js/jquery-3.5.1.min.js"></script>
    <script src="js/jquery-ui.min.js"></script>

    <script>
        $(function() {
            // Custom confirm dialog function
            function customConfirm(message, callback) {
                $('<div></div>').html(message).dialog({
                    modal: true,
                    title: 'Confirmar',
                    resizable: false,
                    width: 400,
                    buttons: {
                        "Sí, eliminar": function() {
                            $(this).dialog('close');
                            if (callback) callback(true);
                        },
                        "Cancelar": function() {
                            $(this).dialog('close');
                            if (callback) callback(false);
                        }
                    },
                    close: function() {
                        // Remove the dialog from the DOM when closed
                        $(this).dialog('destroy').remove();
                    }
                });
            }

            // Attach click handler to delete buttons
            $('.delete-btn').on('click', function(e) {
                e.preventDefault(); // Stop the default button action

                var button = $(this);
                var form = button.closest('form');
                var fileName = button.data('file');
                var message = '¿Estás seguro de que quieres eliminar el archivo: <br><b>' + fileName + '</b>?';

                customConfirm(message, function(confirmed) {
                    if (confirmed) {
                        form.submit(); // If confirmed, submit the form
                    }
                });
            });
        });

        // Refresca la página automáticamente cuando la pestaña vuelve a estar visible.
        // Esto asegura que la lista de sesiones esté siempre actualizada.
        document.addEventListener('visibilitychange', function() {
            if (document.visibilityState === 'visible') {
                window.location.reload();
            }
        });
    </script>
</body>

</html>