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

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class LinkedInChannel implements ChannelInterface
{
    // Holds pending orgs within the same request (OAuth callback -> render)
    private static ?array $inRequestPendingOrgs = null;

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

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

    public function get_color(): string
    {
        return '#0A66C2';
    }

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

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

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

        // Org selection
        if (
            isset($_POST['amai_li_action']) &&
            (string) $_POST['amai_li_action'] === 'select_org'
        ) {
            $this->processLinkedInOrgSelection();
            return;
        }

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

    // --------------------------------------------------
    // Render the appropriate LinkedIn template
    // --------------------------------------------------
    public function render(): void
    {
        $pending_orgs = self::$inRequestPendingOrgs ?? get_option('amai_li_pending_orgs', false);

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

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

        $connect_url = LinkedInAuth::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;">LinkedIn is not configured.</strong> '
                . 'The <code>AMAI_LI_CLIENT_ID</code> and <code>AMAI_LI_CLIENT_SECRET</code> constants are missing from <code>wp-config.php</code>. '
                . 'Add them to enable LinkedIn.</div>';
            return;
        }
        include AMAI_PLUGIN_DIR . 'templates/social/linkedin-connect.php';
    }

    // --------------------------------------------------
    // Expose in-request pending orgs for render()
    // --------------------------------------------------
    public static function getInRequestPendingOrgs(): ?array
    {
        return self::$inRequestPendingOrgs;
    }

    // --------------------------------------------------
    // Process LinkedIn OAuth callback
    // --------------------------------------------------
    private function processLinkedInCallback(): void
    {
        if (!current_user_can('manage_automarketer_ai')) {
            wp_die('Unauthorized');
        }

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

        if (isset($result['error'])) {
            $error = $result['error'];

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

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

        $pending = [
            'orgs'          => $result['orgs'],
            'access_token'  => $result['access_token'],
            'refresh_token' => $result['refresh_token'],
            'expires_in'    => $result['expires_in'],
            'refresh_in'    => $result['refresh_in'],
            'member_id'     => $result['member_id'],
            'member_name'   => $result['member_name'],
        ];

        self::$inRequestPendingOrgs = $pending;

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

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

    // --------------------------------------------------
    // Process LinkedIn org selection
    // --------------------------------------------------
    private function processLinkedInOrgSelection(): void
    {
        if (!current_user_can('manage_automarketer_ai')) {
            wp_die('Unauthorized');
        }

        $selected_urn    = sanitize_text_field((string) ($_POST['organization_urn'] ?? ''));
        $pending_payload = (string)              ($_POST['pending_payload']    ?? '');
        $pending_sig     = (string)              ($_POST['pending_sig']        ?? '');

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

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

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

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

        $selected_org = null;
        foreach ($pending['orgs'] as $org) {
            if (is_array($org) && ($org['organization_urn'] ?? '') === $selected_urn) {
                $selected_org = $org;
                break;
            }
        }

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

        $saved = LinkedInAuth::saveOrg(
            organization_urn:  $selected_org['organization_urn'],
            organization_id:   $selected_org['organization_id'],
            organization_name: $selected_org['organization_name'],
            org_picture_url:   $selected_org['picture_url']  ?? null,
            org_followers:     isset($selected_org['followers']) ? (int) $selected_org['followers'] : null,
            access_token:      (string) ($pending['access_token']  ?? ''),
            refresh_token:     (string) ($pending['refresh_token'] ?? ''),
            expires_in:        (int)    ($pending['expires_in']    ?? 0),
            refresh_in:        (int)    ($pending['refresh_in']    ?? 0),
            member_id:         (string) ($pending['member_id']     ?? ''),
            member_name:       (string) ($pending['member_name']   ?? '')
        );

        delete_option('amai_li_pending_orgs');

        if (!$saved) {
            set_transient('amai_li_auth_error', 'save_failed', 60);
            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-social&channel=linkedin'));
            exit;
        }

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

    // --------------------------------------------------
    // Process LinkedIn disconnect
    // --------------------------------------------------
    private function processLinkedInDisconnect(): 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_li_disconnect'
        )) {
            wp_die('Nonce verification failed.');
        }

        LinkedInAuth::disconnect();
        LinkedInAuth::clearScheduledRefresh();

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