<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\ContactModel;
use App\Models\CustomerHistoryModel;

class ContactService
{
    protected ContactModel $contacts;
    protected CompanyModel $companies;
    protected CustomerHistoryModel $history;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->contacts  = new ContactModel();
        $this->companies = new CompanyModel();
        $this->history   = new CustomerHistoryModel();
        $this->activity  = new ActivityLogModel();
    }

    public function create(array $input, ?int $actingUserId): array
    {
        $companyId = (int) ($input['company_id'] ?? 0);
        if (! $this->companies->find($companyId)) {
            return ['success' => false, 'errors' => ['company_id' => 'Company not found.']];
        }

        $data = $this->mapInput($input);
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

        if (! $this->contacts->insert($data, true)) {
            return ['success' => false, 'errors' => $this->contacts->errors()];
        }

        $id = $this->contacts->getInsertID();
        if (! empty($data['is_primary'])) {
            $this->clearOtherPrimaries($companyId, $id);
        }

        $name = $this->contacts->getFullName($data);
        $this->activity->log('contacts', 'created', $actingUserId, "Created contact #{$id} ({$name})", (string) $id);
        $this->history->insert([
            'company_id'  => $companyId,
            'contact_id'  => $id,
            'event_type'  => 'note',
            'title'       => 'Contact added: ' . $name,
            'description' => null,
            'event_at'    => date('Y-m-d H:i:s'),
            'created_by'  => $actingUserId,
        ]);

        return ['success' => true, 'id' => $id];
    }

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $contact = $this->contacts->find($id);
        if (! $contact) {
            return ['success' => false, 'errors' => ['id' => 'Contact not found.']];
        }

        $companyId = (int) ($input['company_id'] ?? $contact['company_id']);
        if (! $this->companies->find($companyId)) {
            return ['success' => false, 'errors' => ['company_id' => 'Company not found.']];
        }

        $data = $this->mapInput($input);
        $data['updated_by'] = $actingUserId;

        if (! $this->contacts->update($id, $data)) {
            return ['success' => false, 'errors' => $this->contacts->errors()];
        }

        if (! empty($data['is_primary'])) {
            $this->clearOtherPrimaries($companyId, $id);
        }

        $this->activity->log('contacts', 'updated', $actingUserId, "Updated contact #{$id}", (string) $id);

        return ['success' => true];
    }

    public function activate(int $id, ?int $actingUserId): void
    {
        $this->contacts->update($id, ['status' => 'active', 'updated_by' => $actingUserId]);
        $this->activity->log('contacts', 'activated', $actingUserId, "Activated contact #{$id}", (string) $id);
    }

    public function deactivate(int $id, ?int $actingUserId): void
    {
        $this->contacts->update($id, ['status' => 'inactive', 'updated_by' => $actingUserId]);
        $this->activity->log('contacts', 'deactivated', $actingUserId, "Deactivated contact #{$id}", (string) $id);
    }

    public function delete(int $id, ?int $actingUserId): array
    {
        $contact = $this->contacts->find($id);
        if (! $contact) {
            return ['success' => false, 'error' => 'Contact not found.'];
        }

        $this->contacts->delete($id);
        $this->activity->log('contacts', 'deleted', $actingUserId, "Deleted contact #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function clearOtherPrimaries(int $companyId, int $keepId): void
    {
        $this->contacts->builder()
            ->where('company_id', $companyId)
            ->where('id !=', $keepId)
            ->update(['is_primary' => 0]);
    }

    protected function mapInput(array $input): array
    {
        return [
            'company_id' => (int) $input['company_id'],
            'first_name' => trim($input['first_name']),
            'last_name'  => trim($input['last_name']),
            'email'      => trim($input['email'] ?? '') ?: null,
            'phone'      => trim($input['phone'] ?? '') ?: null,
            'job_title'  => trim($input['job_title'] ?? '') ?: null,
            'is_primary' => ! empty($input['is_primary']) ? 1 : 0,
            'status'     => $input['status'] ?? 'active',
            'notes'      => $input['notes'] ?: null,
        ];
    }
}
