<?php

global $wpdb, $backpack;

if (isset($_GET["add"])) {
    $add = true;
} else {
    $add = false;
}

$backpack->fixGPC();

if (isset($_POST['mws_backpack_addedit_task_nonce']) && wp_verify_nonce($_POST['mws_backpack_addedit_task_nonce'], 'mws_backpack_addedit_task_action')) {
    $name     = $_POST['mws_backpack_task_name']     ?? '';
    $type     = $_POST['mws_backpack_task_type']     ?? '';
    $schedule = trim($_POST['mws_backpack_task_schedule']) ?? '';

    if (Cron\CronExpression::isValidExpression($schedule) === false) {
        echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Invalid schedule. Please make sure you are using the correct format.', 'mws-backpack') . '</p></div>';
    } else {
        if ($add) {
            $addTask = $backpack->addTask($name, $type, $schedule);

            if ($addTask) {
                set_transient('mws_backpack_success_message', esc_html__('Task added successfully.', 'mws-backpack'), 60);

                $url = remove_query_arg('add');
                echo '<script>window.location.href = "' . $url . '";</script>';
                exit;
            } else {
                echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Failed to add the task. Please try again.', 'mws-backpack') . '</p></div>';
            }
        } else {
            // Update the existing task
            $taskID = isset($_GET['edit']) ? intval($_GET['edit']) : 0;

            if ($taskID > 0) {
                $updateTask = $backpack->updateTask($taskID, $name, $type, $schedule);

                if ($updateTask !== false) {
                    echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Task updated successfully.', 'mws-backpack') . '</p></div>';
                } else {
                    echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Failed to update the task. Please try again.', 'mws-backpack') . '</p></div>';
                }
            }
        }
    }
} elseif (isset($_POST['mws_backpack_addedit_task_nonce']) && ! wp_verify_nonce($_POST['mws_backpack_addedit_task_nonce'], 'mws_backpack_addedit_task_action')) {
    // Invalid nonce, handle the error
    echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Invalid nonce. Please try again.', 'mws-backpack') . '</p></div>';
}

$task = [
    "id"          => null,
    "name"        => "",
    "type"        => "",
    "location"    => "",
    "next_due_at" => "",
];

if (! $add) {
    $taskID = isset($_GET['edit']) ? intval($_GET['edit']) : 0;

    if ($taskID > 0) {
        $task = $backpack->getTask($taskID);
    }
}

?>

<form action="" method="post">
    <h2><?= (($add) ? "Add New Task" : "Edit Task") ?></h2>

    <?php wp_nonce_field('mws_backpack_addedit_task_action', 'mws_backpack_addedit_task_nonce'); ?>

    <table class="form-table">
        <tr>
            <th scope="row">
                <label for="mws_backpack_task_name">
                    <?php esc_html_e('Name', 'mws-backpack') ?>
                </label>
            </th>

            <td>
                <input type="text" name="mws_backpack_task_name" id="mws_backpack_task_name" value="<?= esc_attr(wp_unslash($task["name"])) ?>" class="regular-text">
                <p class="description" id="tagline-mws_backpack_task_name">
                    The name of the task.
                </p>
            </td>
        </tr>

        <tr>
            <th scope="row">
                <label for="mws_backpack_task_type">
                    <?php esc_html_e('Type', 'mws-backpack') ?>
                </label>
            </th>

            <td>
                <select name="mws_backpack_task_type" id="mws_backpack_task_type">
                    <option value="full" <?php selected($task['type'], 'full') ?>><?php esc_html_e('Full', 'mws-backpack') ?></option>
                    <option value="files" <?php selected($task['type'], 'files') ?>><?php esc_html_e('Files Only', 'mws-backpack') ?></option>
                    <option value="database" <?php selected($task['type'], 'database') ?>><?php esc_html_e('Database Only', 'mws-backpack') ?></option>
                </select>

                <p class="description" id="tagline-mws_backpack_task_priority">
                    The type of backup to perform.
                </p>
            </td>
        </tr>

        <tr>
            <th scope="row">
                <label for="mws_backpack_task_schedule">
                    <?php esc_html_e('Schedule', 'mws-backpack') ?>
                </label>
            </th>

            <td>
                <input type="text" name="mws_backpack_task_schedule" id="mws_backpack_task_schedule" value="<?= esc_attr(wp_unslash($task["schedule"] ?? "")) ?>" class="regular-text">

                <p class="description" id="tagline-mws_backpack_task_schedule">
                    The schedule for this task.
                </p>
            </td>
        </tr>
    </table>

    <div class="files-only-settings hidden">
        <h2>File Backup Settings</h2>

        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="mws_backpack_task_settings_path">
                        <?php esc_html_e('Path(s) to Backup', 'mws-backpack') ?>
                    </label>
                </th>

                <td>
                    <input type="text" name="mws_backpack_task_settings[file][path]" id="mws_backpack_task_settings_path" value="<?= esc_attr(wp_unslash($task["settings"]["path"] ?? $_SERVER["DOCUMENT_ROOT"])) ?>" class="regular-text">

                    <p class="description" id="tagline-mws_backpack_task_settings_path">
                        The path(s) to back up, comma-separated for multiple paths.
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="mws_backpack_task_settings_path_ignore">
                        <?php esc_html_e('Path(s) to Ignore', 'mws-backpack') ?>
                    </label>
                </th>

                <td>
                    <input type="text" name="mws_backpack_task_settings[file][path_ignore]" id="mws_backpack_task_settings_path_ignore" value="<?= esc_attr(wp_unslash($task["settings"]["path_ignore"] ?? "")) ?>" class="regular-text">

                    <p class="description" id="tagline-mws_backpack_task_settings_path_ignore">
                        The path(s) to ignore, comma-separated for multiple paths, use * for wildcard.
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="mws_backpack_task_settings_path">
                        <?php esc_html_e('Path Browser', 'mws-backpack') ?>
                    </label>
                </th>

                <td>
                    <div class="file-browser">
                        <?= $backpack->pathBrowser() ?>
                    </div>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="mws_backpack_task_settings_compression">
                        <?php esc_html_e('Compression', 'mws-backpack') ?>
                    </label>
                </th>

                <td>
                    <select name="mws_backpack_task_settings[file][compression]" id="mws_backpack_task_settings_compression">
                        <option value="zip" <?php selected($task['settings']['file']['compression'] ?? "", 'zip') ?>><?php esc_html_e('zip', 'mws-backpack') ?></option>
                    </select>

                    <p class="description" id="tagline-mws_backpack_task_settings_compression">
                        The compression method to use for backing up the database.
                    </p>
                </td>
            </tr>
        </table>
    </div>

    <div class="database-only-settings hidden">
        <h2>Database Backup Settings</h2>

        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="mws_backpack_task_settings_method">
                        <?php esc_html_e('Method', 'mws-backpack') ?>
                    </label>
                </th>

                <td>
                    <select name="mws_backpack_task_settings[database][method]" id="mws_backpack_task_settings_method">
                        <option value="PHP" <?php selected($task['settings']['database']['method'] ?? "", 'PHP') ?>><?php esc_html_e('PHP', 'mws-backpack') ?></option>
                        <option value="mysqldump" <?php selected($task['settings']['database']['method'] ?? "", 'mysqldump') ?>><?php esc_html_e('mysqldump', 'mws-backpack') ?></option>
                    </select>

                    <p class="description" id="tagline-mws_backpack_task_settings_method">
                        The method to use for backing up the database.
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="mws_backpack_task_settings_compression">
                        <?php esc_html_e('Compression', 'mws-backpack') ?>
                    </label>
                </th>

                <td>
                    <select name="mws_backpack_task_settings[database][compression]" id="mws_backpack_task_settings_compression">
                        <option value="none" <?php selected($task['settings']['database']['compression'] ?? "", 'none') ?>><?php esc_html_e('None', 'mws-backpack') ?></option>
                        <option value="zip" <?php selected($task['settings']['database']['compression'] ?? "", 'zip') ?>><?php esc_html_e('zip', 'mws-backpack') ?></option>
                    </select>

                    <p class="description" id="tagline-mws_backpack_task_settings_compression">
                        The compression method to use for backing up the database.
                    </p>
                </td>
            </tr>
        </table>
    </div>

    <p class="submit">
        <input type="submit" name="submit_settings" id="submit" class="button button-primary" value="<?php esc_attr_e($add ? "Create New Task" : "Update Task", 'mws-backpack'); ?>">
    </p>
</form>

<script>
    document.addEventListener("DOMContentLoaded", () => {
        document.querySelector("#mws_backpack_task_type").addEventListener("change", e => {
            showTypeFields(e.currentTarget.value);
        });

        showTypeFields(document.querySelector("#mws_backpack_task_type").value);

        function showTypeFields(value) {
            if (value === "files") {
                document.querySelector(".files-only-settings").classList.remove("hidden");
                document.querySelector(".database-only-settings").classList.add("hidden");
            } else if (value === "database") {
                document.querySelector(".files-only-settings").classList.add("hidden");
                document.querySelector(".database-only-settings").classList.remove("hidden");
            } else if (value === "full") {
                document.querySelector(".files-only-settings").classList.remove("hidden");
                document.querySelector(".database-only-settings").classList.remove("hidden");
            }
        }
        
        for (let checkbox of document.querySelectorAll(".path-selector")) {
            checkbox.addEventListener("change", e => {
                // Get all
                let allPaths = document.querySelector("#mws_backpack_task_settings_path").value.split(',');

                if (e.currentTarget.checked) {
                    allPaths.push(e.currentTarget.dataset.path);
                } else {
                    allPaths = allPaths.filter(path => path !== e.currentTarget.dataset.path);
                }

                document.querySelector("#mws_backpack_task_settings_path").value = allPaths.join(',');
            });
        }

        // Preload checkboxes
        let allPaths = document.querySelector("#mws_backpack_task_settings_path").value.split(',');

        for (let path of allPaths) {
            document.querySelector(`[data-path="${path}"]`).checked = true;
        }
    });
</script>
