<?php
/**
 * Plugin Name: SocialPilot - Social Media Scheduling Tools
 * Plugin URI: https://www.socialpilot.co
 * Description: Schedule and manage social media posts directly from WordPress using SocialPilot
 * Version: 1.1.5
 * Author: SocialPilot
 * Author URI: https://www.socialpilot.co
 * License: GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain: socialpilot-wp
 * Domain Path: /languages
 *
 * @package SocialPilot
 */

// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Define plugin constants
 */
define('SOCIALPILOT_VERSION', '1.1.5');
define('SOCIALPILOT_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SOCIALPILOT_PLUGIN_URL', plugin_dir_url(__FILE__));
define('SOCIALPILOT_PLUGIN_BASENAME', plugin_basename(__FILE__));

/**
 * Main plugin class
 */
final class SocialPilot_Plugin
{

    /**
     * Instance of the plugin
     *
     * @var SocialPilot_Plugin
     */
    private static $instance = null;

    /**
     * Get plugin instance
     *
     * @return SocialPilot_Plugin
     */
    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct()
    {
        // Load plugin dependencies
        $this->load_dependencies();

        // Initialize hooks
        $this->init_hooks();
    }

    /**
     * Load required dependencies
     *
     * @return void
     */
    private function load_dependencies()
    {
        // Core plugin files
        require_once SOCIALPILOT_PLUGIN_DIR . 'includes/class-socialpilot-settings.php';
        require_once SOCIALPILOT_PLUGIN_DIR . 'includes/class-socialpilot-api.php';
        require_once SOCIALPILOT_PLUGIN_DIR . 'includes/class-socialpilot-metabox.php';
        require_once SOCIALPILOT_PLUGIN_DIR . 'includes/class-socialpilot-encrypt.php';
    }

    /**
     * Initialize plugin hooks
     *
     * @return void
     */
    private function init_hooks()
    {
        // Activation/Deactivation hooks
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));

        // Initialize plugin after WordPress is loaded
        add_action('plugins_loaded', array($this, 'init'));

        // Add settings link to plugins page
        add_filter('plugin_action_links_' . SOCIALPILOT_PLUGIN_BASENAME, array($this, 'add_settings_link'));
    }

    /**
     * Initialize plugin components
     *
     * @return void
     */
    public function init()
    {
        // Load text domain for internationalization
        $this->load_textdomain();

        // Initialize components
        SocialPilot_Settings::get_instance();
        SocialPilot_MetaBox::get_instance();
        SocialPilot_API::get_instance();

        // Initialize AJAX handlers if in admin
        if (is_admin()) {
            $this->init_ajax_handlers();
        }
    }

    /**
     * Load plugin text domain
     *
     * @return void
     */
    private function load_textdomain()
    {
        load_plugin_textdomain(
            'socialpilot-wp',
            false,
            dirname(SOCIALPILOT_PLUGIN_BASENAME) . '/languages'
        );
    }

    /**
     * Plugin activation hook
     *
     * @return void
     */
    public function activate()
    {
        // Set default options
        $this->set_default_options();

        // Set activation redirect flag
        add_option('socialpilot_do_activation_redirect', true);

        // Clear permalinks
        flush_rewrite_rules();
    }

    /**
     * Plugin deactivation hook
     *
     * @return void
     */
    public function deactivate()
    {
        // Remove activation redirect flag
        delete_option('socialpilot_do_activation_redirect');

        delete_option('socialpilot_options');
        // Clear any scheduled hooks
        wp_clear_scheduled_hook('socialpilot_cron_hook');

        // Clear permalinks
        flush_rewrite_rules();
    }

    /**
     * Set default plugin options
     *
     * @return void
     */
    private function set_default_options()
    {
        $default_options = array(
            'api_key' => '',
            'enabled_post_types' => array('post', 'page'),
            'enabled_social_accounts' => array(''),
            'version' => SOCIALPILOT_VERSION,
        );

        add_option('socialpilot_options', $default_options);
    }

    /**
     * Add settings link to plugin page
     *
     * @param array $links Existing plugin links
     * @return array Modified plugin links
     */
    public function add_settings_link($links)
    {
        $settings_link = sprintf(
            '<a href="%s">%s</a>',
            admin_url('options-general.php?page=socialpilot-settings'),
            __('Settings', 'socialpilot-wp')
        );
        array_unshift($links, $settings_link);
        return $links;
    }

    /**
     * Initialize AJAX handlers
     *
     * @return void
     */
    private function init_ajax_handlers()
    {
        // Get accounts
        add_action('wp_ajax_socialpilot_get_accounts', function () {
            check_ajax_referer('socialpilot_nonce', 'nonce');

            if (!current_user_can('edit_posts')) {
                wp_send_json_error(array('message' => __('Permission denied', 'socialpilot-wp')));
                return;
            }

            try {
                $api = SocialPilot_API::get_instance();
                $response = $api->get_accounts();
                wp_send_json_success($response);
            } catch (Exception $e) {
                wp_send_json_error(array('message' => $e->getMessage()));
            }
        });

        // Generate caption
        add_action('wp_ajax_socialpilot_generate_caption', function () {
            check_ajax_referer('socialpilot_nonce', 'nonce');

            if (!current_user_can('edit_posts')) {
                wp_send_json_error(array('message' => __('Permission denied', 'socialpilot-wp')));
                return;
            }

            try {
                if (empty($_POST['title']) || empty($_POST['content'])) {
                    throw new Exception(__('Title and content are required', 'socialpilot-wp'));
                }

                $title = sanitize_text_field(wp_unslash($_POST['title']));
                $content = sanitize_textarea_field(wp_unslash($_POST['content']));

                $api = SocialPilot_API::get_instance();
                $response = $api->generate_caption($title, $content);

                wp_send_json_success($response);
            } catch (Exception $e) {
                wp_send_json_error(array('message' => $e->getMessage()));
            }
        });

        // Upload media
        add_action('wp_ajax_socialpilot_upload_media', function () {
            check_ajax_referer('socialpilot_nonce', 'nonce');

            if (!current_user_can('edit_posts')) {
                wp_send_json_error(array('message' => __('Permission denied', 'socialpilot-wp')));
                return;
            }

            $media_url = isset($_POST['media_url']) ? sanitize_url($_POST['media_url']) : '';
            $media_type = isset($_POST['media_type']) ? sanitize_text_field($_POST['media_type']) : '';

            if (!$media_url || !$media_type) {
                wp_send_json_error(array('message' => __('Invalid media data', 'socialpilot-wp')));
                return;
            }

            try {
                $api = SocialPilot_API::get_instance();
                $response = $api->upload_media($media_url, $media_type);
                wp_send_json_success($response);
            } catch (Exception $e) {
                wp_send_json_error(array('message' => $e->getMessage()));
            }
        });

        // Schedule post
        add_action('wp_ajax_socialpilot_schedule_post', function () {
            check_ajax_referer('socialpilot_nonce', 'nonce');

            if (!current_user_can('edit_posts')) {
                wp_send_json_error(array('message' => __('Permission denied', 'socialpilot-wp')));
                return;
            }

            $post_data = isset($_POST['post_data']) ? json_decode(stripslashes($_POST['post_data']), true) : array();

            if (json_last_error() !== JSON_ERROR_NONE) {
                wp_send_json_error(array('message' => __('Invalid post data format', 'socialpilot-wp')));
                return;
            }

            try {
                $api = SocialPilot_API::get_instance();
                $response = $api->schedule_post($post_data);
                wp_send_json_success($response);
            } catch (Exception $e) {
                wp_send_json_error(array('message' => $e->getMessage()));
            }
        });
    }
}

/**
 * Initialize the plugin
 *
 * @return SocialPilot_Plugin Plugin instance
 */
function socialpilot_init() {
    return SocialPilot_Plugin::get_instance();
}

// Start the plugin
socialpilot_init();