<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\CostCenterModel;

class CostCenterService
{
    protected CostCenterModel $centers;
    protected ActivityLogModel $activity;

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

    public function create(array $input, ?int $actingUserId): array
    {
        $code = strtoupper(trim($input['code'] ?? ''));
        if ($this->centers->isCodeTaken($code)) {
            return ['success' => false, 'errors' => ['code' => 'That cost center 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->centers->insert($data, true)) {
            return ['success' => false, 'errors' => $this->centers->errors()];
        }

        $id = (int) $this->centers->getInsertID();
        $this->activity->log('cost_centers', 'created', $actingUserId, "Created cost center #{$id} ({$data['code']})", (string) $id);

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

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

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

        $parentId = $input['parent_id'] ?? null;
        if ((int) $parentId === $id) {
            return ['success' => false, 'errors' => ['parent_id' => 'A cost center 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->centers->update($id, $data)) {
            return ['success' => false, 'errors' => $this->centers->errors()];
        }

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

        return ['success' => true];
    }

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

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

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

        if ($this->centers->hasChildren($id)) {
            return ['success' => false, 'error' => 'Cannot delete a cost center that has child cost centers.'];
        }

        $refError = $this->checkReferences($id);
        if ($refError) {
            return ['success' => false, 'error' => $refError];
        }

        $this->centers->delete($id);
        $this->activity->log('cost_centers', 'deleted', $actingUserId, "Deleted cost center #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function checkReferences(int $id): ?string
    {
        $db = \Config\Database::connect();
        $tables = [
            'budgets'           => 'budgets',
            'expenses'          => 'expenses',
            'payment_vouchers'  => 'payment vouchers',
            'receipt_vouchers'  => 'receipt vouchers',
        ];

        foreach ($tables as $table => $label) {
            if (! $db->tableExists($table)) {
                continue;
            }
            $count = $db->table($table)->where('cost_center_id', $id)->countAllResults();
            if ($count > 0) {
                return "Cannot delete a cost center that is referenced by {$label}.";
            }
        }

        return null;
    }

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

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

        return null;
    }

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

        return [
            'name'      => trim((string) $input['name']),
            'parent_id' => $parentId > 0 ? $parentId : null,
            'status'    => ($input['status'] ?? 'active') === 'inactive' ? 'inactive' : 'active',
            'notes'     => ! empty($input['notes']) ? trim((string) $input['notes']) : null,
        ];
    }
}
