<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\BudgetModel;
use App\Models\ChartOfAccountModel;
use App\Models\CostCenterModel;

class BudgetService
{
    protected BudgetModel $budgets;
    protected ChartOfAccountModel $accounts;
    protected CostCenterModel $centers;
    protected ActivityLogModel $activity;

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

    public function create(array $input, ?int $actingUserId): array
    {
        $check = $this->validateBusiness($input);
        if (! $check['success']) {
            return $check;
        }

        $data = $this->mapInput($input);
        $data['number']     = $this->budgets->nextNumber();
        $data['status']     = 'draft';
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

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

        $id = (int) $this->budgets->getInsertID();
        $this->activity->log('budgets', 'created', $actingUserId, "Created budget #{$id} ({$data['number']})", (string) $id);

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

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

        $check = $this->validateBusiness($input, true);
        if (! $check['success']) {
            return $check;
        }

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

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

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

        return ['success' => true];
    }

    public function delete(int $id, ?int $actingUserId): array
    {
        $budget = $this->budgets->find($id);
        if (! $budget) {
            return ['success' => false, 'error' => 'Budget not found.'];
        }
        if ($budget['status'] !== 'draft') {
            return ['success' => false, 'error' => 'Only draft budgets can be deleted.'];
        }

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

        return ['success' => true];
    }

    protected function validateBusiness(array $input, bool $allowStatus = false): array
    {
        $amount = round((float) ($input['amount'] ?? 0), 2);
        if ($amount <= 0) {
            return ['success' => false, 'errors' => ['amount' => 'Amount must be greater than zero.']];
        }

        $periodFrom = (string) ($input['period_from'] ?? '');
        $periodTo   = (string) ($input['period_to'] ?? '');
        if ($periodFrom === '' || $periodTo === '') {
            return ['success' => false, 'errors' => ['period_from' => 'Period dates are required.']];
        }
        if (strtotime($periodFrom) > strtotime($periodTo)) {
            return ['success' => false, 'errors' => ['period_to' => 'Period end must be on or after period start.']];
        }

        $fiscalYear = (int) ($input['fiscal_year'] ?? 0);
        if ($fiscalYear < 2000 || $fiscalYear > 2100) {
            return ['success' => false, 'errors' => ['fiscal_year' => 'Enter a valid fiscal year.']];
        }

        $accountId = (int) ($input['account_id'] ?? 0);
        $account   = $this->accounts->find($accountId);
        if (! $account) {
            return ['success' => false, 'errors' => ['account_id' => 'Account not found.']];
        }
        if (($account['status'] ?? '') !== 'active') {
            return ['success' => false, 'errors' => ['account_id' => 'Account must be active.']];
        }
        if (empty($account['is_postable'])) {
            return ['success' => false, 'errors' => ['account_id' => 'Account must be postable.']];
        }

        $centerId = (int) ($input['cost_center_id'] ?? 0);
        if ($centerId > 0) {
            $center = $this->centers->find($centerId);
            if (! $center) {
                return ['success' => false, 'errors' => ['cost_center_id' => 'Cost center not found.']];
            }
            if (($center['status'] ?? '') !== 'active') {
                return ['success' => false, 'errors' => ['cost_center_id' => 'Cost center must be active.']];
            }
        }

        if ($allowStatus) {
            $status = $input['status'] ?? 'draft';
            if (! in_array($status, ['draft', 'active', 'closed'], true)) {
                return ['success' => false, 'errors' => ['status' => 'Invalid status.']];
            }
        }

        return ['success' => true];
    }

    protected function mapInput(array $input, bool $includeStatus = false): array
    {
        $centerId = (int) ($input['cost_center_id'] ?? 0);

        $data = [
            'name'           => trim((string) $input['name']),
            'fiscal_year'    => (int) ($input['fiscal_year'] ?? date('Y')),
            'period_from'    => $input['period_from'] ?? date('Y-m-d'),
            'period_to'      => $input['period_to'] ?? date('Y-m-d'),
            'account_id'     => (int) ($input['account_id'] ?? 0),
            'cost_center_id' => $centerId > 0 ? $centerId : null,
            'amount'         => round((float) ($input['amount'] ?? 0), 2),
            'notes'          => ! empty($input['notes']) ? trim((string) $input['notes']) : null,
        ];

        if ($includeStatus) {
            $status = $input['status'] ?? 'draft';
            $data['status'] = in_array($status, ['draft', 'active', 'closed'], true) ? $status : 'draft';
        }

        return $data;
    }
}
