<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /includes/class-facebook-page.php
// Description: Facebook module submenu page controller - NUCLEAR+++
// Last Edited: 2026-03-25
// ==================================================

namespace AutoMarketerAI;

// No direct access
defined('ABSPATH') || exit;

final class FacebookPage
{
    // --------------------------------------------------
    // Boot — called from automarketer-ai.php
    // --------------------------------------------------
    public static function init(): void
    {
        add_action('admin_menu', [self::class, 'registerSubmenu']);
        add_action('admin_init', [self::class, 'handleActions']);
        add_action('admin_enqueue_scripts', [self::class, 'enqueueAssets']);
    }

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

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

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

        wp_enqueue_script(
            'amai-facebook',
            AMAI_PLUGIN_URL . 'assets/js/amai-facebook.js',
            [],
            AMAI_VERSION,
            true
        );

        wp_localize_script('amai-facebook', 'amaiF', [
            'nonce'       => wp_create_nonce('amai_facebook'),
            'ajaxUrl'     => admin_url('admin-ajax.php'),
            'pageUrl'     => admin_url('admin.php?page=automarketer-ai-facebook'),
        ]);
    }

    // --------------------------------------------------
    // Handle admin_init actions before any output
    // --------------------------------------------------
    public static function handleActions(): void
    {
        $page = sanitize_key((string) ($_GET['page'] ?? ''));
        if ($page !== 'automarketer-ai-facebook') {
            return;
        }

        // OAuth callback
        if (isset($_GET['amai_fb_callback'])) {
            self::processOAuthCallback();
            return;
        }

        // Page selection form submission
        if (
            isset($_POST['amai_fb_action']) &&
            (string) $_POST['amai_fb_action'] === 'select_page'
        ) {
            self::processPageSelection();
            return;
        }

        // Disconnect action
        if (
            isset($_POST['amai_fb_action']) &&
            (string) $_POST['amai_fb_action'] === 'disconnect'
        ) {
            self::processDisconnect();
            return;
        }
    }

    // --------------------------------------------------
    // Render — decides which template to show
    // --------------------------------------------------
    public static function render(): void
    {
        $connection = FacebookAuth::getConnection();

        // Check for pending page selection stored in transient
        $pending_pages = get_transient('amai_fb_pending_pages');
        $auth_error    = get_transient('amai_fb_auth_error');

        delete_transient('amai_fb_auth_error');

        if (is_array($pending_pages) && !empty($pending_pages)) {
            // Show page picker
            include AMAI_PLUGIN_DIR . 'templates/facebook-picker.php';
            return;
        }

        if ($connection !== null) {
            // Show full dashboard
            include AMAI_PLUGIN_DIR . 'templates/facebook.php';
            return;
        }

        // Show connection screen
        $connect_url = FacebookAuth::getAuthUrl();
        if ($connect_url === '') {
            echo '<div class="amai-notice amai-notice--warn" style="margin:32px auto;max-width:640px;padding:20px 24px;background:#FEF3C7;border:1.5px solid #FCD34D;border-radius:8px;font-size:14px;color:#78716C;">'
                . '<strong style="color:#57534E;">Facebook is not configured.</strong> '
                . 'The <code>AMAI_FB_APP_ID</code> and <code>AMAI_FB_APP_SECRET</code> constants are missing from <code>wp-config.php</code>. '
                . 'Add them to enable Facebook and Instagram.</div>';
            return;
        }
        include AMAI_PLUGIN_DIR . 'templates/facebook-connect.php';
    }

    // --------------------------------------------------
    // Process OAuth callback from Meta
    // --------------------------------------------------
    private static function processOAuthCallback(): void
    {
        if (!current_user_can('manage_automarketer_ai')) {
            wp_die('Unauthorized');
        }

        $get    = array_map('sanitize_text_field', (array) $_GET);
        $result = FacebookAuth::handleCallback($get);

        if (isset($result['error'])) {
            set_transient('amai_fb_auth_error', $result['error'], 60);
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-facebook'));
            exit;
        }

        // Store pages + user token in transient for the picker step
        set_transient('amai_fb_pending_pages', [
            'pages'      => $result['pages'],
            'user_token' => $result['user_token'],
            'fb_user_id' => $result['fb_user_id'],
        ], 300);

        wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-facebook'));
        exit;
    }

    // --------------------------------------------------
    // Process page selection from the picker form
    // --------------------------------------------------
    private static function processPageSelection(): void
    {
        if (!current_user_can('manage_automarketer_ai')) {
            wp_die('Unauthorized');
        }

        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
            'amai_fb_select_page'
        )) {
            wp_die('Nonce verification failed.');
        }

        $selected_id = sanitize_text_field((string) ($_POST['page_id'] ?? ''));
        if ($selected_id === '') {
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-facebook'));
            exit;
        }

        $pending = get_transient('amai_fb_pending_pages');
        if (!is_array($pending) || empty($pending['pages'])) {
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-facebook'));
            exit;
        }

        // Find the selected page in the pending list
        $selected_page = null;
        foreach ($pending['pages'] as $page) {
            if (is_array($page) && ($page['id'] ?? '') === $selected_id) {
                $selected_page = $page;
                break;
            }
        }

        if ($selected_page === null) {
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-facebook'));
            exit;
        }

        $saved = FacebookAuth::savePage(
            page_id:          $selected_page['id'],
            page_name:        $selected_page['name'],
            page_token:       $selected_page['access_token'],
            fb_user_id:       (string) ($pending['fb_user_id'] ?? ''),
            page_category:    $selected_page['category'] ?? null,
            page_picture_url: $selected_page['picture_url'] ?? null,
            page_followers:   isset($selected_page['followers']) ? (int) $selected_page['followers'] : null
        );

        delete_transient('amai_fb_pending_pages');

        if (!$saved) {
            set_transient('amai_fb_auth_error', 'save_failed', 60);
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-facebook'));
            exit;
        }

        // Trigger onboarding if not yet started
        $profile = new BusinessProfile();
        $data    = $profile->getOrCreate();

        if ((int) ($data['onboarding_step'] ?? 0) === BusinessProfile::STEP_NOT_STARTED) {
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-facebook&amai_onboarding=1'));
            exit;
        }

        wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-facebook&connected=1'));
        exit;
    }

    // --------------------------------------------------
    // Process disconnect request
    // --------------------------------------------------
    private static function processDisconnect(): void
    {
        if (!current_user_can('manage_automarketer_ai')) {
            wp_die('Unauthorized');
        }

        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
            'amai_fb_disconnect'
        )) {
            wp_die('Nonce verification failed.');
        }

        FacebookAuth::disconnect();

        wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-facebook&disconnected=1'));
        exit;
    }
}