<?php

namespace App\Observers;

use App\Events\TicketCreatedByAdmin;
use App\Events\TicketCreatedByClient;
use App\Core\Hook\HookBridge;
use App\Models\Ticket;
use Illuminate\Support\Facades\Auth;

class TicketObserver
{
    public function created(Ticket $ticket): void
    {
        // Admin panelden oluşturulduysa
        if (Auth::guard('admin')->check()) {
            $admin = Auth::guard('admin')->user();

            // System log - admin tarafından ticket oluşturuldu
            \App\Models\Log::create([
                'type' => \App\Models\Log::TYPE_SYSTEM,
                'observer' => 'TicketObserver',
                'module' => 'Ticket',
                'method' => 'created_by_admin',
                'admin_id' => $admin->id,
                'client_id' => $ticket->client_id,
                'ip_address' => request()->ip() ?? '0.0.0.0',
                'user_agent' => request()->userAgent(),
                'description' => "Ticket #{$ticket->id} created by admin {$admin->name}",
                'request' => [
                    'entity_id' => $ticket->id,
                    'ticket_title' => $ticket->title,
                    'department_id' => $ticket->department_id,
                    'priority' => $ticket->priority,
                ],
            ]);

            TicketCreatedByAdmin::dispatch($ticket, $admin);

            // WHMCS hook: TicketOpenAdmin
            $bridge = app(HookBridge::class);
            $ctx = $bridge->buildTicketContext($ticket);
            $bridge->fireAction('TicketOpenAdmin', array_merge($ctx, [
                'adminid' => $admin->id,
            ]));

            return;
        }

        // Müşteri tarafından oluşturulduysa
        if ($ticket->client) {
            // System log - client tarafından ticket oluşturuldu
            \App\Models\Log::create([
                'type' => \App\Models\Log::TYPE_CLIENT,
                'observer' => 'TicketObserver',
                'module' => 'Ticket',
                'method' => 'created_by_client',
                'client_id' => $ticket->client_id,
                'ip_address' => request()->ip() ?? '0.0.0.0',
                'user_agent' => request()->userAgent(),
                'description' => "Ticket #{$ticket->id} created by client {$ticket->client->first_name} {$ticket->client->last_name}",
                'request' => [
                    'entity_id' => $ticket->id,
                    'ticket_title' => $ticket->title,
                    'department_id' => $ticket->department_id,
                    'priority' => $ticket->priority,
                ],
            ]);

            TicketCreatedByClient::dispatch($ticket, $ticket->client);
        }

        // WHMCS hook: TicketOpen (client or guest)
        $bridge = app(HookBridge::class);
        $ctx = $bridge->buildTicketContext($ticket);
        $bridge->fireAction('TicketOpen', $ctx);
    }

    public function updated(Ticket $ticket): void
    {
        $bridge = app(HookBridge::class);
        $ctx = $bridge->buildTicketContext($ticket);

        // Status change (PROCP uses status_id FK to TicketStatus)
        if ($ticket->wasChanged('status_id')) {
            $bridge->fireAction('TicketStatusChange', array_merge($ctx, [
                'adminid' => Auth::guard('admin')->id(),
            ]));

            // TicketClose fires when new status has is_closed = true.
            // Refresh the relation to avoid stale cached value after update.
            $currentStatus = $ticket->status()->first();
            if ($currentStatus && $currentStatus->is_closed) {
                $bridge->fireAction('TicketClose', $ctx);
            }
        }

        if ($ticket->wasChanged('department_id')) {
            $bridge->fireAction('TicketDepartmentChange', $ctx);
        }

        if ($ticket->wasChanged('priority')) {
            $bridge->fireAction('TicketPriorityChange', $ctx);
        }

        // Subject in PROCP is the `title` field (bridge maps title→subject)
        if ($ticket->wasChanged('title')) {
            $bridge->fireAction('TicketSubjectChange', $ctx);
        }

        // Flagged field is `is_flagged` in PROCP (not `flagged`)
        if ($ticket->wasChanged('is_flagged') && $ticket->is_flagged) {
            $bridge->fireAction('TicketFlagged', array_merge($ctx, [
                'adminid' => Auth::guard('admin')->id(),
            ]));
        }
    }

    public function deleted(Ticket $ticket): void
    {
        app(HookBridge::class)->fireAction('TicketDelete', [
            'ticketId'  => $ticket->id,
            'ticket_id' => $ticket->id,
            'adminId'   => Auth::guard('admin')->id(),
        ]);
    }
}
