<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\SalesStageModel;

class SalesStageService
{
    protected SalesStageModel $stages;
    protected ActivityLogModel $activity;

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

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

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

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

        $id = $this->stages->getInsertID();
        $this->activity->log('sales_stages', 'created', $actingUserId, "Created sales stage #{$id} ({$data['name']})", (string) $id);

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

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

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

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

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

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

        return ['success' => true];
    }

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

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

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

        $this->stages->delete($id);
        $this->activity->log('sales_stages', 'deleted', $actingUserId, "Deleted sales stage #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'name'                => trim($input['name']),
            'sort_order'          => (int) ($input['sort_order'] ?? 0),
            'default_probability' => max(0, min(100, (int) ($input['default_probability'] ?? 0))),
            'is_won'              => ! empty($input['is_won']) ? 1 : 0,
            'is_lost'             => ! empty($input['is_lost']) ? 1 : 0,
            'description'         => $input['description'] ?: null,
            'status'              => $input['status'] ?? 'active',
        ];
    }
}
