<?php

namespace App\Observers;

use App\Core\Hook\HookBridge;
use App\Models\Client;
use App\Services\VisitorClientSyncService;
use Illuminate\Support\Facades\Log;

class ClientObserver
{
    protected $syncService;

    public function __construct(VisitorClientSyncService $syncService)
    {
        $this->syncService = $syncService;
    }

    /**
     * Handle the Client "updated" event.
     * Client bilgileri değiştiğinde visitor cache'i güncelle
     */
    public function updated(Client $client): void
    {
        // Sadece pricing ile ilgili alanlar değiştiyse sync yap
        $pricingRelevantFields = [
            'country_id', 'currency_id', 'language_id',
            'group_id', 'tax_exempt', 'type',
        ];

        $changedFields = array_keys($client->getDirty());
        $hasPricingChanges = ! empty(array_intersect($changedFields, $pricingRelevantFields));

        if ($hasPricingChanges) {
            Log::info('Client pricing-relevant fields updated, syncing with visitor', [
                'client_id' => $client->id,
                'changed_fields' => $changedFields,
            ]);

            // Client ile ilişkili visitor'ı güncelle
            $this->syncService->syncClientWithVisitor($client);
        }

        $bridge = app(HookBridge::class);
        $bridge->fireAction('ClientEdit', $bridge->buildClientContext($client, [
            'olddata' => $client->getOriginal(),
        ]));

        // ClientClose fires when status transitions to 'inactive' (closed account)
        if ($client->wasChanged('status') && $client->status === 'inactive') {
            $bridge->fireAction('ClientClose', $bridge->buildClientContext($client));
        }

        // ClientChangePassword fires when password attribute was changed
        if ($client->wasChanged('password')) {
            $bridge->fireAction('ClientChangePassword', [
                'userid'   => $client->id,
                'user_id'  => $client->id,
                'password' => '(redacted)',
            ]);
        }
    }

    /**
     * Handle the Client "saved" event.
     * Yeni client oluşturulduğunda da sync yap
     */
    public function saved(Client $client): void
    {
        if ($client->wasRecentlyCreated) {
            Log::info('New client created, setting up visitor sync', [
                'client_id' => $client->id,
            ]);

            // Yeni client için visitor sync hazırla
            $this->syncService->syncClientWithVisitor($client);
        }
    }

    /**
     * Handle the Client "created" event.
     * Yeni client oluşturulduğunda default billing address oluştur
     */
    public function created(Client $client): void
    {
        Log::info('New client created, creating default billing address', [
            'client_id' => $client->id,
        ]);

        // System log - yeni müşteri oluşturuldu
        \App\Models\Log::create([
            'type' => \App\Models\Log::TYPE_SYSTEM,
            'observer' => 'ClientObserver',
            'module' => 'Client',
            'method' => 'created',
            'client_id' => $client->id,
            'ip_address' => request()->ip() ?? '0.0.0.0',
            'user_agent' => request()->userAgent(),
            'description' => "New client registered: {$client->first_name} {$client->last_name} ({$client->email})",
            'request' => [
                'entity_id' => $client->id,
                'client_email' => $client->email,
                'client_name' => "{$client->first_name} {$client->last_name}",
                'company_name' => $client->company_name,
            ],
        ]);

        // City bilgisini al (city_id varsa City modelinden name'i al)
        $cityName = null;
        if ($client->city_id) {
            $city = \App\Models\City::find($client->city_id);
            $cityName = $city ? $city->name : null;
        }

        // Default billing address oluştur
        \App\Models\ClientBillingAddress::create([
            'client_id' => $client->id,
            'title' => 'Default Address',
            'first_name' => $client->first_name,
            'last_name' => $client->last_name,
            'company_name' => $client->company_name,
            'email' => $client->email,
            'phone' => $client->phone ?? '',
            'country_id' => $client->country_id,
            'city_id' => $client->city_id,
            'city' => $cityName, // String city name
            'address1' => $client->address1 ?? '',
            'address2' => $client->address2 ?? '',
            'state' => $client->state ?? '',
            'postcode' => $client->postcode ?? '',
            'custom_field_values' => [],
            'custom_fields' => [],
            'is_default' => true,
        ]);

        Log::info('Default billing address created for client', [
            'client_id' => $client->id,
        ]);

        app(HookBridge::class)->fireAction('ClientAdd',
            app(HookBridge::class)->buildClientContext($client));
    }
}
