<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class DeepLinkService
{
    /**
     * Generate deep link URL for a specific screen and parameters.
     */
    public function generateDeepLink(string $screen, array $parameters = []): string
    {
        $baseUrl = config('app.url', 'https://clxpro.com');
        $deepLinkUrl = "{$baseUrl}/deeplink/{$screen}";

        if (!empty($parameters)) {
            $queryParams = http_build_query($parameters);
            $deepLinkUrl .= "?{$queryParams}";
        }

        return $deepLinkUrl;
    }

    /**
     * Generate deep link for ad details.
     */
    public function generateAdDeepLink(int $adId, ?int $userId = null): string
    {
        return $this->generateDeepLink('ad-details', [
            'ad_id' => $adId,
            'user_id' => $userId
        ]);
    }

    /**
     * Generate deep link for user profile.
     */
    public function generateUserProfileDeepLink(int $userId): string
    {
        return $this->generateDeepLink('user-profile', [
            'user_id' => $userId
        ]);
    }

    /**
     * Generate deep link for category page.
     */
    public function generateCategoryDeepLink(int $categoryId, ?string $location = null): string
    {
        $params = ['category_id' => $categoryId];
        if ($location) {
            $params['location'] = $location;
        }

        return $this->generateDeepLink('category', $params);
    }

    /**
     * Generate deep link for chat conversation.
     */
    public function generateChatDeepLink(int $chatId, ?int $userId = null): string
    {
        return $this->generateDeepLink('chat', [
            'chat_id' => $chatId,
            'user_id' => $userId
        ]);
    }

    /**
     * Generate deep link for payment history.
     */
    public function generatePaymentHistoryDeepLink(int $userId): string
    {
        return $this->generateDeepLink('payment-history', [
            'user_id' => $userId
        ]);
    }

    /**
     * Generate deep link for premium plans.
     */
    public function generatePremiumPlansDeepLink(?string $planType = null): string
    {
        $params = [];
        if ($planType) {
            $params['plan_type'] = $planType;
        }

        return $this->generateDeepLink('premium-plans', $params);
    }

    /**
     * Generate deep link for notifications list.
     */
    public function generateNotificationsDeepLink(?int $userId = null): string
    {
        $params = [];
        if ($userId) {
            $params['user_id'] = $userId;
        }

        return $this->generateDeepLink('notifications', $params);
    }

    /**
     * Generate deep link for Banner Promotion.
     */
    public function generateBannerPromotionDeepLink(): string
    {
        return $this->generateDeepLink('banner-promotion');
    }

    /**
     * Generate deep link for Post Ad.
     */
    public function generatePostAdDeepLink(): string
    {
        return $this->generateDeepLink('post-ad');
    }

    /**
     * Generate deep link for Packages & Orders.
     */
    public function generatePackagesDeepLink(): string
    {
        return $this->generateDeepLink('packages');
    }

    /**
     * Generate deep link for Analytics.
     */
    public function generateAnalyticsDeepLink(): string
    {
        return $this->generateDeepLink('analytics');
    }

    /**
     * Generate deep link for Trust Score.
     */
    public function generateTrustScoreDeepLink(): string
    {
        return $this->generateDeepLink('trust-score');
    }

    /**
     * Generate deep link for My Reviews.
     */
    public function generateMyReviewsDeepLink(): string
    {
        return $this->generateDeepLink('my-reviews');
    }

     /**
     * Generate deep link for Favorites.
     */
    public function generateFavoritesDeepLink(): string
    {
        return $this->generateDeepLink('favorites');
    }

    /**
     * Generate deep link for My Plan.
     */
    public function generateMyPlanDeepLink(): string
    {
        return $this->generateDeepLink('my-plan');
    }

    /**
     * Generate deep link for Blogs List.
     */
    public function generateBlogsDeepLink(): string
    {
        return $this->generateDeepLink('blogs');
    }

    /**
     * Generate deep link for Specific Blog Detail.
     */
    public function generateBlogDetailDeepLink(string $slug): string
    {
        return $this->generateDeepLink('blog-detail', ['slug' => $slug]);
    }

    /**
     * Parse deep link URL and extract screen and parameters.
     */
    public function parseDeepLink(string $deepLinkUrl): array
    {
        $parsedUrl = parse_url($deepLinkUrl);
        
        if (!$parsedUrl || !isset($parsedUrl['path'])) {
            return ['screen' => null, 'parameters' => []];
        }

        // Extract screen from path
        $pathParts = explode('/', trim($parsedUrl['path'], '/'));
        $screen = end($pathParts);

        // Extract parameters from query string
        $parameters = [];
        if (isset($parsedUrl['query'])) {
            parse_str($parsedUrl['query'], $parameters);
        }

        return [
            'screen' => $screen,
            'parameters' => $parameters
        ];
    }

    /**
     * Validate deep link URL format.
     */
    public function validateDeepLink(string $deepLinkUrl): bool
    {
        $parsedUrl = parse_url($deepLinkUrl);
        
        if (!$parsedUrl || !isset($parsedUrl['path'])) {
            return false;
        }

        // Check if it's a valid CLX Pro deep link
        $baseUrl = config('app.url', 'https://clxpro.com');
        $expectedPath = parse_url($baseUrl, PHP_URL_PATH) . '/deeplink/';

        return Str::startsWith($parsedUrl['path'], $expectedPath);
    }

    /**
     * Get supported deep link screens.
     */
    public function getSupportedScreens(): array
    {
        return [
            'ad-details' => [
                'description' => 'Open specific ad details',
                'parameters' => ['ad_id', 'user_id']
            ],
            'user-profile' => [
                'description' => 'Open user profile',
                'parameters' => ['user_id']
            ],
            'category' => [
                'description' => 'Open category with filters',
                'parameters' => ['category_id', 'location']
            ],
            'chat' => [
                'description' => 'Open chat conversation',
                'parameters' => ['chat_id', 'user_id']
            ],
            'payment-history' => [
                'description' => 'Open payment history',
                'parameters' => ['user_id']
            ],
            'premium-plans' => [
                'description' => 'Open premium plans page',
                'parameters' => ['plan_type']
            ],
            'notifications' => [
                'description' => 'Open notifications list',
                'parameters' => ['user_id']
            ],
            'settings' => [
                'description' => 'Open app settings',
                'parameters' => []
            ]
        ];
    }

    /**
     * Generate fallback URL for web browsers.
     */
    public function generateWebFallback(string $screen, array $parameters = []): string
    {
        $baseUrl = config('app.url', 'https://clxpro.com');
        
        switch ($screen) {
            case 'ad-details':
                return "{$baseUrl}/ads/{$parameters['ad_id']}";
            case 'user-profile':
                return "{$baseUrl}/users/{$parameters['user_id']}";
            case 'category':
                $url = "{$baseUrl}/categories/{$parameters['category_id']}";
                if (isset($parameters['location'])) {
                    $url .= "?location={$parameters['location']}";
                }
                return $url;
            case 'chat':
                return "{$baseUrl}/chats/{$parameters['chat_id']}";
            case 'payment-history':
                return "{$baseUrl}/users/{$parameters['user_id']}/payments";
            case 'premium-plans':
                return "{$baseUrl}/premium-plans";
            case 'notifications':
                return "{$baseUrl}/notifications";
            default:
                return $baseUrl;
        }
    }

    /**
     * Log deep link usage for analytics.
     */
    public function logDeepLinkUsage(string $deepLinkUrl, ?int $userId = null): void
    {
        $parsed = $this->parseDeepLink($deepLinkUrl);
        
        Log::info('Deep link accessed', [
            'url' => $deepLinkUrl,
            'screen' => $parsed['screen'],
            'parameters' => $parsed['parameters'],
            'user_id' => $userId,
            'timestamp' => now()->toIso8601String()
        ]);
    }

    /**
     * Generate universal link for iOS.
     */
    public function generateUniversalLink(string $screen, array $parameters = []): string
    {
        $baseUrl = config('app.url', 'https://clxpro.com');
        return "{$baseUrl}/apple-app-site-association/{$screen}" . (!empty($parameters) ? '?' . http_build_query($parameters) : '');
    }

    /**
     * Generate app link for Android.
     */
    public function generateAppLink(string $screen, array $parameters = []): string
    {
        $packageName = config('services.app.package_name', 'com.clxpro.app');
        $deepLinkUrl = $this->generateDeepLink($screen, $parameters);
        
        return "intent://{$deepLinkUrl}#Intent;scheme=https;package={$packageName};S.browser_fallback_url={$deepLinkUrl};end";
    }
}
