<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /includes/class-social-page.php
// Description: Social Media module page controller — channel-agnostic, loops over registered ChannelInterface implementations - NUCLEAR+++
// Last Edited: 2026-03-29
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class SocialPage
{
    // Registered channel instances — keyed by slug.
    // To add a new channel: instantiate its class here.
    // It must implement ChannelInterface.
    private static array $channels = [];

    // --------------------------------------------------
    // Boot
    // --------------------------------------------------
    public static function init(): void
    {
        self::registerChannels();

        add_action('admin_menu',            [self::class, 'registerSubmenu']);
        add_action('admin_init',            [self::class, 'handleActions']);
        add_action('admin_enqueue_scripts', [self::class, 'enqueueAssets']);
        add_action('wp_ajax_amai_save_approval_mode', [self::class, 'ajaxSaveApprovalMode']);
    }

    // --------------------------------------------------
    // Register all channel implementations.
    // Adding a new channel: add one line here.
    // --------------------------------------------------
    private static function registerChannels(): void
    {
        $channel_list = [
            new FacebookChannel(),
            new InstagramChannel(),
            new XChannel(),
            new GoogleChannel(),
            new LinkedInChannel(),
            new TikTokChannel(),
            new PinterestChannel(),
        ];

        foreach ($channel_list as $channel) {
            self::$channels[$channel->get_slug()] = $channel;
        }
    }

    // --------------------------------------------------
    // Register the Social Media submenu page
    // --------------------------------------------------
    public static function registerSubmenu(): void
    {
        add_submenu_page(
            null,
            'Social Media',
            'Social Media',
            'manage_automarketer_ai',
            'automarketer-ai-social',
            [self::class, 'render']
        );
    }

    // --------------------------------------------------
    // Enqueue assets — only on this page
    // --------------------------------------------------
    // --------------------------------------------------
    public static function enqueueAssets(string $hook): void
    {
        if (strpos($hook, 'automarketer-ai-social') === false) {
            return;
        }

        wp_enqueue_style(
            'amai-social',
            AMAI_PLUGIN_URL . 'assets/css/social.css',
            [],
            AMAI_VERSION
        );

        wp_enqueue_script(
            'amai-social',
            AMAI_PLUGIN_URL . 'assets/js/amai-social.js',
            [],
            (string) filemtime(AMAI_PLUGIN_DIR . 'assets/js/amai-social.js'),
            true
        );

        $approval_mode = (get_option('amai_approval_mode', 'review') === 'autopilot') ? 'autopilot' : 'review';

        // Load compose-tab assets when on the compose tab
        if (isset($_GET['tab']) && $_GET['tab'] === 'compose') {
            wp_enqueue_style(
                'amai-manual-post',
                AMAI_PLUGIN_URL . 'assets/css/manual-post.css',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/manual-post.css')
            );
            wp_enqueue_media();
            wp_enqueue_script(
                'amai-manual-post',
                AMAI_PLUGIN_URL . 'assets/js/amai-manual-post.js',
                [],
                (string) filemtime(AMAI_PLUGIN_DIR . 'assets/js/amai-manual-post.js'),
                true
            );
            wp_localize_script('amai-manual-post', 'amaiManual', [
                'nonce'   => wp_create_nonce('amai_manual_post'),
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'channel' => sanitize_key((string) ($_GET['channel'] ?? 'facebook')),
                'hasImageProvider' => (function() { foreach ((array) get_option('amai_active_modules', []) as $id) { if (is_string($id) && str_starts_with($id, 'img-')) { return true; } } return false; })(),
            ]);
        }
        $fb_connection  = \AutoMarketerAI\FacebookAuth::getConnection();
        $biz_profile    = (new \AutoMarketerAI\BusinessProfile())->getOrCreate();

        wp_localize_script('amai-social', 'amaiSocial', [
            'nonce'         => wp_create_nonce('amai_social'),
            'ajaxUrl'       => admin_url('admin-ajax.php'),
            'pageUrl'       => admin_url('admin.php?page=automarketer-ai-social'),
            'composeUrl'    => admin_url('admin.php?page=automarketer-ai-social&channel=facebook&tab=compose'),
            'approvalMode'  => $approval_mode,
            'locationNonce' => wp_create_nonce('amai_location_search'),
            'bioNonce'      => wp_create_nonce('amai_generate_fb_bio'),
            'pageName'      => (string) ($fb_connection['page_name'] ?? ($biz_profile['page_name'] ?? '')),
            'pageAvatarUrl'  => (string) ($fb_connection['page_picture_url'] ?? ''),
            'xUsername'      => (string) (\AutoMarketerAI\XAuth::getConnection()['username']          ?? ''),
            'xDisplayName'   => (string) (\AutoMarketerAI\XAuth::getConnection()['display_name']      ?? ''),
            'xAvatarUrl'     => (string) (\AutoMarketerAI\XAuth::getConnection()['profile_image_url'] ?? ''),
            'websiteUrl'    => (string) ($biz_profile['website_url'] ?? ''),
        ]);
    }

    // --------------------------------------------------
    // AJAX — save approval mode
    // --------------------------------------------------
    public static function ajaxSaveApprovalMode(): void
    {
        $nonce = sanitize_text_field((string) ($_POST['_wpnonce'] ?? ''));
        if (!wp_verify_nonce($nonce, 'amai_save_approval_mode')) {
            wp_send_json_error(['message' => 'Invalid nonce.'], 403);
            return;
        }

        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized.'], 403);
            return;
        }

        $mode = sanitize_key((string) ($_POST['mode'] ?? ''));
        if ($mode !== 'review' && $mode !== 'autopilot') {
            wp_send_json_error(['message' => 'Invalid mode.'], 400);
            return;
        }

        update_option('amai_approval_mode', $mode, false);
        wp_send_json_success(['mode' => $mode]);
    }

    // --------------------------------------------------
    // Delegate admin_init actions to the active channel
    // --------------------------------------------------
    public static function handleActions(): void
    {
        $page = sanitize_key((string) ($_GET['page'] ?? ''));
        if ($page !== 'automarketer-ai-social') {
            return;
        }

        $slug    = sanitize_key((string) ($_GET['channel'] ?? 'facebook'));
        $channel = self::$channels[$slug] ?? self::$channels['facebook'] ?? null;

        if ($channel === null) {
            return;
        }

        $channel->handle_actions();
    }

    // --------------------------------------------------
    // Render — outer shell with channel nav
    // --------------------------------------------------
    public static function render(): void
    {
        $active_slug = sanitize_key((string) ($_GET['channel'] ?? 'facebook'));

        if (!isset(self::$channels[$active_slug])) {
            $active_slug = 'facebook';
        }

        $channels   = self::$channels;
        $auth_error = get_transient('amai_fb_auth_error');
        delete_transient('amai_fb_auth_error');

        include AMAI_PLUGIN_DIR . 'templates/social-shell.php';
    }

    // --------------------------------------------------
    // Render the content area for the active channel slug.
    // Called from social-shell.php.
    // --------------------------------------------------
    public static function renderChannel(string $slug): void
    {
        $channel = self::$channels[$slug] ?? null;

        if ($channel === null || !$channel->is_available()) {
            include AMAI_PLUGIN_DIR . 'templates/social/coming-soon.php';
            return;
        }

        $channel->render();
    }

    // --------------------------------------------------
    // Returns connection status keyed by slug.
    // Used by social-shell.php to render nav indicators.
    // --------------------------------------------------
    public static function getChannelConnectionStatus(): array
    {
        $status = [];
        foreach (self::$channels as $slug => $channel) {
            $status[$slug] = $channel->get_connection_status();
        }
        return $status;
    }

    // --------------------------------------------------
    // Returns all registered channels.
    // Used by social-shell.php to build the nav.
    // --------------------------------------------------
    public static function getChannels(): array
    {
        return self::$channels;
    }
}