<?php
/**
 * 📧 GMAIL CONTROLLER - V2.2 PURE
 *
 * Manages Gmail integration:
 * - OAuth 2.0 authentication flow
 * - Gmail API integration
 * - Token management
 * - Settings configuration
 *
 * @package FleekDash\Controllers
 * @since 2.2.0
 */

namespace FleekDash\Controllers;

use WP_REST_Request;
use WP_Error;
use FleekDash\Services\ResponseService;

/**
 * Class GmailController
 *
 * Pure V2.2 Controller - Minimal legacy dependencies
 * Uses GmailService for actual API calls but manages flow via ResponseService
 *
 * @package FleekDash\Controllers
 */
class GmailController
{
    /**
     * 🔐 Initialize Gmail OAuth flow
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function init_auth(WP_REST_Request $request)
    {
        try {
            // Get Gmail OAuth client settings
            $client_id = \get_option('fleekdash_gmail_client_id', '');
            $client_secret = \get_option('fleekdash_gmail_client_secret', '');

            if (empty($client_id) || empty($client_secret)) {
                return ResponseService::error(
                    'Gmail API credentials not configured',
                    ['configure_url' => \admin_url('admin.php?page=fleekdash-integrations')],
                    400
                );
            }

            // Load Gmail client if available
            if (!class_exists('Google_Client')) {
                return ResponseService::error(
                    'Google Client library not available',
                    null,
                    500
                );
            }

            // Create OAuth URL
            $client = new \Google_Client();
            $client->setClientId($client_id);
            $client->setClientSecret($client_secret);
            $client->setRedirectUri(\admin_url('admin-ajax.php?action=fleekdash_gmail_callback'));
            $client->addScope(\Google_Service_Gmail::GMAIL_READONLY);
            $client->setAccessType('offline');
            $client->setPrompt('consent');

            $auth_url = $client->createAuthUrl();

            return ResponseService::success('Gmail OAuth URL generated', [
                'authUrl' => $auth_url
            ]);

        } catch (\Exception $e) {
            return ResponseService::error(
                'Failed to initialize Gmail authentication',
                ['error' => $e->getMessage()],
                500
            );
        }
    }

    /**
     * 🔄 Handle Gmail OAuth callback
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function handle_callback(WP_REST_Request $request)
    {
        try {
            $code = $request->get_param('code');

            if (empty($code)) {
                return ResponseService::error('Authorization code is missing', null, 400);
            }

            // Get Gmail OAuth client settings
            $client_id = \get_option('fleekdash_gmail_client_id', '');
            $client_secret = \get_option('fleekdash_gmail_client_secret', '');

            if (!class_exists('Google_Client')) {
                return ResponseService::error('Google Client library not available', null, 500);
            }

            // Exchange authorization code for access token
            $client = new \Google_Client();
            $client->setClientId($client_id);
            $client->setClientSecret($client_secret);
            $client->setRedirectUri(\admin_url('admin-ajax.php?action=fleekdash_gmail_callback'));

            $token = $client->fetchAccessTokenWithAuthCode($code);

            if (isset($token['error'])) {
                return ResponseService::error(
                    'Failed to get access token',
                    ['error' => $token['error_description'] ?? 'Unknown error'],
                    500
                );
            }

            // Store the token in WordPress user meta
            $user_id = \get_current_user_id();
            \update_user_meta($user_id, 'fleekdash_gmail_token', $token);

            return ResponseService::success('Gmail connected successfully', [
                'redirect' => \admin_url('admin.php?page=fleekdash-accounts&connection=gmail&status=success')
            ]);

        } catch (\Exception $e) {
            return ResponseService::error(
                'OAuth callback failed',
                ['error' => $e->getMessage()],
                500
            );
        }
    }

    /**
     * 📬 List Gmail messages
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function list_messages(WP_REST_Request $request)
    {
        try {
            // Check if Google Client library is available
            if (!class_exists('Google_Client')) {
                return ResponseService::success('Gmail integration requires Google Client library', [
                    'messages' => [],
                    'info' => 'Install Google API PHP Client to enable Gmail features'
                ]);
            }

            // Use GmailEndpoints API if available
            if (class_exists('FleekDash\API\GmailEndpoints')) {
                require_once FLEEKDASH_PLUGIN_DIR . 'includes/API/GmailEndpoints.php';
                $gmail_api = new \FleekDash\API\GmailEndpoints();
                return $gmail_api->list_messages($request);
            }

            // Graceful fallback
            return ResponseService::success('Gmail integration available but not configured', [
                'messages' => [],
                'info' => 'Configure Gmail integration in settings'
            ]);

        } catch (\Exception $e) {
            return ResponseService::error(
                'Failed to retrieve Gmail messages',
                ['error' => $e->getMessage()],
                500
            );
        }
    }

    /**
     * 📨 Get specific Gmail message
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function get_message(WP_REST_Request $request)
    {
        try {
            $message_id = $request->get_param('id');

            if (empty($message_id)) {
                return ResponseService::error('Message ID is required', null, 400);
            }

            // Check if Google Client library is available
            if (!class_exists('Google_Client')) {
                return ResponseService::error(
                    'Gmail integration requires Google Client library',
                    ['info' => 'Install Google API PHP Client'],
                    503
                );
            }

            // Use GmailEndpoints API if available
            if (class_exists('FleekDash\API\GmailEndpoints')) {
                require_once FLEEKDASH_PLUGIN_DIR . 'includes/API/GmailEndpoints.php';
                $gmail_api = new \FleekDash\API\GmailEndpoints();
                return $gmail_api->get_message($request);
            }

            // Graceful fallback
            return ResponseService::error('Gmail integration not fully configured', null, 500);

        } catch (\Exception $e) {
            return ResponseService::error(
                'Failed to retrieve Gmail message',
                ['error' => $e->getMessage()],
                500
            );
        }
    }

    /**
     * 🔌 Disconnect Gmail account
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function disconnect(WP_REST_Request $request)
    {
        try {
            $user_id = \get_current_user_id();
            \delete_user_meta($user_id, 'fleekdash_gmail_token');

            return ResponseService::success('Gmail disconnected successfully');

        } catch (\Exception $e) {
            return ResponseService::error(
                'Failed to disconnect Gmail',
                ['error' => $e->getMessage()],
                500
            );
        }
    }

    /**
     * ⚙️ Get Gmail settings
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function get_settings(WP_REST_Request $request)
    {
        try {
            $settings = [
                'fleekdash_gmail_client_id' => \get_option('fleekdash_gmail_client_id', ''),
                'fleekdash_gmail_client_secret' => \get_option('fleekdash_gmail_client_secret', ''),
            ];

            return ResponseService::success('Gmail settings retrieved', $settings);

        } catch (\Exception $e) {
            return ResponseService::error(
                'Failed to retrieve Gmail settings',
                ['error' => $e->getMessage()],
                500
            );
        }
    }

    /**
     * 🔧 Update Gmail settings
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function update_settings(WP_REST_Request $request)
    {
        try {
            $params = $request->get_json_params();

            if (!isset($params['fleekdash_gmail_client_id']) || !isset($params['fleekdash_gmail_client_secret'])) {
                return ResponseService::error(
                    'Client ID and Client Secret are required',
                    null,
                    400
                );
            }

            $client_id = \sanitize_text_field($params['fleekdash_gmail_client_id']);
            $client_secret = \sanitize_text_field($params['fleekdash_gmail_client_secret']);

            \update_option('fleekdash_gmail_client_id', $client_id);
            \update_option('fleekdash_gmail_client_secret', $client_secret);

            return ResponseService::success('Gmail settings updated successfully');

        } catch (\Exception $e) {
            return ResponseService::error(
                'Failed to update Gmail settings',
                ['error' => $e->getMessage()],
                500
            );
        }
    }
}
