<?php

namespace App\Modules\Addon\MigrateWhmcs\Importers;

use App\Models\Client;
use App\Models\Currency;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * PRC-1113 — WHMCS `tblclients` → procp `App\Models\Client`.
 *
 * Alan-eşleme yalnız: kimlik (ad/soyad/firma/email), iletişim (telefon/adres),
 * country (WHMCS 2-char `country` → procp countries.a2_iso), currency (WHMCS 7.8
 * tblclients'ta currency kolonu YOK → sistem varsayılanı), status enum çevirisi.
 * Chunk/idempotency/dry-run/hata-izolasyonu tabanda (AbstractWhmcsImporter).
 *
 * ŞİFRE: WHMCS hash'i GÖÇMEZ — güvenlik kararı gereği taze rastgele parola atanır
 * (hashed cast şifreler) + password_must_change=true → kullanıcı reset zorunlu.
 * E-posta çakışması: procp'de aynı e-posta varsa mevcut client EZİLMEZ (skip).
 */
class ClientImporter extends AbstractWhmcsImporter
{
    public function sourceType(): string
    {
        return 'client';
    }

    protected function sourceTable(): string
    {
        return 'tblclients';
    }

    protected function importRow(object $row): ?int
    {
        $email = trim((string) ($row->email ?? ''));

        // E-posta çakışması: mevcut procp client'ı ASLA ezme → skip.
        if ($email !== '' && Client::where('email', $email)->exists()) {
            $this->report->warn(
                $this->sourceType(),
                "Client #{$row->id}: e-posta zaten var ('{$email}') → atlandı (mevcut kayıt korunur)."
            );

            return null;
        }

        // country: WHMCS 2-char kod → procp countries.a2_iso (id=1 HARDCODE YOK).
        $countryId = null;
        $countryCode = strtoupper(trim((string) ($row->country ?? '')));
        if ($countryCode !== '') {
            $countryId = DB::table('countries')->where('a2_iso', $countryCode)->value('id');
        }

        // ŞİFRE: WHMCS hash'i GÖÇMEZ; taze rastgele parola (hashed cast şifreler).
        $client = Client::create([
            'first_name' => $this->text($row->firstname ?? null),
            'last_name' => $this->text($row->lastname ?? null),
            'company_name' => $this->text($row->companyname ?? null),
            'email' => $email,
            'phone' => $this->text($row->phonenumber ?? null),
            'address1' => $this->text($row->address1 ?? null),
            'address2' => $this->text($row->address2 ?? null),
            // PRC-1113 — procp clients tablosunda free-text 'city' YOK (yalnız city_id FK).
            // WHMCS free-text city → city_id fuzzy/güvenilmez; omit (city_id null kalır).
            'state' => $this->text($row->state ?? null),
            'postcode' => $this->text($row->postcode ?? null),
            'country_id' => $countryId,
            'currency_id' => $this->defaultCurrencyId(),
            'status' => $this->mapStatus((string) ($row->status ?? '')),
            'tax_exempt' => $this->mapTaxExempt($row->taxexempt ?? null),
            'notes' => $this->text($row->notes ?? null),
            'password' => Str::random(40),
            'registered_at' => $this->normalizeDate($row->datecreated ?? null),
        ]);

        // password_must_change fillable DEĞİL → doğrudan atama + save (reset zorunlu).
        $client->password_must_change = true;
        $client->save();

        return $client->id;
    }

    /**
     * WHMCS text kolonları NOT NULL '' saklar → boş stringi null'a indir (temiz veri).
     */
    protected function text(mixed $value): ?string
    {
        $v = trim((string) ($value ?? ''));

        return $v === '' ? null : $v;
    }

    /**
     * WHMCS client status ('Active'/'Inactive'/'Closed') → procp lowercase enum.
     * Bilinmeyen → güvenli varsayılan 'active'.
     */
    protected function mapStatus(string $whmcsStatus): string
    {
        return match (strtolower(trim($whmcsStatus))) {
            'inactive' => 'inactive',
            'closed' => 'closed',
            default => 'active',
        };
    }

    /**
     * WHMCS taxexempt ('on' = muaf, aksi boş) → procp boolean.
     */
    protected function mapTaxExempt(mixed $value): bool
    {
        return strtolower(trim((string) ($value ?? ''))) === 'on';
    }

    /**
     * Sistem varsayılan currency id (WHMCS 7.8 tblclients'ta currency kolonu yok).
     */
    protected function defaultCurrencyId(): int
    {
        return (int) (Currency::where('is_default', true)->value('id') ?? 1);
    }

    /**
     * WHMCS '0000-00-00' / boş tarihleri null'a çevir (procp datetime cast güvenliği).
     */
    protected function normalizeDate(mixed $date): ?string
    {
        $d = trim((string) ($date ?? ''));
        if ($d === '' || str_starts_with($d, '0000-00-00')) {
            return null;
        }

        return $d;
    }
}
