<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\CashAccountModel;
use App\Models\ChartOfAccountModel;

class CashAccountService
{
    protected CashAccountModel $accounts;
    protected ChartOfAccountModel $glAccounts;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->accounts   = new CashAccountModel();
        $this->glAccounts = new ChartOfAccountModel();
        $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 cash account code is already in use.']];
        }

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

        $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('cash_accounts', 'created', $actingUserId, "Created cash 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' => 'Cash account not found.']];
        }

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

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

        $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('cash_accounts', 'updated', $actingUserId, "Updated cash 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('cash_accounts', 'activated', $actingUserId, "Activated cash account #{$id}", (string) $id);
    }

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

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

        $db = db_connect();

        $transfers = $db->table('bank_transfers')
            ->groupStart()
                ->groupStart()
                    ->where('from_type', 'cash')
                    ->where('from_id', $id)
                ->groupEnd()
                ->orGroupStart()
                    ->where('to_type', 'cash')
                    ->where('to_id', $id)
                ->groupEnd()
            ->groupEnd()
            ->countAllResults();

        if ($transfers > 0) {
            return ['success' => false, 'error' => 'Cannot delete a cash account that has transfers.'];
        }

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

        return ['success' => true];
    }

    protected function validateGlAccount($accountId): ?string
    {
        $accountId = (int) $accountId;
        if ($accountId <= 0) {
            return 'A GL account is required.';
        }

        $account = $this->glAccounts->find($accountId);
        if (! $account) {
            return 'GL account not found.';
        }
        if ($account['status'] !== 'active') {
            return 'GL account must be active.';
        }
        if (empty($account['is_postable'])) {
            return 'GL account must be postable.';
        }

        return null;
    }

    protected function mapInput(array $input): array
    {
        return [
            'name'            => trim((string) $input['name']),
            'currency'        => strtoupper(trim((string) ($input['currency'] ?? 'USD'))) ?: 'USD',
            'account_id'      => (int) $input['account_id'],
            'opening_balance' => (float) ($input['opening_balance'] ?? 0),
            'status'          => ($input['status'] ?? 'active') === 'inactive' ? 'inactive' : 'active',
            'notes'           => ! empty($input['notes']) ? trim((string) $input['notes']) : null,
        ];
    }
}
