<?php

namespace App\Components\Institution;

use App\Models\Institution\Institution;
use App\Rules\EmailAddress;
use App\Rules\PhoneNumber;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class ContactManager extends Component {
    use AuthorizesRequests;

    public Institution $institution;
    public bool $show = false;

    public bool $editing = false;
    public int $editing_id;

    // New Fields
    public string $name = '';
    public string $job_title = '';
    public string $email = '';
    public string $mobile = '';
    public string $telephone = '';

    public function addContact() {
        $this->authorize('institutions.contacts.create');

        $this->validate([
            'name' => 'nullable|string|max:255',
            'job_title' => 'nullable|string|max:255',
            'email' => ['nullable', 'email:rfc,dns', 'max:255', new EmailAddress],
            'mobile' => ['nullable', 'string', 'max:255', new PhoneNumber],
            'telephone' => ['nullable', 'string', 'max:255', new PhoneNumber],
        ]);

        $isFirst = $this->institution->contacts()->count() === 0;

        $this->institution->contacts()->create([
            'name' => $this->name,
            'job_title' => $this->job_title,
            'email' => $this->email ?: null,
            'mobile' => $this->mobile ?: null,
            'telephone' => $this->telephone ?: null,
            'is_primary' => $isFirst,
        ]);

        $this->hideAdd();
    }

    public function hideAdd() {
        $this->reset('name', 'job_title', 'email', 'mobile', 'telephone', 'editing', 'editing_id');
        $this->show = false;
    }

    public function deleteContact(HistoryService $historyService, int $id) {
        $this->authorize('institutions.contacts.delete');

        $contact = $this->institution->contacts()->find($id);

        if (!$contact) {
            return;
        }

        $wasPrimary = $contact->is_primary;

        $contact->delete();

        if ($wasPrimary) {
            $newPrimary = $this->institution->contacts()->first();

            if ($newPrimary) {
                // Fixed typo from original: is_current -> is_primary
                $newPrimary->update(['is_primary' => true]);
            }
        }

        $historyService->add($this->institution, 'Contact "' . $contact->name . '" deleted', [
            'contact_id' => $id,
        ]);

        $this->hideAdd();
    }

    public function makePrimary(HistoryService $historyService, int $id) {
        $this->authorize('institutions.contacts.edit');

        $contact = $this->institution->contacts()->find($id);

        if (!$contact) return;

        $this->institution->contacts()->update([
            'is_primary' => false
        ]);

        $contact->update(['is_primary' => true]);

        $historyService->add($this->institution, 'Contact "' . $contact->name . '" set as primary', [
            'contact_id' => $id,
        ]);
    }

    public function loadContact(int $id) {
        $this->authorize('institutions.contacts.edit');

        $contact = $this->institution->contacts()->find($id);

        if (!$contact) {
            return;
        }

        $this->name = $contact->name;
        $this->job_title = $contact->job_title;
        $this->email = $contact->email ?: '';
        $this->mobile = $contact->mobile ?: '';
        $this->telephone = $contact->telephone ?: '';

        $this->editing = true;
        $this->editing_id = $id;

        $this->showAdd();
    }

    public function showAdd() {
        $this->show = true;
    }

    public function editContact(HistoryService $historyService) {
        $this->authorize('institutions.contacts.edit');

        $contact = $this->institution->contacts()->find($this->editing_id);

        if (!$contact) {
            return;
        }

        $this->validate([
            'name' => 'nullable|string|max:255',
            'job_title' => 'nullable|string|max:255',
            'email' => ['nullable', 'email:rfc,dns', 'max:255', new EmailAddress],
            'mobile' => ['nullable', 'string', 'max:255', new PhoneNumber],
            'telephone' => ['nullable', 'string', 'max:255', new PhoneNumber],
        ]);

        $contact->update([
            'name' => $this->name,
            'job_title' => $this->job_title,
            'email' => $this->email ?: null,
            'mobile' => $this->mobile ?: null,
            'telephone' => $this->telephone ?: null,
        ]);

        $historyService->add($this->institution, 'Contact "' . $contact->name . '" updated', [
            'contact_id' => $this->editing_id,
        ]);

        $this->hideAdd();
    }

    public function render() {
        return view('components.institution.contact-manager');
    }
}