<?php
/**
 * WPBS_Plugin_Builder
 *
 * Admin page for building and editing WordPress plugins via AI.
 * Handles AJAX requests for build, install, edit, and plugin listing.
 */
if (!defined('ABSPATH')) exit;

class WPBS_Plugin_Builder {

    private static $instance = null;

    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action('wp_ajax_pspb_build_plugin', [$this, 'ajax_build_plugin']);
        add_action('wp_ajax_pspb_install_plugin', [$this, 'ajax_install_plugin']);
        add_action('wp_ajax_pspb_list_plugins', [$this, 'ajax_list_plugins']);
        add_action('wp_ajax_pspb_edit_plugin', [$this, 'ajax_edit_plugin']);
        add_action('wp_ajax_pspb_read_plugin_files', [$this, 'ajax_read_plugin_files']);
    }

    /**
     * Render the Plugin Builder admin page.
     */
    public function render_page() {
        ?>
        <div class="wrap pspb-wrap">
            <h1>Plugin Builder</h1>
            <p class="description">Describe a WordPress plugin and AI will build, install, and activate it automatically.</p>

            <div class="pspb-mode-toggle">
                <label>
                    <input type="checkbox" id="pspb-edit-mode"> Edit an existing plugin
                </label>
            </div>

            <!-- Build Mode -->
            <div id="pspb-build-section" class="pspb-section">
                <h2>Build a New Plugin</h2>
                <textarea id="pspb-build-prompt" rows="6" class="large-text" placeholder="Describe the plugin you want to build. Be specific about features, admin pages, shortcodes, settings, etc."></textarea>
                <p>
                    <button type="button" id="pspb-build-btn" class="button button-primary button-hero">Build Plugin</button>
                </p>
            </div>

            <!-- Edit Mode -->
            <div id="pspb-edit-section" class="pspb-section" style="display:none;">
                <h2>Edit an Existing Plugin</h2>
                <p>
                    <label for="pspb-plugin-select"><strong>Select Plugin:</strong></label>
                    <select id="pspb-plugin-select" class="regular-text">
                        <option value="">Loading plugins...</option>
                    </select>
                    <button type="button" id="pspb-refresh-plugins" class="button">Refresh</button>
                </p>
                <textarea id="pspb-edit-prompt" rows="6" class="large-text" placeholder="Describe the changes you want to make to the selected plugin..."></textarea>
                <p>
                    <button type="button" id="pspb-edit-btn" class="button button-primary button-hero">Edit Plugin</button>
                </p>
            </div>

            <!-- Status Feed -->
            <div id="pspb-status-feed" class="pspb-status-feed">
                <h3>Status</h3>
                <div id="pspb-status-messages"></div>
            </div>
        </div>
        <?php
    }

    // --- AJAX Handlers ---

    /**
     * Build a new plugin via the PageSpark API.
     */
    public function ajax_build_plugin() {
        check_ajax_referer('pspb_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        $prompt = sanitize_textarea_field($_POST['prompt'] ?? '');
        $previous_errors = isset($_POST['previous_errors']) ? array_map('sanitize_text_field', (array)$_POST['previous_errors']) : [];
        $attempt_number = absint($_POST['attempt_number'] ?? 1);

        if (empty($prompt)) {
            wp_send_json_error('Plugin description is required');
        }

        $api_client = WPBS_API_Client::instance();
        $result = $api_client->request_plugin_build($prompt, [
            'siteContext' => $api_client->build_site_context(),
            'previous_errors' => $previous_errors,
            'attempt_number' => $attempt_number,
        ]);

        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }

        wp_send_json_success($result);
    }

    /**
     * Install a plugin zip locally via Plugin_Upgrader (no Playwright).
     */
    public function ajax_install_plugin() {
        check_ajax_referer('pspb_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        $download_url = esc_url_raw($_POST['download_url'] ?? '');
        $plugin_slug = sanitize_file_name($_POST['plugin_name'] ?? '');
        $mode = sanitize_text_field($_POST['mode'] ?? 'install');

        if (empty($download_url)) {
            wp_send_json_error('Download URL is required');
        }

        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';

        // For update mode: deactivate + delete existing plugin first
        if ($mode === 'update' && $plugin_slug) {
            $plugin_file = $this->find_plugin_file($plugin_slug);
            if ($plugin_file) {
                deactivate_plugins($plugin_file);
                delete_plugins([$plugin_file]);
            }
        }

        // Install from blob URL
        $upgrader = new Plugin_Upgrader(new WP_Ajax_Upgrader_Skin());
        $result = $upgrader->install($download_url);

        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }
        if ($result === false) {
            wp_send_json_error('Plugin installation failed');
        }

        // Activate the newly installed plugin
        $new_plugin_file = $this->find_plugin_file($plugin_slug);
        if ($new_plugin_file) {
            $activated = activate_plugin($new_plugin_file);
            if (is_wp_error($activated)) {
                wp_send_json_error('Installed but activation failed: ' . $activated->get_error_message());
            }
        }

        // Clean up the blob on the API side
        $api_client = WPBS_API_Client::instance();
        $api_client->request_blob_cleanup($download_url);

        wp_send_json_success([
            'success' => true,
            'plugin_name' => $plugin_slug,
            'mode' => $mode,
        ]);
    }

    /**
     * Find a plugin's main file by directory slug.
     */
    private function find_plugin_file($slug) {
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        foreach (get_plugins() as $file => $data) {
            if (dirname($file) === $slug) {
                return $file;
            }
        }
        return null;
    }

    /**
     * List plugins built by PageSpark (have "Built-By: PageSpark Plugin Builder" header).
     */
    public function ajax_list_plugins() {
        check_ajax_referer('pspb_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $all_plugins = get_plugins();
        $pagespark_plugins = [];

        foreach ($all_plugins as $plugin_file => $plugin_data) {
            // Read the main file to check for Built-By header
            $plugin_path = WP_PLUGIN_DIR . '/' . $plugin_file;
            if (!file_exists($plugin_path)) continue;

            $header_data = get_file_data($plugin_path, ['BuiltBy' => 'Built-By']);
            if (!empty($header_data['BuiltBy']) && stripos($header_data['BuiltBy'], 'PageSpark') !== false) {
                $slug = dirname($plugin_file);
                $pagespark_plugins[] = [
                    'slug' => $slug,
                    'file' => $plugin_file,
                    'name' => $plugin_data['Name'],
                    'version' => $plugin_data['Version'] ?? '1.0.0',
                    'description' => $plugin_data['Description'] ?? '',
                    'active' => is_plugin_active($plugin_file),
                ];
            }
        }

        wp_send_json_success($pagespark_plugins);
    }

    /**
     * Edit an existing plugin via the PageSpark API.
     */
    public function ajax_edit_plugin() {
        check_ajax_referer('pspb_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        $plugin_files_json = $_POST['plugin_files'] ?? '';
        $edit_prompt = sanitize_textarea_field($_POST['edit_prompt'] ?? '');
        $previous_errors = isset($_POST['previous_errors']) ? array_map('sanitize_text_field', (array)$_POST['previous_errors']) : [];
        $attempt_number = absint($_POST['attempt_number'] ?? 1);

        if (empty($plugin_files_json) || empty($edit_prompt)) {
            wp_send_json_error('Plugin files and edit prompt are required');
        }

        // plugin_files is sent as JSON string
        $plugin_files = json_decode(stripslashes($plugin_files_json), true);
        if (!is_array($plugin_files)) {
            wp_send_json_error('Invalid plugin files format');
        }

        $api_client = WPBS_API_Client::instance();
        $result = $api_client->request_plugin_edit([
            'plugin_files' => $plugin_files,
            'edit_prompt' => $edit_prompt,
            'site_context' => $api_client->build_site_context(),
            'previous_errors' => $previous_errors,
            'attempt_number' => $attempt_number,
        ]);

        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }

        wp_send_json_success($result);
    }

    /**
     * Read all files from a plugin directory as a { path: content } map.
     */
    public function ajax_read_plugin_files() {
        check_ajax_referer('pspb_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        $plugin_slug = sanitize_file_name($_POST['plugin_slug'] ?? '');
        if (empty($plugin_slug)) {
            wp_send_json_error('Plugin slug is required');
        }

        $plugin_dir = WP_PLUGIN_DIR . '/' . $plugin_slug;
        if (!is_dir($plugin_dir)) {
            wp_send_json_error('Plugin directory not found');
        }

        $files = [];
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($plugin_dir, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $relative_path = $plugin_slug . '/' . str_replace($plugin_dir . '/', '', $file->getPathname());
                // Only read text-based files
                $ext = strtolower($file->getExtension());
                $allowed_extensions = ['php', 'js', 'css', 'html', 'txt', 'json', 'xml', 'md', 'yml', 'yaml'];
                if (in_array($ext, $allowed_extensions)) {
                    $content = file_get_contents($file->getPathname());
                    if ($content !== false) {
                        $files[$relative_path] = $content;
                    }
                }
            }
        }

        if (empty($files)) {
            wp_send_json_error('No readable files found in plugin directory');
        }

        wp_send_json_success($files);
    }
}
