<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\SalesRepresentativeModel;
use App\Models\SalesTerritoryModel;

class SalesTeamService
{
    protected SalesRepresentativeModel $reps;
    protected SalesTerritoryModel $territories;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->reps        = new SalesRepresentativeModel();
        $this->territories = new SalesTerritoryModel();
        $this->activity    = new ActivityLogModel();
    }

    // --- Territories ---

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

        $data = [
            'name'       => trim($input['name']),
            'code'       => $code !== '' ? $code : null,
            'region'     => trim($input['region'] ?? '') ?: null,
            'status'     => $input['status'] ?? 'active',
            'notes'      => $input['notes'] ?: null,
            'created_by' => $actingUserId,
            'updated_by' => $actingUserId,
        ];

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

        $id = (int) $this->territories->getInsertID();
        $this->activity->log('sales_territories', 'created', $actingUserId, "Created territory #{$id}", (string) $id);

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

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

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

        $data = [
            'name'       => trim($input['name']),
            'code'       => $code !== '' ? $code : null,
            'region'     => trim($input['region'] ?? '') ?: null,
            'status'     => $input['status'] ?? 'active',
            'notes'      => $input['notes'] ?: null,
            'updated_by' => $actingUserId,
        ];

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

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

        return ['success' => true];
    }

    public function setTerritoryStatus(int $id, string $status, ?int $actingUserId): void
    {
        $this->territories->update($id, ['status' => $status, 'updated_by' => $actingUserId]);
        $this->activity->log('sales_territories', $status === 'active' ? 'activated' : 'deactivated', $actingUserId, "Set territory #{$id} to {$status}", (string) $id);
    }

    public function deleteTerritory(int $id, ?int $actingUserId): array
    {
        if (! $this->territories->find($id)) {
            return ['success' => false, 'error' => 'Territory not found.'];
        }
        $this->territories->delete($id);
        $this->activity->log('sales_territories', 'deleted', $actingUserId, "Deleted territory #{$id}", (string) $id);

        return ['success' => true];
    }

    // --- Representatives ---

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

        $data = $this->mapRepInput($input);
        $data['code']       = $code !== '' ? $code : null;
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

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

        $id = (int) $this->reps->getInsertID();
        $this->activity->log('sales_representatives', 'created', $actingUserId, "Created sales rep #{$id}", (string) $id);

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

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

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

        $data = $this->mapRepInput($input);
        $data['code']       = $code !== '' ? $code : null;
        $data['updated_by'] = $actingUserId;

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

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

        return ['success' => true];
    }

    public function setRepStatus(int $id, string $status, ?int $actingUserId): void
    {
        $this->reps->update($id, ['status' => $status, 'updated_by' => $actingUserId]);
        $this->activity->log('sales_representatives', $status === 'active' ? 'activated' : 'deactivated', $actingUserId, "Set sales rep #{$id} to {$status}", (string) $id);
    }

    public function deleteRep(int $id, ?int $actingUserId): array
    {
        if (! $this->reps->find($id)) {
            return ['success' => false, 'error' => 'Sales representative not found.'];
        }
        $this->reps->delete($id);
        $this->activity->log('sales_representatives', 'deleted', $actingUserId, "Deleted sales rep #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function mapRepInput(array $input): array
    {
        return [
            'name'         => trim($input['name']),
            'employee_id'  => ! empty($input['employee_id']) ? (int) $input['employee_id'] : null,
            'territory_id' => ! empty($input['territory_id']) ? (int) $input['territory_id'] : null,
            'email'        => trim($input['email'] ?? '') ?: null,
            'phone'        => trim($input['phone'] ?? '') ?: null,
            'status'       => $input['status'] ?? 'active',
            'notes'        => $input['notes'] ?: null,
        ];
    }
}
