<?php

namespace App\Http\Controllers;

use App\Services\EnvatoService;
use App\Models\License;
use App\Models\LicenseDomain;
use App\Models\Product;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;

class LicenseStatusController extends Controller
{
    /**
     * Display the license status check page.
     */
    public function index()
    {
        return view('license-status');
    }

    /**
     * Check license status.
     */
    public function check(Request $request)
    {
        try {
            // Rate limiting
            $ip = $request->ip();
            $settings = Setting::first();
            $maxAttempts = $settings->license_max_attempts ?? 5;
            $decayMinutes = $settings->license_lockout_minutes ?? 15;

            $key = 'license_check_' . md5($ip);
            $attempts = Cache::get($key, 0);

            if ($attempts >= $maxAttempts) {
                return response()->json([
                    'success' => false,
                    'message' => __('license_status.verification_error') . ': Too many attempts. Please try again later.'
                ], 429);
            }

            Cache::put($key, $attempts + 1, now()->addMinutes($decayMinutes));

            $validator = Validator::make($request->all(), [
                'license_key' => 'required|string|max:255',
                'email' => 'required|email|max:255',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Please enter all required data correctly.',
                    'errors' => $validator->errors()
                ], 422);
            }

            $licenseCode = $request->input('license_key');
            $email = $request->input('email');

            // Search for license by code and email
            $license = License::where('license_key', $licenseCode)
                ->whereHas('user', function($subQ) use ($email) {
                    $subQ->where('email', $email);
                })
                ->with(['product', 'user', 'domains'])
                ->first();

            if (!$license) {
                // Try to find by purchase code for Envato licenses
                $license = License::where('purchase_code', $licenseCode)
                    ->whereHas('user', function($subQ) use ($email) {
                        $subQ->where('email', $email);
                    })
                    ->with(['product', 'user', 'domains'])
                    ->first();
            }

        if (!$license) {
            return response()->json([
                'success' => false,
                'message' => __('license_status.license_not_found')
            ], 404);
        }        // Determine license type
        $licenseType = $this->determineLicenseType($license);

        // For Envato licenses, verify with Envato API (optional additional check)
        $envatoData = null;
        if ($licenseType === __('license_status.envato') && $license->purchase_code) {
            $envatoService = new EnvatoService();
            try {
                $envatoData = $envatoService->verifyPurchase($license->purchase_code);
            } catch (\Exception $ex) {
                $envatoData = null;
            }

            if (!$envatoData) {
                // We'll add this flag to the response below
            }
        }

        // Check license status
        $status = $this->getLicenseStatus($license);

            // Get license details
            $licenseDetails = [
                'license_key' => $license->license_key,
                'purchase_code' => $license->purchase_code,
                'email' => $license->user ? $license->user->email : $email,
                'status' => $status,
                'license_type' => $licenseType,
                'product_name' => $license->product ? $license->product->name : 'Not specified',
                'created_at' => $license->created_at->format('Y-m-d H:i:s'),
                'expires_at' => $license->license_expires_at ? $license->license_expires_at->format('Y-m-d H:i:s') : null,
                'is_expired' => $license->license_expires_at && $license->license_expires_at->isPast(),
                'days_remaining' => $license->license_expires_at ? max(0, now()->diffInDays($license->license_expires_at, false)) : null,
                'domains' => $license->domains->map(function ($domain) {
                    return [
                        'domain' => $domain->domain,
                        'status' => $domain->status,
                        'ip_address' => $domain->ip_address,
                        'created_at' => $domain->created_at->format('Y-m-d H:i:s'),
                    ];
                }),
                'supported_until' => $license->supported_until ? $license->supported_until->format('Y-m-d H:i:s') : null,
                'max_domains' => $license->max_domains ?? 1,
                'used_domains' => $license->domains->count(),
                // Attach envato verification results when available
                'envato_data' => $envatoData,
                'envato_verification' => $envatoData ? 'success' : 'failed',
            ];

            // Reset attempts on success
            Cache::forget($key);

            return response()->json([
                'success' => true,
                'message' => __('license_status.license_found_success'),
                // frontend expects .license on the returned object (data.license)
                'license' => $licenseDetails
            ]);
        } catch (\Exception $e) {
            // License check error occurred
            return response()->json([
                'success' => false,
                'message' => __('license_status.unexpected_error')
            ], 500);
        }
    }

    /**
     * Determine license type (Custom or Envato).
     */
    private function determineLicenseType($license)
    {
        if ($license->purchase_code && strlen($license->purchase_code) > 10) {
            return __('license_status.envato');
        }

        return __('license_status.custom');
    }

    /**
     * Get license status with Arabic labels.
     */
    private function getLicenseStatus($license)
    {
        if ($license->status === 'active') {
            if ($license->license_expires_at && $license->license_expires_at->isPast()) {
                return __('license_status.expired');
            }
            return __('license_status.active');
        } elseif ($license->status === 'inactive') {
            return __('license_status.inactive');
        } elseif ($license->status === 'suspended') {
            return __('license_status.revoked');
        } elseif ($license->status === 'expired') {
            return __('license_status.expired');
        }

        return 'Unknown';
    }

    /**
     * Get license history/logs.
     */
    public function history(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'license_key' => 'required|string|max:255',
            'email' => 'required|email|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => __('license_status.validation_error'),
                'errors' => $validator->errors()
            ], 422);
        }

    $licenseCode = $request->input('license_key');
        $email = $request->input('email');

        $license = License::where('license_key', $licenseCode)
            ->whereHas('user', function($q) use ($email) {
                $q->where('email', $email);
            })
            ->first();

        if (!$license) {
            $license = License::where('purchase_code', $licenseCode)
                ->whereHas('user', function($q) use ($email) {
                    $q->where('email', $email);
                })
                ->first();
        }

        if (!$license) {
            return response()->json([
                'success' => false,
                'message' => 'No license found with this data.'
            ], 404);
        }

        $logs = $license->logs()
            ->orderBy('created_at', 'desc')
            ->limit(50)
            ->get()
            ->map(function ($log) {
                return [
                    'action' => $log->action,
                    'status' => $log->status,
                    'ip_address' => $log->ip_address,
                    'user_agent' => $log->user_agent,
                    'created_at' => $log->created_at->format('Y-m-d H:i:s'),
                    'message' => $log->message,
                ];
            });

        return response()->json([
            'success' => true,
            'data' => $logs
        ]);
    }
}