<?php
/**
 * Plugin Name:       SearchFIT
 * Plugin URI:        https://searchfit.ai/extensions/wordpress
 * Description:       Automate your WordPress content with AI. Receive articles via secure webhook API to create posts with images, categories, and tags. Perfect for ChatGPT, Claude, and AI content workflows.
 * Version:           1.1.0
 * Author:            SearchFIT
 * Author URI:        https://searchfit.ai
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       searchfit
 * Domain Path:       /languages
 * Requires at least: 5.0
 * Tested up to:      6.9
 * Requires PHP:      7.4
 *
 * @package SearchFIT
 * @copyright 2026 SearchFIT
 *
 * SearchFIT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * any later version.
 *
 * SearchFIT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SearchFIT. If not, see https://www.gnu.org/licenses/gpl-2.0.html.
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Define plugin constants.
define( 'SEARCHFIT_VERSION', '1.1.0' );
define( 'SEARCHFIT_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'SEARCHFIT_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'SEARCHFIT_PLUGIN_FILE', __FILE__ );

/**
 * Main SearchFIT Plugin Class
 *
 * @since 1.0.0
 */
class SearchFIT {

    /**
     * Instance of this class.
     *
     * @var SearchFIT
     */
    private static $instance = null;

    /**
     * Get instance of this class.
     *
     * @return SearchFIT
     */
    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor.
     */
    private function __construct() {
        $this->load_includes();
        $this->init_hooks();
    }

    /**
     * Load plugin includes.
     */
    private function load_includes() {
        require_once SEARCHFIT_PLUGIN_DIR . 'includes/class-searchfit-webhook.php';
    }

    /**
     * Initialize hooks.
     */
    private function init_hooks() {
        // Activation and deactivation hooks.
        register_activation_hook( __FILE__, array( $this, 'activate' ) );
        register_deactivation_hook( __FILE__, array( $this, 'deactivate' ) );

        // Plugin action links.
        add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'plugin_action_links' ) );
        add_filter( 'plugin_row_meta', array( $this, 'plugin_row_meta' ), 10, 2 );

        // Admin hooks.
        if ( is_admin() ) {
            add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
            add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
            add_action( 'wp_ajax_searchfit_regenerate_api_key', array( $this, 'ajax_regenerate_api_key' ) );
        }
    }

    /**
     * Plugin activation.
     */
    public function activate() {
        // Set plugin version.
        add_option( 'searchfit_version', SEARCHFIT_VERSION );

        // Generate webhook API key if it doesn't exist.
        if ( ! get_option( 'searchfit_webhook_api_key' ) ) {
            $api_key = SearchFIT_Webhook::generate_api_key();
            add_option( 'searchfit_webhook_api_key', $api_key );
        }

        // Flush rewrite rules for REST API.
        flush_rewrite_rules();
    }

    /**
     * Plugin deactivation.
     */
    public function deactivate() {
        flush_rewrite_rules();
    }

    /**
     * Add admin menu.
     */
    public function add_admin_menu() {
        $icon_url = $this->get_menu_icon();

        add_menu_page(
            __( 'SearchFIT', 'searchfit' ),
            __( 'SearchFIT', 'searchfit' ),
            'manage_options',
            'searchfit',
            array( $this, 'render_admin_page' ),
            $icon_url,
            30
        );
    }

    /**
     * Get menu icon as data URI.
     *
     * @return string
     */
    private function get_menu_icon() {
        return plugins_url( 'assets/images/logo.png', __FILE__ );
    }

    /**
     * Render admin page.
     */
    public function render_admin_page() {
        // Check user capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        include SEARCHFIT_PLUGIN_DIR . 'admin/views/admin-page.php';
    }

    /**
     * Enqueue admin scripts and styles.
     *
     * @param string $hook The current admin page hook.
     */
    public function enqueue_admin_scripts( $hook ) {
        // Only load on SearchFIT admin page.
        if ( 'toplevel_page_searchfit' !== $hook ) {
            return;
        }

        wp_enqueue_style(
            'searchfit-admin',
            SEARCHFIT_PLUGIN_URL . 'assets/css/searchfit-admin.css',
            array(),
            SEARCHFIT_VERSION
        );

        wp_enqueue_script(
            'searchfit-admin',
            SEARCHFIT_PLUGIN_URL . 'assets/js/searchfit.js',
            array( 'jquery' ),
            SEARCHFIT_VERSION,
            true
        );

        wp_localize_script(
            'searchfit-admin',
            'searchfitAdmin',
            array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'nonce'   => wp_create_nonce( 'searchfit_regenerate_api_key' ),
                'i18n'    => array(
                    'copied'            => __( 'Copied!', 'searchfit' ),
                    'copyFailed'        => __( 'Failed to copy', 'searchfit' ),
                    'regenerateConfirm' => __( 'Are you sure you want to regenerate the API key? The old key will stop working immediately.', 'searchfit' ),
                    'regenerating'      => __( 'Regenerating...', 'searchfit' ),
                    'regenerateError'   => __( 'Failed to regenerate API key. Please try again.', 'searchfit' ),
                ),
            )
        );
    }

    /**
     * AJAX handler for regenerating webhook API key.
     */
    public function ajax_regenerate_api_key() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'searchfit_regenerate_api_key', 'nonce', false ) ) {
            wp_send_json_error(
                array(
                    'message' => __( 'Security check failed.', 'searchfit' ),
                )
            );
        }

        // Check permissions.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error(
                array(
                    'message' => __( 'You do not have permission to perform this action.', 'searchfit' ),
                )
            );
        }

        // Generate new API key.
        $new_api_key = SearchFIT_Webhook::generate_api_key();

        // Update the option.
        update_option( 'searchfit_webhook_api_key', $new_api_key );

        wp_send_json_success(
            array(
                'message' => __( 'API key regenerated successfully.', 'searchfit' ),
                'api_key' => $new_api_key,
            )
        );
    }

    /**
     * Add plugin action links.
     *
     * @param array $links Existing plugin action links.
     * @return array Modified plugin action links.
     */
    public function plugin_action_links( $links ) {
        $settings_link = sprintf(
            '<a href="%s">%s</a>',
            admin_url( 'admin.php?page=searchfit' ),
            __( 'Settings', 'searchfit' )
        );

        array_unshift( $links, $settings_link );

        return $links;
    }

    /**
     * Add plugin row meta links.
     *
     * @param array  $links Existing plugin row meta links.
     * @param string $file  Plugin file path.
     * @return array Modified plugin row meta links.
     */
    public function plugin_row_meta( $links, $file ) {
        if ( plugin_basename( SEARCHFIT_PLUGIN_FILE ) !== $file ) {
            return $links;
        }

        $row_meta = array(
            'docs' => sprintf(
                '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
                'https://searchfit.ai/docs',
                __( 'Documentation', 'searchfit' )
            ),
            'support' => sprintf(
                '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
                'https://wordpress.org/support/plugin/searchfit/',
                __( 'Support', 'searchfit' )
            ),
        );

        return array_merge( $links, $row_meta );
    }
}

/**
 * Initialize the plugin.
 *
 * @return SearchFIT
 */
function searchfit_init() {
    return SearchFIT::get_instance();
}

// Start the plugin.
searchfit_init();
