<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\QuotationTemplateModel;

class QuotationTemplateService
{
    protected QuotationTemplateModel $templates;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->templates = new QuotationTemplateModel();
        $this->activity  = new ActivityLogModel();
    }

    public function create(array $input, ?int $actingUserId): array
    {
        $code = strtoupper(trim($input['code'] ?? ''));
        if ($code !== '' && $this->templates->isCodeTaken($code)) {
            return ['success' => false, 'errors' => ['code' => 'That template code is already in use.']];
        }

        $data = $this->mapInput($input);
        $data['code']       = $code !== '' ? $code : null;
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

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

        $id = (int) $this->templates->getInsertID();
        $this->activity->log('quotation_templates', 'created', $actingUserId, "Created quotation template #{$id}", (string) $id);

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

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

        $code = strtoupper(trim($input['code'] ?? ''));
        if ($code !== '' && $this->templates->isCodeTaken($code, $id)) {
            return ['success' => false, 'errors' => ['code' => 'That template code is already in use.']];
        }

        $data = $this->mapInput($input);
        $data['code']       = $code !== '' ? $code : null;
        $data['updated_by'] = $actingUserId;

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

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

        return ['success' => true];
    }

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

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

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

        $this->templates->delete($id);
        $this->activity->log('quotation_templates', 'deleted', $actingUserId, "Deleted quotation template #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'name'                  => trim($input['name']),
            'subject'               => trim($input['subject'] ?? '') ?: null,
            'intro_text'            => $input['intro_text'] ?: null,
            'terms_text'            => $input['terms_text'] ?: null,
            'default_validity_days' => max(1, (int) ($input['default_validity_days'] ?? 30)),
            'status'                => $input['status'] ?? 'active',
            'notes'                 => $input['notes'] ?: null,
        ];
    }
}
