<?php

if ($_GET['refresh_updates'] ?? false) {
    // Delete the update_plugins transient to force a refresh of plugin update information
    delete_site_transient('update_plugins');

    // Redirect to the same page without the 'refresh_updates' query parameter
    echo '<script>window.location.href = "' . remove_query_arg('refresh_updates') . '";</script>';
    exit;
}

?>

<h2>Dashboard</h2>

<div style="display: flex; flex-wrap: wrap; gap: 20px;">
    <div style="flex: 1; min-width: 300px;">
        <h3>WordPress Info</h3>

        <table class="widefat fixed" id="plugin-update-table" style="margin-bottom: 1rem;">
            <tbody>
                <tr>
                    <th>PHP Version</th>
                    <td><?= phpversion() ?></td>
                </tr>

                <tr>
                    <th>Installed WP Version</th>
                    <td><?= get_bloginfo('version') ?></td>
                </tr>

                <tr>
                    <th>Latest WP Version</th>
                    <td>
                        <?php
                        // Fetch the latest WordPress version from the API
                        $response = wp_remote_get('https://api.wordpress.org/core/version-check/1.7/');
                        if (! is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                            $data = json_decode(wp_remote_retrieve_body($response), true);
                            if (isset($data['offers'][0]['current'])) {
                                echo esc_html($data['offers'][0]['current']);
                            } else {
                                echo 'Unable to fetch latest version';
                            }
                        } else {
                            echo 'Unable to fetch latest version';
                        }
                        ?>
                    </td>
                </tr>

                <tr>
                    <th>Database Name</th>
                    <td><?= DB_NAME ?></td>
                </tr>

                <tr>
                    <th>Database User</th>
                    <td><?= DB_USER ?></td>
                </tr>

                <tr>
                    <th>Document Root</th>
                    <td><?= $_SERVER["DOCUMENT_ROOT"] ?></td>
                </tr>
            </tbody>
        </table>
    </div>

    <div style="flex: 1; min-width: 300px;">
        <h3>Plugin Updates</h3>

        <table class="widefat fixed striped" id="plugin-update-table" style="margin-bottom: 1rem;">
            <thead>
                <tr>
                    <th>Plugin Name</th>
                    <th>Installed Version</th>
                    <th>Latest Available Version</th>
                </tr>
            </thead>
            <tbody>
                <?php

                $allPlugins = get_plugin_updates();

                if (! empty($allPlugins)) {
                    foreach ($allPlugins as $pluginFile => $pluginData) {
                        echo '<tr>';
                        echo '<td>' . esc_html($pluginData->Name) . '</td>';
                        echo '<td>' . esc_html($pluginData->Version) . '</td>';
                        echo '<td>' . esc_html($pluginData->update->new_version) . '</td>';
                        echo '</tr>';
                    }
                } else {
                    echo '<tr><td colspan="3">All plugins are up to date.</td></tr>';
                }
                ?>
            </tbody>
        </table>

        <a href="?page=mws-backpack&tab=dashboard&refresh_updates=true" class="button">Refresh Updates</a>

        <?php if (! empty($allPlugins)) : ?>
            <button id="copy-updates" class="button">Copy to Clipboard</button>
            <script>
                document.getElementById('copy-updates').addEventListener('click', function () {
                    const rows = document.querySelectorAll('#plugin-update-table tbody tr');
                    let text   = '';
                    rows.forEach(row => {
                        const cells = row.querySelectorAll('td');
                        if (cells.length === 3) {
                            const name             = cells[0].innerText.trim();
                            const installedVersion = cells[1].innerText.trim();
                            const latestVersion    = cells[2].innerText.trim();
                            text += `${name} ${installedVersion} → ${latestVersion}\n`;
                        }
                    });

                    navigator.clipboard.writeText(text).then(() => {
                        alert('Updates list copied to clipboard!');
                    }).catch(err => {
                        alert('Failed to copy: ' + err);
                    });
                });
            </script>
        <?php endif; ?>
    </div>
</div>