<?php
/*
Plugin Name: Itinerator Templates
Description: Stores templates for Itinerator blocks in the plugin folder and creates a symlink named "itinerator" in the themes directory, pointing back to the plugin folder.
Version: 1.0
Author: The Number
*/

// Hook into WordPress activation and create the symlink
register_activation_hook(__FILE__, 'itinerator_create_symlink');

function itinerator_create_symlink() {
    // Define the theme directory path dynamically
    $theme_directory = get_stylesheet_directory();

    // Update - make sure this directory exists
    if (!file_exists($theme_directory)) {
        mkdir($theme_directory, 0755, true);
    }

    // Define the symlink path
    $symlink_path = $theme_directory . '/itinerator';

    // Define the target path (plugin folder)
    $target_path = plugin_dir_path(__FILE__) . '/itinerator';

    // Check if the symlink or directory already exists
    if (is_dir($symlink_path) && !is_link($symlink_path)) {
        // Log an error and deactivate the plugin
        error_log("A directory named 'itinerator' already exists in the theme directory. Please remove it to activate the plugin.");
        deactivate_plugins(plugin_basename(__FILE__));
        wp_die("A directory named 'itinerator' already exists in the theme directory. Please remove it to reactivate this plugin.");
        return;
    }

    // Attempt to create the symlink
    if (!is_link($symlink_path) && symlink($target_path, $symlink_path)) {
        // Symlink created successfully
        error_log('Itinerator templates symlink created successfully.');
    } else {
        // Failed to create symlink
        error_log('Failed to create Itinerator templates symlink.');
    }
}

// Hook into WordPress deactivation and remove the symlink
register_deactivation_hook(__FILE__, 'itinerator_remove_symlink');

function itinerator_remove_symlink() {
    // Define the symlink path
    $symlink_path = get_stylesheet_directory() . '/itinerator';

    // Check if the symlink exists
    if (is_link($symlink_path)) {
        // Try to remove the symlink and check if the operation was successful
        if (@unlink($symlink_path)) {
            error_log('Itinerator symlink removed on deactivation.');
        } else {
            error_log('Failed to remove Itinerator symlink on deactivation.');
        }
    }
}

// Enqueue the JavaScript file
function itinerator_enqueue_scripts() {
    wp_enqueue_script( 'itinerator-script', plugins_url( '/app.js', __FILE__ ), array( 'jquery' ), '1.0', true );
    wp_enqueue_style( 'itinerator-style', plugins_url( '/app.css', __FILE__ ), array(), '1.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'itinerator_enqueue_scripts', 20 );



// Need to dequeue the google maps api script if there are already other ones loaded.
function dequeue_google_maps_api_script() {
    $wp_scripts = wp_scripts();

    $matches = 0;

    foreach ($wp_scripts->registered as $handle => $script) {
        if (preg_match('/^(?:https?:\/\/)?maps\.googleapis\.com.*\/maps\/api\/js/', $script->src)) {
            $matches++;
        }
    }

    if ($matches > 1) {
        wp_dequeue_script('google_maps_api');
    }
}
add_action('wp_enqueue_scripts', 'dequeue_google_maps_api_script', 999);

// Hook to add admin menu
add_action('admin_menu', 'itinerator_add_admin_menu');

function itinerator_add_admin_menu() {
    add_menu_page(
        'Itinerator Templates Settings', // Page title
        'Itinerator Templates', // Menu title
        'manage_options', // Capability
        'itinerator-templates-settings', // Menu slug
        'itinerator_templates_settings_page', // Callback function
        'data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMjIgMzIyIj48cGF0aCBkPSJNMTcwLjcyLDgwLjQ3VjczLjIxQTM3LjI3LDM3LjI3LDAsMSwwLDEyNSwyNy4yN2EzNi40MiwzNi40MiwwLDAsMC0xLjQsMTBoMGEzNS44OSwzNS44OSwwLDAsMCwxLjQsOS45NEEzNy41MywzNy41MywwLDAsMCwxNTEsNzMuMDhoLS4yVjgwLjVBNjYuMzEsNjYuMzEsMCwwLDAsOTQuNTEsMTQ2VjI1NC43YTY2LjI4LDY2LjI4LDAsMSwwLDEzMi41NCwwVjE0NS45MmE2Ni4zMSw2Ni4zMSwwLDAsMC01Ni4zMy02NS40NVpNMTQzLjY1LDM3LjIyYTE3LjQzLDE3LjQzLDAsMSwxLDUuMTcsMTIuMjksMTcuNTQsMTcuNTQsMCwwLDEtNS4xNy0xMi4yOVptMTcuMTMsMTI2YTE3LjMzLDE3LjMzLDAsMCwxLDAtMzQuNjVoMGExNy4zMywxNy4zMywwLDAsMSwwLDM0LjY1Wm05Ljk0LDc3LjMyYTE2LjgyLDE2LjgyLDAsMSwxLTkuOTQtMy4xMWgwYTE3LjE2LDE3LjE2LDAsMCwxLDkuOTQsMy4xM1ptMzYuNDUsMTQuMTZhNDYuMzksNDYuMzksMCwxLDEtOTIuNzgsMFYxNDUuOTJhNDYuNDUsNDYuNDUsMCwwLDEsMzYuNDQtNDUuMjl2OS40NWEzNy4xNywzNy4xNywwLDAsMCwwLDcxLjY1djM3LjE1YTM3LjIzLDM3LjIzLDAsMSwwLDE5Ljg5LDBWMTgxLjc0YTM3LjE3LDM3LjE3LDAsMCwwLDAtNzEuNjVoMHYtOS40NmE0Ni40Nyw0Ni40NywwLDAsMSwzNi40NSw0NS4yOVoiIHN0eWxlPSJmaWxsOiM5Y2ExYTciLz48L3N2Zz4=', // Same SVG icon
        91 // Position it right after the main Itinerator menu (90)
    );
}

// Callback function to display the settings page
function itinerator_templates_settings_page() {
    // Handle file upload/delete if submitted
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['action'])) {
            if ($_POST['action'] === 'delete' && isset($_POST['file'])) {
                $file = sanitize_text_field($_POST['file']);
                $file_path = plugin_dir_path(__FILE__) . $file;
                if (file_exists($file_path) && is_file($file_path)) {
                    unlink($file_path);
                    echo '<div class="notice notice-success"><p>File deleted successfully.</p></div>';
                }
            } elseif ($_POST['action'] === 'replace' && isset($_FILES['new_file'])) {
                $file = sanitize_text_field($_POST['file']);
                $target_path = plugin_dir_path(__FILE__) . $file;
                if (move_uploaded_file($_FILES['new_file']['tmp_name'], $target_path)) {
                    echo '<div class="notice notice-success"><p>File replaced successfully.</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>Error replacing file.</p></div>';
                }
            } elseif ($_POST['action'] === 'upload' && isset($_FILES['upload_file'])) {
                $upload_dir = isset($_POST['upload_dir']) ? trim($_POST['upload_dir'], '/') : '';
                $target_dir = plugin_dir_path(__FILE__) . $upload_dir;

                // Create directory if it doesn't exist
                if (!empty($upload_dir) && !file_exists($target_dir)) {
                    mkdir($target_dir, 0755, true);
                }

                $target_path = $target_dir . '/' . basename($_FILES['upload_file']['name']);

                if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $target_path)) {
                    echo '<div class="notice notice-success"><p>File uploaded successfully.</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>Error uploading file.</p></div>';
                }
            }
        }
    }

    // Get all files in plugin directory
    $plugin_dir = plugin_dir_path(__FILE__);
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($plugin_dir, RecursiveDirectoryIterator::SKIP_DOTS)
    );

    // Filter out hidden files and unwanted directories
    $files = new CallbackFilterIterator($iterator, function ($file) {
        $filename = $file->getFilename();
        $excluded_files = array('.git', '.gitignore', '.DS_Store', '.DS_STORE', '.svn', '__MACOSX');

        if ($filename[0] === '.' || in_array($filename, $excluded_files)) {
            return false;
        }

        foreach ($excluded_files as $excluded) {
            if (strpos($file->getPathname(), DIRECTORY_SEPARATOR . $excluded . DIRECTORY_SEPARATOR) !== false) {
                return false;
            }
        }
        return true;
    });

    ?>
    <div class="wrap">
        <h1>Itinerator Templates Settings</h1>

        <!-- Upload Form -->
        <div class="card" style="max-width: 100%; margin-bottom: 20px;">
            <h2>Upload New File</h2>
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload">
                <p>
                    <label for="upload_dir">Upload Directory (optional):</label><br>
                    <select name="upload_dir" id="upload_dir">
                        <option value="">Root Directory</option>
                        <option value="itinerator">itinerator/</option>
                        <!-- Add more options if needed -->
                    </select>
                </p>
                <p>
                    <label for="upload_file">Select File:</label><br>
                    <input type="file" name="upload_file" id="upload_file" required>
                </p>
                <p>
                    <input type="submit" class="button button-primary" value="Upload File">
                </p>
            </form>
        </div>

        <!-- Files Table -->
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th>File</th>
                    <th>Size</th>
                    <th>Last Modified</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $files_array = iterator_to_array($files);
                ksort($files_array);

                foreach ($files_array as $file):
                    $relative_path = str_replace($plugin_dir, '', $file->getPathname());
                    ?>
                    <tr>
                        <td><?php echo esc_html($relative_path); ?></td>
                        <td><?php echo size_format($file->getSize()); ?></td>
                        <td><?php echo date('Y-m-d H:i:s', $file->getMTime()); ?></td>
                        <td>
                            <form method="post" style="display: inline-block; margin-right: 10px;">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="file" value="<?php echo esc_attr($relative_path); ?>">
                                <button type="submit" class="button button-small"
                                        onclick="return confirm('Are you sure you want to delete this file?')">
                                    Delete
                                </button>
                            </form>

                            <form method="post" enctype="multipart/form-data" style="display: inline-block;">
                                <input type="hidden" name="action" value="replace">
                                <input type="hidden" name="file" value="<?php echo esc_attr($relative_path); ?>">
                                <input type="file" name="new_file" style="display: none;"
                                       onchange="this.form.submit();" id="file_<?php echo esc_attr(md5($relative_path)); ?>">
                                <button type="button" class="button button-small"
                                        onclick="document.getElementById('file_<?php echo esc_attr(md5($relative_path)); ?>').click()">
                                    Replace
                                </button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php
}

// Hook to initialize settings
add_action('admin_init', 'itinerator_register_settings');

function itinerator_register_settings() {
    register_setting('itinerator_templates_settings_group', 'itinerator_template_option');

    add_settings_section(
        'itinerator_templates_main_section',
        'Main Settings',
        'itinerator_templates_section_callback',
        'itinerator_templates_settings'
    );

    add_settings_field(
        'itinerator_template_option',
        'Template Option',
        'itinerator_template_option_callback',
        'itinerator_templates_settings',
        'itinerator_templates_main_section'
    );
}

function itinerator_templates_section_callback() {
    echo '<p>Main settings for the Itinerator Templates plugin.</p>';
}

function itinerator_template_option_callback() {
    $option = get_option('itinerator_template_option');
    echo '<input type="text" name="itinerator_template_option" value="' . esc_attr($option) . '" />';
}

function itinerator_enqueue_code_editor() {
    wp_enqueue_script('codemirror-js', 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.js', array(), null, true);
    wp_enqueue_script('codemirror-js-mode', 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/javascript/javascript.min.js', array('codemirror-js'), null, true);
    wp_enqueue_script('codemirror-css-mode', 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/css/css.min.js', array('codemirror-js'), null, true);
    wp_enqueue_style('codemirror-css', 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.css');
}
add_action('admin_enqueue_scripts', 'itinerator_enqueue_code_editor');

function itinerator_save_file_edits() {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['app_js_content'])) {
            file_put_contents(plugin_dir_path(__FILE__) . 'app.js', stripslashes($_POST['app_js_content']));
        }
        if (isset($_POST['app_css_content'])) {
            file_put_contents(plugin_dir_path(__FILE__) . 'app.css', stripslashes($_POST['app_css_content']));
        }
        if (isset($_POST['php_content'])) {
            file_put_contents(__FILE__, stripslashes($_POST['php_content']));
        }
    }
}
add_action('admin_post_itinerator_save_edits', 'itinerator_save_file_edits');


// function get_random_default_hero_image($return_type = 'url', $size = 'full') {
//     $default_image_ids = array(7538, 6060, 6057, 7539, 4574);

//     $random_image_id = $default_image_ids[array_rand($default_image_ids)];

//     if ($return_type === 'id') {
//         return $random_image_id;
//     } else {
//         return wp_get_attachment_image_url($random_image_id, $size);
//     }
// }
