<?php

namespace App\Observers;

use App\Models\CompanyRegistration;
use App\Models\EmployeeRegistration;
use App\Models\PortalUser;
use Illuminate\Support\Facades\Log;

class PortalUserObserver
{
    /**
     * Handle the PortalUser "updated" event.
     *
     * When a user sets their password, update the related registration's account_status to 'active'.
     */
    public function updated(PortalUser $portalUser): void
    {
        // Check if password_set_at was just set (changed from null to a timestamp)
        if ($portalUser->isDirty('password_set_at') && $portalUser->password_set_at !== null) {
            // User just set their password, activate their account
            $this->activateRegistration($portalUser);
        }
    }

    /**
     * Activate the registration associated with this portal user.
     */
    private function activateRegistration(PortalUser $portalUser): void
    {
        try {
            if ($portalUser->isCompanyAdmin()) {
                // Update company registration
                $registration = CompanyRegistration::where('company_id', $portalUser->company_id)
                    ->where('account_status', 'invited')
                    ->first();

                if ($registration) {
                    $registration->update(['account_status' => 'active']);

                    Log::info('Company registration activated after password set', [
                        'registration_id' => $registration->id,
                        'company_id' => $portalUser->company_id,
                        'portal_user_id' => $portalUser->id,
                    ]);
                }
            } elseif ($portalUser->isEmployee()) {
                // Update employee registration
                $registration = EmployeeRegistration::where('company_employee_id', $portalUser->employee_id)
                    ->where('account_status', 'invited')
                    ->first();

                if ($registration) {
                    $registration->update(['account_status' => 'active']);

                    Log::info('Employee registration activated after password set', [
                        'registration_id' => $registration->id,
                        'employee_id' => $portalUser->employee_id,
                        'portal_user_id' => $portalUser->id,
                    ]);
                }
            }
        } catch (\Exception $e) {
            Log::error('Error activating registration after password set: ' . $e->getMessage(), [
                'portal_user_id' => $portalUser->id,
                'exception' => $e,
            ]);
        }
    }
}
