<?php

namespace App\Services;

use App\Models\Setting;
use App\Services\MachineIdService;
use App\Services\LicenseDatabaseService;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class LicenseService
{
    protected $machineIdService;
    protected $licenseDb;

    public function __construct(MachineIdService $machineIdService, LicenseDatabaseService $licenseDb)
    {
        $this->machineIdService = $machineIdService;
        $this->licenseDb = $licenseDb;
    }

    /**
     * التحقق من الترخيص محلياً
     */
    public function verifyLocal(): bool
    {
        try {
            $currentMachineId = $this->machineIdService->getMachineId();
            $licenseData = $this->licenseDb->findByMachineId($currentMachineId);
            
            if (!$licenseData) {
                return false;
            }

            if ($licenseData['status'] !== 'active') {
                return false;
            }

            if (isset($licenseData['expires_at']) && $licenseData['expires_at']) {
                $expiresAt = Carbon::parse($licenseData['expires_at']);
                if (Carbon::now()->greaterThan($expiresAt)) {
                    return false;
                }
            }

            return true;
        } catch (\Exception $e) {
            \Log::error('License verification error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * التحقق من صحة تنسيق مفتاح الترخيص
     */
    protected function validateLicenseFormat(string $licenseKey, string $serialNumber): bool
    {
        $licensePattern = '/^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/';
        $serialPattern = '/^SN-[A-Z0-9]{12}$/';
        
        $licenseValid = preg_match($licensePattern, strtoupper($licenseKey));
        $serialValid = preg_match($serialPattern, strtoupper($serialNumber));
        
        return $licenseValid && $serialValid;
    }

    /**
     * التحقق من الترخيص
     */
    public function verifyLicense(string $licenseKey, string $serialNumber): array
    {
        if (!$this->validateLicenseFormat($licenseKey, $serialNumber)) {
            return [
                'valid' => false,
                'message' => 'تنسيق مفتاح الترخيص أو الرقم التسلسلي غير صحيح',
            ];
        }

        $licenseData = $this->licenseDb->find(strtoupper($licenseKey), strtoupper($serialNumber));

        if (!$licenseData) {
            return [
                'valid' => false,
                'message' => 'مفتاح الترخيص غير موجود. يرجى التواصل مع الدعم للحصول على ترخيص صحيح.',
            ];
        }

        if ($licenseData['status'] !== 'active' && $licenseData['status'] !== 'pending') {
            return [
                'valid' => false,
                'message' => 'الترخيص غير مفعّل أو معلّق',
            ];
        }

        if (isset($licenseData['expires_at']) && $licenseData['expires_at']) {
            $expiresAt = Carbon::parse($licenseData['expires_at']);
            if (Carbon::now()->greaterThan($expiresAt)) {
                return [
                    'valid' => false,
                    'message' => 'الترخيص منتهي الصلاحية',
                ];
            }
        }

        $currentMachineId = $this->machineIdService->getMachineId();
        if (isset($licenseData['machine_id']) && $licenseData['machine_id'] && $licenseData['machine_id'] !== $currentMachineId) {
            return [
                'valid' => false,
                'message' => 'هذا الترخيص مفعّل على جهاز آخر. كل ترخيص يعمل على جهاز واحد فقط.',
            ];
        }

        return [
            'valid' => true,
            'data' => [
                'status' => $licenseData['status'],
                'expires_at' => isset($licenseData['expires_at']) ? $licenseData['expires_at'] : null,
                'max_users' => $licenseData['max_users'] ?? 10,
            ],
        ];
    }

    /**
     * تفعيل الترخيص
     */
    public function activate(string $licenseKey, string $serialNumber, array $customerData = []): array
    {
        $verification = $this->verifyLicense($licenseKey, $serialNumber);

        if (!$verification['valid']) {
            return [
                'success' => false,
                'message' => $verification['message'] ?? 'مفتاح الترخيص غير صحيح',
            ];
        }

        $verificationData = $verification['data'];
        $existingLicense = $this->licenseDb->find(strtoupper($licenseKey), strtoupper($serialNumber));

        if (!$existingLicense) {
            return [
                'success' => false,
                'message' => 'خطأ في التحقق من الترخيص. يرجى التواصل مع الدعم.',
            ];
        }

        $machineId = $this->machineIdService->getMachineId();
        $machineName = $this->machineIdService->getMachineName();
        $ipAddress = request()->ip();

        $updateData = [
            'domain' => request()->getHost(),
            'machine_id' => $machineId,
            'machine_name' => $machineName,
            'ip_address' => $ipAddress,
            'email' => $customerData['email'] ?? $existingLicense['email'],
            'customer_name' => $customerData['name'] ?? $existingLicense['customer_name'],
            'status' => 'active',
            'activated_at' => Carbon::now()->format('Y-m-d H:i:s'),
            'expires_at' => isset($verificationData['expires_at']) ? $verificationData['expires_at'] : $existingLicense['expires_at'],
            'max_users' => $verificationData['max_users'] ?? $existingLicense['max_users'] ?? 10,
        ];

        $this->licenseDb->update(strtoupper($licenseKey), $updateData);

        Setting::setValue('license_key', substr(strtoupper($licenseKey), 0, 8) . '****');
        Setting::setValue('license_status', 'active');
        Setting::setValue('license_activated_at', Carbon::now()->format('Y-m-d'));

        $updatedLicense = $this->licenseDb->find(strtoupper($licenseKey), strtoupper($serialNumber));

        return [
            'success' => true,
            'message' => 'تم تفعيل الترخيص بنجاح',
            'license' => $updatedLicense,
        ];
    }

    /**
     * الحصول على معلومات الترخيص الحالي
     */
    public function getLicenseInfo(): ?array
    {
        $currentMachineId = $this->machineIdService->getMachineId();
        $licenseData = $this->licenseDb->findByMachineId($currentMachineId);

        if (!$licenseData) {
            return null;
        }

        $isValid = $licenseData['status'] === 'active';
        
        if ($isValid && isset($licenseData['expires_at']) && $licenseData['expires_at']) {
            $expiresAt = Carbon::parse($licenseData['expires_at']);
            if (Carbon::now()->greaterThan($expiresAt)) {
                $isValid = false;
            }
        }

        $daysRemaining = null;
        if (isset($licenseData['expires_at']) && $licenseData['expires_at']) {
            $expiresAt = Carbon::parse($licenseData['expires_at']);
            $daysRemaining = Carbon::now()->diffInDays($expiresAt, false);
            if ($daysRemaining < 0) {
                $daysRemaining = 0;
            }
        }

        return [
            'license_key' => substr($licenseData['license_key'], 0, 8) . '****',
            'serial_number' => $licenseData['serial_number'],
            'customer_name' => $licenseData['customer_name'] ?? null,
            'email' => $licenseData['email'] ?? null,
            'status' => $licenseData['status'],
            'activated_at' => isset($licenseData['activated_at']) ? Carbon::parse($licenseData['activated_at'])->format('Y-m-d') : null,
            'expires_at' => isset($licenseData['expires_at']) ? Carbon::parse($licenseData['expires_at'])->format('Y-m-d') : null,
            'days_remaining' => $daysRemaining,
            'max_users' => $licenseData['max_users'] ?? 10,
            'is_valid' => $isValid,
        ];
    }
}



