<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\BankAccountModel;
use App\Models\ChartOfAccountModel;

class BankAccountService
{
    protected BankAccountModel $accounts;
    protected ChartOfAccountModel $glAccounts;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->accounts   = new BankAccountModel();
        $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 bank 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('bank_accounts', 'created', $actingUserId, "Created bank 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' => 'Bank account not found.']];
        }

        $code = strtoupper(trim($input['code'] ?? ''));
        if ($this->accounts->isCodeTaken($code, $id)) {
            return ['success' => false, 'errors' => ['code' => 'That bank 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('bank_accounts', 'updated', $actingUserId, "Updated bank 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('bank_accounts', 'activated', $actingUserId, "Activated bank account #{$id}", (string) $id);
    }

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

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

        $db = db_connect();

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

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

        $cheques = $db->table('cheques')->where('bank_account_id', $id)->countAllResults();
        if ($cheques > 0) {
            return ['success' => false, 'error' => 'Cannot delete a bank account that has cheques.'];
        }

        $reconciliations = $db->table('bank_reconciliations')->where('bank_account_id', $id)->countAllResults();
        if ($reconciliations > 0) {
            return ['success' => false, 'error' => 'Cannot delete a bank account that has reconciliations.'];
        }

        $this->accounts->delete($id);
        $this->activity->log('bank_accounts', 'deleted', $actingUserId, "Deleted bank 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']),
            'bank_name'       => ! empty($input['bank_name']) ? trim((string) $input['bank_name']) : null,
            'account_number'  => ! empty($input['account_number']) ? trim((string) $input['account_number']) : null,
            'branch'          => ! empty($input['branch']) ? trim((string) $input['branch']) : null,
            '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,
        ];
    }
}
