<?php

namespace Modules\Sale\Services;

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

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

    public function __construct()
    {
        $this->history   = new CustomerHistoryModel();
        $this->companies = new CompanyModel();
        $this->contacts  = new ContactModel();
        $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.']];
        }

        $contactId = ! empty($input['contact_id']) ? (int) $input['contact_id'] : null;
        if ($contactId) {
            $contact = $this->contacts->find($contactId);
            if (! $contact || (int) $contact['company_id'] !== $companyId) {
                return ['success' => false, 'errors' => ['contact_id' => 'Contact does not belong to this company.']];
            }
        }

        $eventAt = trim($input['event_at'] ?? '');
        if ($eventAt === '') {
            $eventAt = date('Y-m-d H:i:s');
        } elseif (strlen($eventAt) === 16) {
            $eventAt .= ':00';
        }

        $data = [
            'company_id'  => $companyId,
            'contact_id'  => $contactId,
            'event_type'  => $input['event_type'] ?? 'note',
            'title'       => trim($input['title']),
            'description' => $input['description'] ?: null,
            'event_at'    => $eventAt,
            'created_by'  => $actingUserId,
        ];

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

        $id = $this->history->getInsertID();
        $this->activity->log('customer_history', 'created', $actingUserId, "Logged customer history #{$id}", (string) $id);

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

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

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

        return ['success' => true];
    }
}
