<?php

namespace App\Modules\Citizenship\TR\ApiProviders\Nvi;

use App\Core\Citizenship\Api\AbstractCitizenshipApiProvider;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class Nvi extends AbstractCitizenshipApiProvider
{
    public function verify(array $data): array
    {
        $idNumber = trim((string) ($data['individual_id'] ?? ''));
        $firstName = (string) ($data['first_name'] ?? '');
        $lastName = (string) ($data['last_name'] ?? '');
        $birthYear = (string) ($data['birth_year'] ?? '');

        if ($idNumber === '' || $firstName === '' || $lastName === '' || $birthYear === '') {
            return $this->fail('NVI doğrulama için TC, ad, soyad ve doğum yılı gereklidir.');
        }

        try {
            $soapUrl = 'https://tckimlik.nvi.gov.tr/Service/KPSPublic.asmx?WSDL';
            $soapBody = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soap:Body>
    <TCKimlikNoDogrula xmlns="http://tckimlik.nvi.gov.tr/WS">
      <TCKimlikNo>' . e($idNumber) . '</TCKimlikNo>
      <Ad>' . e(mb_strtoupper($firstName, 'UTF-8')) . '</Ad>
      <Soyad>' . e(mb_strtoupper($lastName, 'UTF-8')) . '</Soyad>
      <DogumYili>' . e($birthYear) . '</DogumYili>
    </TCKimlikNoDogrula>
  </soap:Body>
</soap:Envelope>';

            $response = Http::withHeaders([
                'Content-Type' => 'text/xml; charset=utf-8',
                'SOAPAction' => 'http://tckimlik.nvi.gov.tr/WS/TCKimlikNoDogrula',
            ])->withBody($soapBody, 'text/xml')->timeout(10)->post($soapUrl);

            $body = $response->body();
            $isValid = str_contains($body, '<TCKimlikNoDogrulaResult>true</TCKimlikNoDogrulaResult>');

            if ($isValid) {
                return $this->ok(['raw' => $body]);
            }

            return $this->fail('TC Kimlik No doğrulanamadı.', ['raw' => $body]);
        } catch (\Throwable $e) {
            Log::error('NVI API verification failed', ['error' => $e->getMessage()]);

            return $this->fail('NVI API bağlantı hatası: ' . $e->getMessage());
        }
    }

    public function getProviderInfo(): array
    {
        return [
            'name' => 'nvi',
            'label' => 'NVI — Resmi T.C. Kimlik Doğrulama',
            'description' => 'Nüfus ve Vatandaşlık İşleri SOAP servisi (KPSPublic).',
        ];
    }
}
