<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\ChartOfAccountModel;
use App\Models\TaxRateModel;

class TaxRateService
{
    protected TaxRateModel $rates;
    protected ChartOfAccountModel $accounts;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->rates    = new TaxRateModel();
        $this->accounts = new ChartOfAccountModel();
        $this->activity = new ActivityLogModel();
    }

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

        $rateError = $this->validateRate($input['rate'] ?? null);
        if ($rateError) {
            return ['success' => false, 'errors' => ['rate' => $rateError]];
        }

        $accountError = $this->validateAccount($input['account_id'] ?? null);
        if ($accountError) {
            return ['success' => false, 'errors' => ['account_id' => $accountError]];
        }

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

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

        $id = (int) $this->rates->getInsertID();
        $this->activity->log('tax_rates', 'created', $actingUserId, "Created tax rate #{$id} ({$data['code']})", (string) $id);

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

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

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

        $rateError = $this->validateRate($input['rate'] ?? null);
        if ($rateError) {
            return ['success' => false, 'errors' => ['rate' => $rateError]];
        }

        $accountError = $this->validateAccount($input['account_id'] ?? null);
        if ($accountError) {
            return ['success' => false, 'errors' => ['account_id' => $accountError]];
        }

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

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

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

        return ['success' => true];
    }

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

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

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

        $this->rates->delete($id);
        $this->activity->log('tax_rates', 'deleted', $actingUserId, "Deleted tax rate #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function validateRate($rate): ?string
    {
        if ($rate === null || $rate === '') {
            return 'Rate is required.';
        }
        if (! is_numeric($rate)) {
            return 'Rate must be a number.';
        }
        if ((float) $rate < 0) {
            return 'Rate cannot be negative.';
        }

        return null;
    }

    protected function validateAccount($accountId): ?string
    {
        $accountId = (int) $accountId;
        if ($accountId <= 0) {
            return null;
        }

        $account = $this->accounts->find($accountId);
        if (! $account) {
            return 'Linked account not found.';
        }

        return null;
    }

    protected function mapInput(array $input): array
    {
        $accountId = (int) ($input['account_id'] ?? 0);

        return [
            'name'           => trim((string) $input['name']),
            'rate'           => round((float) ($input['rate'] ?? 0), 4),
            'tax_type'       => $input['tax_type'] ?? 'vat',
            'account_id'     => $accountId > 0 ? $accountId : null,
            'is_recoverable' => ((string) ($input['is_recoverable'] ?? '0') === '1') ? 1 : 0,
            'status'         => ($input['status'] ?? 'active') === 'inactive' ? 'inactive' : 'active',
            'notes'          => ! empty($input['notes']) ? trim((string) $input['notes']) : null,
        ];
    }
}
