<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\ChartOfAccountModel;
use App\Models\JournalEntryLineModel;

class ChartOfAccountService
{
    protected ChartOfAccountModel $accounts;
    protected JournalEntryLineModel $lines;
    protected ActivityLogModel $activity;

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

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

        $parentError = $this->validateParent($input['parent_id'] ?? null);
        if ($parentError) {
            return ['success' => false, 'errors' => ['parent_id' => $parentError]];
        }

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

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

        $id = (int) $this->accounts->getInsertID();
        $this->activity->log('chart_of_accounts', 'created', $actingUserId, "Created account #{$id} ({$data['code']})", (string) $id);

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

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

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

        $parentId = $input['parent_id'] ?? null;
        if ((int) $parentId === $id) {
            return ['success' => false, 'errors' => ['parent_id' => 'An account cannot be its own parent.']];
        }

        $parentError = $this->validateParent($parentId);
        if ($parentError) {
            return ['success' => false, 'errors' => ['parent_id' => $parentError]];
        }

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

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

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

        return ['success' => true];
    }

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

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

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

        if ($this->accounts->hasChildren($id)) {
            return ['success' => false, 'error' => 'Cannot delete an account that has child accounts.'];
        }

        if ($this->lines->countForAccount($id) > 0) {
            return ['success' => false, 'error' => 'Cannot delete an account that has journal lines.'];
        }

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

        return ['success' => true];
    }

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

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

        return null;
    }

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

        return [
            'name'        => trim((string) $input['name']),
            'type'        => $input['type'] ?? 'asset',
            'parent_id'   => $parentId > 0 ? $parentId : null,
            'is_postable' => ((string) ($input['is_postable'] ?? '0') === '1') ? 1 : 0,
            'status'      => $input['status'] ?? 'active',
            'description' => ! empty($input['description']) ? trim((string) $input['description']) : null,
        ];
    }
}
