<?php

namespace App\Modules\Registrar\Dummyregistrar;

use App\Core\Registrar\AbstractRegistrar;
use App\Jobs\SendEmailJob;
use App\Models\Setting;
use Illuminate\Support\Facades\Log;

class Dummyregistrar extends AbstractRegistrar
{
    /**
     * Template mapping for client notifications per action
     */
    /**
     * Template mapping for client notifications per action.
     *
     * NOTE: register/transfer/renew are handled centrally by
     * DomainProvisioningService (see sendProvisioningSuccessEmail / line ~984)
     * so we deliberately leave them null here to avoid duplicate emails.
     */
    private const CLIENT_TEMPLATES = [
        'Domain Register' => null,
        'Domain Transfer' => null,
        'Domain Renew' => null,
        'Update Nameservers' => 'Domain Nameservers Updated',
        'Update Contacts' => 'Domain Contacts Updated',
        'Update Domain Lock' => 'Domain Lock Status Changed',
        'Update Privacy' => 'Domain Privacy Updated',
        'Send EPP Code' => 'Domain EPP Code Sent',
        'Add DNS Record' => 'Domain DNS Records Updated',
        'Update DNS Record' => 'Domain DNS Records Updated',
        'Delete DNS Record' => 'Domain DNS Records Updated',
        'Bulk Update DNS Records' => 'Domain DNS Records Updated',
        'Domain Delete' => 'Domain Deleted',
        'Domain Sync' => null,
    ];

    /**
     * Send admin + client notification emails for dummy registrar operations.
     * Shows full input parameters and return value in the email body.
     *
     * PRC-49: caller artık `DomainModuleParamsBuilder::build()` ile enriched
     * `$params` gönderiyor — modül DB'ye dokunmaz, `$params`'a güvenir.
     *
     * PRC-48: `dummy_registrar_email_notifications_enabled = 0` (default 1) ile
     * tamamen kapatılabilir (production test trafiğini bastırmak için).
     */
    protected function notifyAdmin(string $action, array $params = [], array $result = []): void
    {
        if (! Setting::getValue('dummy_registrar_email_notifications_enabled', true)) {
            return;
        }

        $domain = $params['domain'] ?? 'unknown';

        try {
            $adminEmail = Setting::getValue('company_email');
            if (! $adminEmail) {
                return;
            }

            // Caller already passed enriched params with domain_id when available.
            $entityType = isset($params['domain_id']) ? 'domain' : 'client';
            $entityId = $params['domain_id'] ?? 1;

            $jsonFlags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
            $maskedConfig = $this->maskSensitiveConfig($this->config ?? []);

            SendEmailJob::dispatch(
                'Dummy Registrar Admin Notification',
                $entityType,
                $entityId,
                [
                    'ACTION' => $action,
                    // Both DOMAINNAME (legacy template) and DOMAIN (Jira-spec alias) — keep both
                    // so existing customised templates continue to work.
                    'DOMAINNAME' => $domain,
                    'DOMAIN' => $domain,
                    'ACTIONDATE' => now()->format('d/m/Y H:i:s'),
                    // DETAILS = pretty-formatted HTML block (Module Config + Input + Return)
                    'DETAILS' => $this->formatActionDetails($params, $result, $maskedConfig),
                    // Raw JSON aliases — useful if a template is customised to render its own layout.
                    'PARAMS' => json_encode($params, $jsonFlags) ?: '[]',
                    'RESULT' => json_encode($result, $jsonFlags) ?: '[]',
                    'MODULE_CONFIG' => json_encode($maskedConfig, $jsonFlags) ?: '[]',
                ],
                null,
                $adminEmail
            );

            // Also send client notification if a matching template exists
            $this->notifyClient($action, $domain, $params, $result);
        } catch (\Exception $e) {
            Log::warning('Dummyregistrar: Admin notification failed', [
                'action' => $action,
                'domain' => $domain,
                'error' => $e->getMessage(),
            ]);
        }
    }

    /**
     * Send client notification email for domain operations.
     *
     * PRC-49: caller already passed enriched `$params` from
     * `DomainModuleParamsBuilder::build()`; we no longer hit the DB here.
     */
    protected function notifyClient(string $action, string $domain, array $params = [], array $result = []): void
    {
        $templateName = self::CLIENT_TEMPLATES[$action] ?? null;
        if (! $templateName) {
            return;
        }

        $domainId = $params['domain_id'] ?? null;
        $clientEmail = $params['client_email'] ?? null;
        if (! $domainId || ! $clientEmail) {
            return;
        }

        try {
            $firstName = $params['client_first_name'] ?? '';
            $lastName = $params['client_last_name'] ?? '';

            // ISO format dates from builder; reformat to d.m.Y for templates
            $expireDate = $params['expire_date']
                ? \Carbon\Carbon::parse($params['expire_date'])->format('d.m.Y')
                : null;
            $registerDate = $params['register_date']
                ? \Carbon\Carbon::parse($params['register_date'])->format('d.m.Y')
                : null;

            $mergeFields = [
                'FIRSTNAME' => $firstName,
                'LASTNAME' => $lastName,
                'CLIENT_NAME' => trim($firstName.' '.$lastName),
                'DOMAIN' => $domain,
                'PERIOD' => $params['period'] ?? null,
                'REGISTRATIONDATE' => $registerDate,
                'EXPIRYDATE' => $expireDate,
                'EXPIRY_DATE' => $expireDate,
                'REGISTRAR' => $params['module'] ?: 'dummyregistrar',
                'DOMAINURL' => route('store.auth.domains.manage', $domainId),
            ];

            // Action'a özel merge field'lar
            $mergeFields = array_merge($mergeFields, $this->getClientMergeFields($action, $params, $result));

            SendEmailJob::dispatch(
                $templateName,
                'domain',
                $domainId,
                $mergeFields,
                $params['client_language'] ?? 'tr',
                $clientEmail
            );
        } catch (\Exception $e) {
            Log::warning('Dummyregistrar: Client notification failed', [
                'action' => $action,
                'domain' => $domain,
                'template' => $templateName,
                'error' => $e->getMessage(),
            ]);
        }
    }

    /**
     * Action'a özel client merge field'larını döndürür
     */
    private function getClientMergeFields(string $action, array $params, array $result): array
    {
        $data = $result['data'] ?? [];

        return match ($action) {
            'Update Nameservers' => [
                'NAMESERVERS' => implode(', ', $params['nameservers'] ?? []),
                'NAMESERVER1' => $params['nameservers'][0] ?? '',
                'NAMESERVER2' => $params['nameservers'][1] ?? '',
                'NAMESERVER3' => $params['nameservers'][2] ?? '',
                'NAMESERVER4' => $params['nameservers'][3] ?? '',
            ],
            'Update Contacts' => [
                'UPDATED_GROUPS' => implode(', ', array_keys($params['groups'] ?? [])),
            ],
            'Update Domain Lock' => [
                'LOCK_STATUS' => ($params['lock'] ?? $params['lock_status'] ?? true) ? 'Kilitli (Locked)' : 'Açık (Unlocked)',
                'TRANSFER_ALLOWED' => ($params['lock'] ?? true) ? 'Hayır' : 'Evet',
            ],
            'Update Privacy' => [
                'PRIVACY_STATUS' => ($params['id_protection'] ?? $params['privacy_enabled'] ?? true) ? 'Aktif (Enabled)' : 'Devre Dışı (Disabled)',
                'WHOIS_MASKED' => ($params['id_protection'] ?? true) ? 'Evet' : 'Hayır',
            ],
            'Send EPP Code' => [
                'EPP_CODE' => $data['epp_code'] ?? '',
                'EPP_SENT_TO' => $data['sent_to'] ?? '',
                'EPP_VALID_UNTIL' => isset($data['valid_until']) ? date('d.m.Y', strtotime($data['valid_until'])) : '',
            ],
            'Add DNS Record', 'Update DNS Record', 'Delete DNS Record', 'Bulk Update DNS Records' => [
                'RECORD_TYPE' => $params['type'] ?? $data['type'] ?? '',
                'RECORD_NAME' => $params['name'] ?? $data['name'] ?? '',
                'RECORD_VALUE' => $params['value'] ?? $data['value'] ?? '',
                'RECORD_TTL' => (string) ($params['ttl'] ?? $data['ttl'] ?? '3600'),
                'DNS_ACTION' => match ($action) {
                    'Add DNS Record' => 'eklendi',
                    'Update DNS Record' => 'güncellendi',
                    'Delete DNS Record' => 'silindi',
                    default => 'güncellendi',
                },
            ],
            'Domain Delete' => [
                'DELETED_AT' => $data['deleted_at'] ?? now()->format('d.m.Y H:i'),
            ],
            default => [],
        };
    }

    /**
     * Action için HTML formatlı detay bloğu — module config + input params + return value.
     *
     * PRC-49: `$params` artık `DomainModuleParamsBuilder` üzerinden enriched
     * gelir; modül kendisi DB'den hydrate etmez (`enrichParams()` silindi).
     * PRC-48: `$moduleConfig` sensitive field'ları (api_secret/api_key/password/token)
     * mask edilmiş halde, mail body'sinde "Module Configuration" bloğu olarak gösterilir.
     */
    private function formatActionDetails(array $params, array $result, array $moduleConfig = []): string
    {
        $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
        $paramsJson = json_encode($params, $flags) ?: '[]';
        $resultJson = json_encode($result, $flags) ?: '[]';
        $configJson = json_encode($moduleConfig, $flags) ?: '[]';

        $preStyle = 'background:#f5f5f5;border:1px solid #ddd;padding:12px;border-radius:4px;'
            .'font-family:Menlo,Monaco,Consolas,monospace;font-size:12px;white-space:pre-wrap;'
            .'word-wrap:break-word;overflow-x:auto;color:#333;';

        $block = function (string $label, string $json) use ($preStyle) {
            return '<p style="margin:16px 0 4px 0;"><strong>'.$label.':</strong></p>'
                .'<pre style="'.$preStyle.'">'.htmlspecialchars($json, ENT_QUOTES, 'UTF-8').'</pre>';
        };

        $sections = '<div style="margin-top:10px;">';
        if (! empty($moduleConfig)) {
            $sections .= $block('Module Configuration (sensitive fields masked)', $configJson);
        }
        $sections .= $block('Input Parameters', $paramsJson)
            .$block('Return Value', $resultJson)
            .'</div>';

        return $sections;
    }

    /**
     * Mask sensitive registrar config fields before including in email body.
     * Anything matching `secret|password|token|key` (case-insensitive) is replaced
     * with the literal "***" — `api_url`, `test_mode`, etc. pass through.
     */
    private function maskSensitiveConfig(array $config): array
    {
        $sensitivePattern = '/(secret|password|token|key)/i';
        $masked = [];
        foreach ($config as $key => $value) {
            if (is_string($key) && preg_match($sensitivePattern, $key) && $value !== '' && $value !== null) {
                $masked[$key] = '***';
                continue;
            }
            $masked[$key] = $value;
        }
        return $masked;
    }

    /**
     * Domain kaydı oluşturur (kayıt)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function registerDomain(array $params)
    {
        $requiredParams = ['domain', 'period'];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => "Gerekli parametre eksik: {$param}",
                ];
            }
        }

        // Dummy domain kaydı oluşturma (gerçek API çağrısı yok)
        $orderId = 'DUMMY_REG_'.strtoupper(uniqid());
        $result = [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_register_success'),
            'data' => [
                'order_id' => $orderId,
                'domain' => $params['domain'],
                'sld' => $params['sld'] ?? explode('.', $params['domain'])[0],
                'tld' => $params['tld'] ?? implode('.', array_slice(explode('.', $params['domain']), 1)),
                'period' => $params['period'],
                'registrar' => 'dummyregistrar',
                'registered_at' => now()->toISOString(),
                'expires_at' => now()->addYears($params['period'])->toISOString(),
                'nameservers' => $params['nameservers'] ?? ['ns1.dummy.com', 'ns2.dummy.com'],
                'auto_renew' => $params['auto_renew'] ?? false,
                'id_protection' => $params['id_protection'] ?? false,
                'registrant' => $params['registrant'] ?? null,
                'admin_contact' => $params['admin'] ?? null,
                'tech_contact' => $params['tech'] ?? null,
                'client_id' => $params['client_id'] ?? null,
                'client_email' => $params['client_email'] ?? null,
                'whois_status' => 'registered',
                'domain_status' => ['clientTransferProhibited', 'clientDeleteProhibited'],
                'additional_fields' => $params['additional_fields'] ?? [],
            ],
        ];

        Log::info('Dummyregistrar: Domain registered', [
            'action' => 'registered',
            'domain' => $params['domain'],
            'period' => $params['period'],
            'order_id' => $orderId,
        ]);

        $this->notifyAdmin('Domain Register', $params, $result);

        return $result;
    }

    /**
     * Domain transferi yapar
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function transferDomain(array $params)
    {
        $requiredParams = ['domain', 'epp_code'];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => "Gerekli parametre eksik: {$param}",
                ];
            }
        }

        $transferId = 'DUMMY_TRANS_'.strtoupper(uniqid());
        $period = $params['period'] ?? 1;

        $result = [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_transfer_success'),
            'data' => [
                'transfer_id' => $transferId,
                'domain' => $params['domain'],
                'sld' => $params['sld'] ?? explode('.', $params['domain'])[0],
                'tld' => $params['tld'] ?? implode('.', array_slice(explode('.', $params['domain']), 1)),
                'epp_code' => str_repeat('*', strlen($params['epp_code'] ?? '')),
                'period' => $period,
                'registrar' => 'dummyregistrar',
                'transfer_status' => 'pending',
                'transfer_started_at' => now()->toISOString(),
                'estimated_completion' => now()->addDays(5)->toISOString(),
                'expires_at' => now()->addYears($period)->toISOString(),
                'registrant' => $params['registrant'] ?? null,
                'client_id' => $params['client_id'] ?? null,
                'client_email' => $params['client_email'] ?? null,
                'nameservers' => $params['nameservers'] ?? ['ns1.dummy.com', 'ns2.dummy.com'],
            ],
        ];

        $this->notifyAdmin('Domain Transfer', $params, $result);

        return $result;
    }

    /**
     * Domain yenileme yapar
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function renewDomain(array $params)
    {
        $requiredParams = ['domain', 'period'];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => "Gerekli parametre eksik: {$param}",
                ];
            }
        }

        $renewalId = 'DUMMY_REN_'.strtoupper(uniqid());
        $currentExpiry = $params['current_expiry'] ?? now()->toISOString();
        $newExpiry = now()->addYears($params['period'])->toISOString();

        $result = [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_renew_success'),
            'data' => [
                'renewal_id' => $renewalId,
                'domain' => $params['domain'],
                'sld' => $params['sld'] ?? explode('.', $params['domain'])[0],
                'tld' => $params['tld'] ?? implode('.', array_slice(explode('.', $params['domain']), 1)),
                'period' => $params['period'],
                'registrar' => 'dummyregistrar',
                'renewed_at' => now()->toISOString(),
                'previous_expiry' => $currentExpiry,
                'new_expiry' => $newExpiry,
                'auto_renew' => $params['auto_renew'] ?? false,
                'client_id' => $params['client_id'] ?? null,
                'client_email' => $params['client_email'] ?? null,
            ],
        ];

        $this->notifyAdmin('Domain Renew', $params, $result);

        return $result;
    }

    /**
     * Nameserver ayarlarını değiştirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function setNameservers(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        if (! isset($params['nameservers']) || ! is_array($params['nameservers'])) {
            return [
                'status' => 'error',
                'message' => 'Nameserver listesi gerekli',
            ];
        }

        $result = [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_update_nameservers_success'),
            'data' => [
                'domain' => $params['domain'],
                'registrar' => 'dummyregistrar',
                'previous_nameservers' => ['ns1.dummy.com', 'ns2.dummy.com'],
                'new_nameservers' => $params['nameservers'],
                'propagation_estimated' => '24-48 hours',
                'updated_at' => now()->toISOString(),
            ],
        ];

        $this->notifyAdmin('Update Nameservers', $params, $result);

        return $result;
    }

    /**
     * Nameserver ayarlarını getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function getNameservers(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        return [
            'status' => 'success',
            'message' => 'Nameserver bilgileri alındı',
            'data' => [
                'domain' => $params['domain'],
                'nameservers' => [
                    'ns1.dummy.com',
                    'ns2.dummy.com',
                ],
            ],
        ];
    }

    public function setContactDetails(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        if (! isset($params['groups']) || ! is_array($params['groups'])) {
            return [
                'status' => 'error',
                'message' => 'Contact groups required',
            ];
        }

        $result = [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_update_contact_success'),
            'data' => [
                'domain' => $params['domain'],
                'registrar' => 'dummyregistrar',
                'updated_groups' => array_keys($params['groups']),
                'contacts' => $params['groups'],
                'whois_updated' => true,
                'updated_at' => now()->toISOString(),
            ],
        ];

        $this->notifyAdmin('Update Contacts', $params, $result);

        return $result;
    }

    public function getContactDetails(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        return [
            'status' => 'success',
            'message' => 'Contact information retrieved',
            'groups' => [
                'Registrar' => [
                    'firstname' => 'John',
                    'lastname' => 'Doe',
                    'email' => 'john@example.com',
                    'phone' => '+1234567890',
                    'company' => 'Example Registrar Inc',
                    'address' => '123 Main Street',
                    'city' => 'New York',
                    'state' => 'NY',
                    'postal_code' => '10001',
                    'country' => 'United States',
                ],
                'Owner' => [
                    'firstname' => 'Jane',
                    'lastname' => 'Smith',
                    'email' => 'jane@example.com',
                    'phone' => '+9876543210',
                    'company' => 'ACME Corporation',
                    'address' => '456 Business Ave',
                    'city' => 'Los Angeles',
                    'state' => 'CA',
                    'postal_code' => '90001',
                    'country' => 'United States',
                ],
                'Technical Contact' => [
                    'firstname' => 'Bob',
                    'lastname' => 'Johnson',
                    'email' => 'bob@tech.example.com',
                    'phone' => '+5551234567',
                    'company' => 'Tech Solutions Ltd',
                ],
                'Billing Contact' => [
                    'firstname' => 'Alice',
                    'lastname' => 'Williams',
                    'email' => 'alice@billing.example.com',
                    'phone' => '+5559876543',
                    'company' => 'Accounting Services',
                ],
            ],
        ];
    }

    /**
     * Domain kaydını siler (admin-only)
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function deleteDomain(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        $deleteId = 'DUMMY_DEL_'.strtoupper(uniqid());

        $result = [
            'status' => 'success',
            'message' => 'Domain deleted at registrar',
            'data' => [
                'delete_id' => $deleteId,
                'domain' => $params['domain'],
                'registrar' => 'dummyregistrar',
                'action' => 'immediate_delete',
                'refund_eligible' => false,
                'grace_period_remaining' => '0 days',
                'deleted_at' => now()->toISOString(),
            ],
        ];

        Log::info('Dummyregistrar: Domain deleted', [
            'action' => 'deleted',
            'domain' => $params['domain'],
            'delete_id' => $deleteId,
        ]);

        $this->notifyAdmin('Domain Delete', $params, $result);

        return $result;
    }

    /**
     * Domain detaylarını getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function getDomainDetails(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        return [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_get_domain_info_success'),
            'data' => [
                'domain' => $params['domain'],
                'status' => 'active',
                'locked' => true,
                'privacy_enabled' => false,
                'auto_renew' => true,
                'created_at' => now()->subYear()->toISOString(),
                'updated_at' => now()->toISOString(),
                'expires_at' => now()->addYear()->toISOString(),
                'nameservers' => [
                    'ns1.dummy.com',
                    'ns2.dummy.com',
                ],
                'registrar' => 'Dummy Registrar',
                'epp_code_available' => true,
            ],
        ];
    }

    /**
     * Domain kilit durumunu getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function getDomainLock(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        return [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_get_lock_status_success'),
            'data' => [
                'domain' => $params['domain'],
                'locked' => true,
            ],
        ];
    }

    /**
     * Privacy ayarlarını getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function getPrivacySettings(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        return [
            'status' => 'success',
            'message' => 'Privacy ayarları alındı',
            'data' => [
                'domain' => $params['domain'],
                'privacy_enabled' => false,
                'available' => true,
            ],
        ];
    }

    /**
     * EPP kodunu getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function getEppCode(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        return [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_get_epp_success'),
            'data' => [
                'domain' => $params['domain'],
                'epp_code' => 'DUMMY-EPP-'.strtoupper(substr(md5($params['domain']), 0, 10)),
            ],
        ];
    }

    /**
     * EPP kodunu e-posta ile gönderir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function sendEppCode(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        // PRC-49: caller passes enriched params; client_email is already in $params.
        $sentTo = $params['client_email'] ?? 'registrant@example.com';
        $eppCode = 'DUMMY-EPP-'.strtoupper(substr(md5($params['domain'].now()), 0, 12));

        $result = [
            'status' => 'success',
            'message' => 'EPP kodu kayıtlı e-posta adresine gönderildi',
            'data' => [
                'domain' => $params['domain'],
                'registrar' => 'dummyregistrar',
                'epp_code' => $eppCode,
                'sent_to' => $sentTo,
                'valid_until' => now()->addDays(7)->toISOString(),
                'note' => 'Domain must be unlocked before transfer',
                'sent_at' => now()->toISOString(),
            ],
        ];

        $this->notifyAdmin('Send EPP Code', $params, $result);

        return $result;
    }

    /**
     * Domain kilidini günceller
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function updateDomainLock(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        $lockStatus = $params['lock'] ?? $params['lock_status'] ?? true;

        $result = [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_set_lock_success'),
            'data' => [
                'domain' => $params['domain'],
                'registrar' => 'dummyregistrar',
                'previous_lock_status' => ! $lockStatus,
                'new_lock_status' => $lockStatus,
                'lock_type' => 'clientTransferProhibited',
                'transfer_allowed' => ! $lockStatus,
                'updated_at' => now()->toISOString(),
            ],
        ];

        $this->notifyAdmin('Update Domain Lock', $params, $result);

        return $result;
    }

    /**
     * Gizlilik ayarlarını günceller
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function updatePrivacySettings(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        $privacyEnabled = $params['id_protection'] ?? $params['privacy_enabled'] ?? true;

        $result = [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_register_privacy_success'),
            'data' => [
                'domain' => $params['domain'],
                'registrar' => 'dummyregistrar',
                'previous_privacy' => ! $privacyEnabled,
                'new_privacy' => $privacyEnabled,
                'whois_masked' => $privacyEnabled,
                'service' => 'WHOIS Privacy Protection',
                'updated_at' => now()->toISOString(),
            ],
        ];

        $this->notifyAdmin('Update Privacy', $params, $result);

        return $result;
    }

    /**
     * Domain müsaitlik kontrolü
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function checkDomainAvailability(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        // Deterministic availability for testing: domain available unless it
        // starts with 'taken' — makes local browser smoke tests predictable.
        $isAvailable = ! str_starts_with(strtolower($params['domain']), 'taken');

        // Dual-shape response: `status/data` (core registrar contract) +
        // flat `success/available` (DomainService convenience keys).
        return [
            'status' => 'success',
            'success' => true,
            'available' => $isAvailable,
            'message' => __('admin/modules.dummyregistrar_check_availability_message'),
            'data' => [
                'domain' => $params['domain'],
                'available' => $isAvailable,
                'price' => $isAvailable ? rand(10, 50) : null,
                'currency' => 'USD',
                'checked_at' => now()->toISOString(),
            ],
        ];
    }

    /**
     * DNS kayıtlarını getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function getDNSRecords(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        return [
            'status' => 'success',
            'message' => 'DNS kayıtları alındı',
            'data' => [
                'domain' => $params['domain'],
                'records' => [
                    [
                        'id' => '1',
                        'type' => 'A',
                        'name' => '@',
                        'value' => '127.0.0.1',
                        'ttl' => 3600,
                        'priority' => null,
                    ],
                    [
                        'id' => '2',
                        'type' => 'CNAME',
                        'name' => 'www',
                        'value' => '@',
                        'ttl' => 3600,
                        'priority' => null,
                    ],
                    [
                        'id' => '3',
                        'type' => 'MX',
                        'name' => '@',
                        'value' => 'mail.dummyyyy.com',
                        'ttl' => 3600,
                        'priority' => 10,
                    ],
                ],
            ],
        ];
    }

    /**
     * DNS kaydı ekler
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function addDNSRecord(array $params)
    {
        $requiredParams = ['domain', 'type', 'name', 'value'];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => "Gerekli parametre eksik: {$param}",
                ];
            }
        }

        $recordId = 'DNS_'.strtoupper(uniqid());
        $result = [
            'status' => 'success',
            'message' => 'DNS kaydı eklendi',
            'data' => [
                'record_id' => $recordId,
                'domain' => $params['domain'],
                'registrar' => 'dummyregistrar',
                'type' => $params['type'],
                'name' => $params['name'],
                'value' => $params['value'],
                'ttl' => $params['ttl'] ?? 3600,
                'priority' => $params['priority'] ?? null,
                'propagation_estimated' => '5-30 minutes',
                'priority' => $params['priority'] ?? null,
            ],
        ];

        $this->notifyAdmin('Add DNS Record', $params, $result);

        return $result;
    }

    /**
     * DNS kaydını günceller
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function updateDNSRecord(array $params)
    {
        $requiredParams = ['domain', 'record_id'];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => "Gerekli parametre eksik: {$param}",
                ];
            }
        }

        $result = [
            'status' => 'success',
            'message' => 'DNS kaydı güncellendi',
            'data' => [
                'id' => $params['record_id'],
                'type' => $params['type'] ?? 'A',
                'name' => $params['name'] ?? '@',
                'value' => $params['value'] ?? '127.0.0.1',
                'ttl' => $params['ttl'] ?? 3600,
                'priority' => $params['priority'] ?? null,
            ],
        ];

        $this->notifyAdmin('Update DNS Record', $params, $result);

        return $result;
    }

    /**
     * DNS kaydını siler
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function deleteDNSRecord(array $params)
    {
        $requiredParams = ['domain', 'record_id'];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => "Gerekli parametre eksik: {$param}",
                ];
            }
        }

        $result = [
            'status' => 'success',
            'message' => 'DNS kaydı silindi',
            'data' => [
                'id' => $params['record_id'],
                'deleted_at' => now()->toISOString(),
            ],
        ];

        $this->notifyAdmin('Delete DNS Record', $params, $result);

        return $result;
    }

    /**
     * DNS kayıtlarını günceller
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function updateDNSRecords(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        $result = [
            'status' => 'success',
            'message' => 'DNS kayıtları başarıyla güncellendi',
            'data' => [
                'domain' => $params['domain'],
                'records' => $params['records'] ?? [],
                'updated_at' => now()->toISOString(),
            ],
        ];

        $this->notifyAdmin('Bulk Update DNS Records', $params, $result);

        return $result;
    }

    /**
     * Child nameserver listesini getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function getChildNameservers(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        return [
            'status' => 'success',
            'message' => 'Child nameserver listesi alındı',
            'data' => [
                'domain' => $params['domain'],
                'nameservers' => [
                    [
                        'id' => '1',
                        'hostname' => 'ns1.'.$params['domain'],
                        'ip' => '192.0.2.1',
                    ],
                    [
                        'id' => '2',
                        'hostname' => 'ns2.'.$params['domain'],
                        'ip' => '192.0.2.2',
                    ],
                ],
            ],
        ];
    }

    /**
     * Child nameserver ekler
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function addChildNameserver(array $params)
    {
        $requiredParams = ['domain', 'hostname', 'ip'];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => "Gerekli parametre eksik: {$param}",
                ];
            }
        }

        $nameserverId = 'NS_'.strtoupper(uniqid());
        $result = [
            'status' => 'success',
            'message' => 'Child nameserver eklendi',
            'data' => [
                'id' => $nameserverId,
                'hostname' => $params['hostname'],
                'ip' => $params['ip'],
            ],
        ];

        $this->notifyAdmin('Add Child Nameserver', $params, $result);

        return $result;
    }

    /**
     * Child nameserver günceller
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function updateChildNameserver(array $params)
    {
        $requiredParams = ['domain', 'nameserver_id'];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => "Gerekli parametre eksik: {$param}",
                ];
            }
        }

        $result = [
            'status' => 'success',
            'message' => 'Child nameserver güncellendi',
            'data' => [
                'id' => $params['nameserver_id'],
                'hostname' => $params['hostname'] ?? 'ns1.dummy.com',
                'ip' => $params['ip'] ?? '192.0.2.1',
            ],
        ];

        $this->notifyAdmin('Update Child Nameserver', $params, $result);

        return $result;
    }

    /**
     * Child nameserver siler
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function deleteChildNameserver(array $params)
    {
        $requiredParams = ['domain', 'nameserver_id'];

        foreach ($requiredParams as $param) {
            if (! isset($params[$param]) || empty($params[$param])) {
                return [
                    'status' => 'error',
                    'message' => "Gerekli parametre eksik: {$param}",
                ];
            }
        }

        $result = [
            'status' => 'success',
            'message' => 'Child nameserver silindi',
            'data' => [
                'id' => $params['nameserver_id'],
                'deleted_at' => now()->toISOString(),
            ],
        ];

        $this->notifyAdmin('Delete Child Nameserver', $params, $result);

        return $result;
    }

    /**
     * Domain senkronizasyonu
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function syncDomain(array $params)
    {
        if (! isset($params['domain']) || empty($params['domain'])) {
            return [
                'status' => 'error',
                'message' => 'Domain adı gerekli',
            ];
        }

        // Gerçekçi bir expire date simüle et (rastgele 30 gün ile 3 yıl arası)
        $randomDays = rand(30, 1095); // 30 gün - 3 yıl arası
        $expiresAt = now()->addDays($randomDays)->toISOString();

        $result = [
            'status' => 'success',
            'message' => __('admin/modules.dummyregistrar_sync_success'),
            'data' => [
                'domain' => $params['domain'],
                'status' => 'active',
                'expires_at' => $expiresAt,
                'auto_renew' => (bool) rand(0, 1),
                'locked' => (bool) rand(0, 1),
                'privacy_enabled' => (bool) rand(0, 1),
                'synced_at' => now()->toISOString(),
            ],
        ];

        $this->notifyAdmin('Domain Sync', $params, $result);

        return $result;
    }

    /**
     * Email forwarding kurallarını getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function getEmailForwarding(array $params)
    {
        return [
            'status' => 'success',
            'forwards' => [
                ['prefix' => 'info', 'destination' => 'admin@example.com'],
                ['prefix' => 'support', 'destination' => 'support@example.com'],
            ],
        ];
    }

    /**
     * Email forwarding kuralı ekler
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function addEmailForwarding(array $params)
    {
        $result = ['status' => 'success', 'message' => 'Email forwarding rule added successfully'];

        $this->notifyAdmin('Add Email Forward', $params, $result);

        return $result;
    }

    /**
     * Email forwarding kuralı siler
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function deleteEmailForwarding(array $params)
    {
        $result = ['status' => 'success', 'message' => 'Email forwarding rule deleted successfully'];

        $this->notifyAdmin('Delete Email Forward', $params, $result);

        return $result;
    }

    /**
     * URL forwarding kurallarını getirir
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function getURLForwarding(array $params)
    {
        return [
            'status' => 'success',
            'forwards' => [
                ['source' => '@', 'destination' => 'https://www.example.com', 'type' => 'redirect_301'],
            ],
        ];
    }

    /**
     * URL forwarding kurallarını kaydeder
     *
     * @param  array  $params  Parametreler
     * @return array İşlem sonucu
     */
    public function saveURLForwarding(array $params)
    {
        $result = ['status' => 'success', 'message' => 'URL forwarding saved successfully'];

        $this->notifyAdmin('Save URL Forwarding', $params, $result);

        return $result;
    }

    /**
     * Module dashboard output for the registrar edit page
     */
    public function getModuleDashboard(array $params)
    {
        return [
            'status' => 'success',
            'data' => [
                'html' => '<div class="row">'
                    . '<div class="col-md-4"><div class="card border-0 shadow-sm"><div class="card-body text-center"><h5>$1,234.56</h5><p class="text-muted mb-0">Account Balance</p></div></div></div>'
                    . '<div class="col-md-4"><div class="card border-0 shadow-sm"><div class="card-body text-center"><h5>42</h5><p class="text-muted mb-0">Active Domains</p></div></div></div>'
                    . '<div class="col-md-4"><div class="card border-0 shadow-sm"><div class="card-body text-center"><h5 class="text-success">Connected</h5><p class="text-muted mb-0">API Status</p></div></div></div>'
                    . '</div>',
            ],
        ];
    }

    /**
     * Available test actions for the dummy registrar
     */
    public function getTestActions(): array
    {
        return [
            'test_connection' => [
                'label' => 'Test Connection',
                'icon' => 'fas fa-plug',
                'description' => 'Test API connectivity',
            ],
            'test_balance' => [
                'label' => 'Check Balance',
                'icon' => 'fas fa-wallet',
                'description' => 'Retrieve account balance',
            ],
            'test_domain_list' => [
                'label' => 'List Domains',
                'icon' => 'fas fa-list',
                'description' => 'Fetch first 5 domains',
            ],
        ];
    }

    /**
     * Test API connection
     */
    public function testConnection(array $params): array
    {
        $result = ['status' => 'success', 'message' => 'Connection successful! API is reachable.'];

        $this->notifyAdmin('Test Connection', $params, $result);

        return $result;
    }

    /**
     * Test balance retrieval
     */
    public function testBalance(array $params): array
    {
        $result = ['status' => 'success', 'message' => 'Account balance: $1,234.56 USD'];

        $this->notifyAdmin('Test Balance', $params, $result);

        return $result;
    }

    /**
     * Test domain list retrieval
     */
    public function testDomainList(array $params): array
    {
        $result = ['status' => 'success', 'message' => 'Found 42 domains. First 5: example1.com, example2.net, example3.org, test4.com, demo5.io'];

        $this->notifyAdmin('Test Domain List', $params, $result);

        return $result;
    }

    /**
     * Konfigürasyon alanlarını döndürür
     */
    public function getConfigFields(): array
    {
        return [
            'api_url' => [
                'type' => 'text',
                'label' => __('admin/modules.dummyregistrar_field_api_url_label'),
                'required' => true,
                'description' => __('admin/modules.dummyregistrar_field_api_url_description'),
                'placeholder' => 'https://api.dummy.com',
                'value' => $this->config['api_url'] ?? 'https://api.dummy.com',
            ],
            'api_key' => [
                'type' => 'text',
                'label' => 'API Anahtarı',
                'required' => true,
                'description' => 'API erişim anahtarı',
                'placeholder' => 'your-api-key',
                'value' => $this->config['api_key'] ?? '',
            ],
            'api_secret' => [
                'type' => 'password',
                'label' => 'API Secret',
                'required' => true,
                'description' => 'API gizli anahtarı',
                'placeholder' => '********',
                'value' => $this->config['api_secret'] ?? '',
            ],
            'test_mode' => [
                'type' => 'checkbox',
                'label' => __('admin/modules.dummyregistrar_field_test_mode_label'),
                'required' => false,
                'description' => __('admin/modules.dummyregistrar_field_test_mode_description'),
                'default' => true,
                'value' => $this->config['test_mode'] ?? true,
            ],
        ];
    }

    /**
     * Admin panel çıktısı
     *
     * @param  array  $params  Parametreler
     * @return string HTML çıktısı
     */
    public function adminOutput(array $params)
    {
        $domain = $params['domain'] ?? 'N/A';
        $registeredAt = $params['registered_at'] ?? 'N/A';
        $expiresAt = $params['expires_at'] ?? 'N/A';

        return <<<HTML
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Dummy Registrar - Domain Bilgileri</h5>
            </div>
            <div class="card-body">
                <table class="table table-sm">
                    <tbody>
                        <tr>
                            <th width="30%">Domain:</th>
                            <td>{$domain}</td>
                        </tr>
                        <tr>
                            <th>Kayıt Tarihi:</th>
                            <td>{$registeredAt}</td>
                        </tr>
                        <tr>
                            <th>Son Kullanma Tarihi:</th>
                            <td>{$expiresAt}</td>
                        </tr>
                        <tr>
                            <th>Registrar:</th>
                            <td>Dummy Registrar (Test)</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        HTML;
    }

    /**
     * Müşteri panel çıktısı
     *
     * @param  array  $params  Parametreler
     * @return string HTML çıktısı
     */
    public function clientOutput(array $params)
    {
        $domain = $params['domain'] ?? 'N/A';
        $expiresAt = $params['expires_at'] ?? 'N/A';
        $autoRenew = ($params['auto_renew'] ?? false) ? 'Aktif' : 'Pasif';
        $privacyEnabled = ($params['privacy_enabled'] ?? false) ? 'Aktif' : 'Pasif';

        return <<<HTML
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-globe me-2"></i>Domain Bilgileri</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="text-muted mb-3">Domain Detayları</h6>
                        <table class="table table-sm table-borderless">
                            <tbody>
                                <tr>
                                    <td class="text-muted" width="40%"><i class="fas fa-globe me-2"></i>Domain:</td>
                                    <td><strong>{$domain}</strong></td>
                                </tr>
                                <tr>
                                    <td class="text-muted"><i class="fas fa-calendar me-2"></i>Son Kullanma:</td>
                                    <td>{$expiresAt}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="text-muted mb-3">Ayarlar</h6>
                        <table class="table table-sm table-borderless">
                            <tbody>
                                <tr>
                                    <td class="text-muted" width="40%"><i class="fas fa-sync me-2"></i>Otomatik Yenileme:</td>
                                    <td>{$autoRenew}</td>
                                </tr>
                                <tr>
                                    <td class="text-muted"><i class="fas fa-shield-alt me-2"></i>WHOIS Gizliliği:</td>
                                    <td>{$privacyEnabled}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="alert alert-info mt-3 mb-0">
                    <i class="fas fa-lightbulb me-2"></i>
                    <strong>Bilgi:</strong> Bu bir dummy (test) registrar modülüdür. Gerçek domain işlemleri yapmaz.
                </div>
            </div>
        </div>
        HTML;
    }

    /**
     * Reference implementation: .tr family needs identity_type + (TCKN | VKN + tax_office).
     * Other TLDs require no extra fields.
     */
    public function getExtraFields(string $tld): array
    {
        // Registrar-eligible Turkish TLDs supported by this reference impl.
        // Intentionally excludes restricted namespaces (gov.tr/edu.tr/bel.tr)
        // and less common commercial TLDs (biz.tr/info.tr/tv.tr/...); real
        // production modules should tailor this list per registrar coverage.
        if (! in_array($tld, ['tr', 'com.tr', 'net.tr', 'org.tr'], true)) {
            return [];
        }

        return [
            'identity_type' => [
                'type'     => 'select',
                'label'    => __('admin/common.dummyregistrar_tr_identity_type'),
                'options'  => [
                    'individual' => __('admin/common.dummyregistrar_tr_individual'),
                    'corporate'  => __('admin/common.dummyregistrar_tr_corporate'),
                ],
                'required' => true,
                'order'    => 10,
            ],
            'tckn' => [
                'type'       => 'text',
                'label'      => __('admin/common.dummyregistrar_tr_tckn'),
                'required'   => true,
                'depends_on' => ['identity_type' => 'individual'],
                'validation' => [
                    // length drives HTML maxlength on the input;
                    // pattern drives regex validation (same rule, different layer).
                    'length'  => 11,
                    'pattern' => '/^\d{11}$/',
                ],
                'order'      => 20,
            ],
            'vkn' => [
                'type'       => 'text',
                'label'      => __('admin/common.dummyregistrar_tr_vkn'),
                'required'   => true,
                'depends_on' => ['identity_type' => 'corporate'],
                'validation' => [
                    // length drives HTML maxlength on the input;
                    // pattern drives regex validation (same rule, different layer).
                    'length'  => 10,
                    'pattern' => '/^\d{10}$/',
                ],
                'order'      => 30,
            ],
            'tax_office' => [
                'type'       => 'text',
                'label'      => __('admin/common.dummyregistrar_tr_tax_office'),
                'required'   => true,
                'depends_on' => ['identity_type' => 'corporate'],
                'order'      => 40,
            ],
        ];
    }

    /**
     * Algorithmic per-key validation. Declarative rules (length/pattern) are
     * applied by core before this is called — here we only do math (MERNIS
     * mod-10 checksum for TCKN).
     *
     * Return contract: true = valid; string = ALREADY-TRANSLATED error message.
     */
    public function validateExtraField(string $tld, string $key, mixed $value, array $allValues): bool|string
    {
        if ($key === 'tckn' && is_string($value) && $value !== '') {
            if (! $this->isValidTcknChecksum($value)) {
                return __('admin/common.dummyregistrar_invalid_tckn');
            }
        }

        return true;
    }

    /**
     * TCKN MERNIS mod-10 checksum.
     *
     * Rules:
     *  1. 11 digits; first digit cannot be 0.
     *  2. (d1+d3+d5+d7+d9)*7 − (d2+d4+d6+d8)  mod 10 = d10
     *  3. (d1..d10) sum                       mod 10 = d11
     */
    private function isValidTcknChecksum(string $tckn): bool
    {
        if (! preg_match('/^\d{11}$/', $tckn)) {
            return false;
        }
        if ($tckn[0] === '0') {
            return false;
        }

        // d indices below are 0-based; docstring prose uses 1-based (d1 == $d[0]).
        $d = array_map('intval', str_split($tckn));

        $d10 = ((($d[0] + $d[2] + $d[4] + $d[6] + $d[8]) * 7)
               - ($d[1] + $d[3] + $d[5] + $d[7])) % 10;
        if ($d10 < 0) {
            $d10 += 10;
        }
        if ($d10 !== $d[9]) {
            return false;
        }

        $d11 = array_sum(array_slice($d, 0, 10)) % 10;

        return $d11 === $d[10];
    }
}
