<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /includes/class-facebook-channel.php
// Description: Facebook social channel — implements ChannelInterface, owns all FB OAuth and render logic - NUCLEAR+++
// Last Edited: 2026-03-28
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class FacebookChannel implements ChannelInterface
{
    // Holds pending pages within the same request (OAuth callback → render)
    private static ?array $inRequestPendingPages = null;

    public function get_slug(): string
    {
        return 'facebook';
    }

    public function get_label(): string
    {
        return 'Facebook';
    }

    public function get_color(): string
    {
        return '#1877F2';
    }

    public function is_available(): bool
    {
        return true;
    }

    public function get_connection_status(): string
    {
        return FacebookAuth::getConnection() !== null ? 'connected' : 'disconnected';
    }

    // --------------------------------------------------
    // Handle all Facebook GET/POST actions
    // --------------------------------------------------
    public function handle_actions(): void
    {
        // OAuth callback from Facebook
        if (isset($_GET['amai_fb_callback'])) {
            $this->processFacebookCallback();
            return;
        }

        // Page selection
        if (
            isset($_POST['amai_fb_action']) &&
            (string) $_POST['amai_fb_action'] === 'select_page'
        ) {
            $this->processFacebookPageSelection();
            return;
        }

        // Disconnect
        if (
            isset($_POST['amai_fb_action']) &&
            (string) $_POST['amai_fb_action'] === 'disconnect'
        ) {
            $this->processFacebookDisconnect();
            return;
        }
    }

    // --------------------------------------------------
    // Render the appropriate Facebook template
    // --------------------------------------------------
    public function render(): void
    {
        $pending_pages = self::$inRequestPendingPages ?? get_option('amai_fb_pending_pages', false);

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

        if ($this->get_connection_status() === 'connected') {
            include AMAI_PLUGIN_DIR . 'templates/social/facebook-dashboard.php';
            return;
        }

        $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/social/facebook-connect.php';
    }

    // --------------------------------------------------
    // Expose in-request pending pages for render()
    // (called by SocialPage after handle_actions() fires)
    // --------------------------------------------------
    public static function getInRequestPendingPages(): ?array
    {
        return self::$inRequestPendingPages;
    }

    // --------------------------------------------------
    // Process Facebook OAuth callback
    // --------------------------------------------------
    private function processFacebookCallback(): 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'])) {
            $error = $result['error'];

            if ($error === 'authorization_cancelled' || isset($get['error'])) {
                set_transient('amai_fb_auth_error', 'user_cancelled', 60);
            } else {
                set_transient('amai_fb_auth_error', $error, 60);
            }

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

        $pending = [
            'pages'      => $result['pages'],
            'user_token' => $result['user_token'],
            'fb_user_id' => $result['fb_user_id'],
        ];

        self::$inRequestPendingPages = $pending;

        delete_option('amai_fb_pending_pages');
        update_option('amai_fb_pending_pages', $pending, false);

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

    // --------------------------------------------------
    // Process Facebook page selection
    // --------------------------------------------------
    private function processFacebookPageSelection(): void
    {
        if (!current_user_can('manage_automarketer_ai')) {
            wp_die('Unauthorized');
        }

        $selected_id     = sanitize_text_field((string) ($_POST['page_id']        ?? ''));
        $pending_payload = (string)              ($_POST['pending_payload'] ?? '');
        $pending_sig     = (string)              ($_POST['pending_sig']     ?? '');

        if ($selected_id === '') {
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-social&channel=facebook'));
            exit;
        }

        $pending = FacebookAuth::verifyPending($pending_payload, $pending_sig);

        if (!is_array($pending) || empty($pending['pages'])) {
            $pending = get_option('amai_fb_pending_pages', false);
        }

        if (!is_array($pending) || empty($pending['pages'])) {
            set_transient('amai_fb_auth_error', 'session_expired', 60);
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-social&channel=facebook'));
            exit;
        }

        $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-social&channel=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_option('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-social&channel=facebook'));
            exit;
        }

        $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-social&channel=facebook&amai_onboarding=1'));
            exit;
        }

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

    // --------------------------------------------------
    // Process Facebook disconnect
    // --------------------------------------------------
    private function processFacebookDisconnect(): 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-social&channel=facebook&disconnected=1'));
        exit;
    }
}