<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\CustomerHistoryModel;

class CompanyService
{
    protected CompanyModel $companies;
    protected CustomerHistoryModel $history;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->companies = new CompanyModel();
        $this->history   = new CustomerHistoryModel();
        $this->activity  = new ActivityLogModel();
    }

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

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

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

        $id = $this->companies->getInsertID();
        $this->activity->log('companies', 'created', $actingUserId, "Created company #{$id} ({$data['name']})", (string) $id);
        $this->history->insert([
            'company_id'  => $id,
            'event_type'  => 'status_change',
            'title'       => 'Company created',
            'description' => "Company \"{$data['name']}\" was added to the customer registry.",
            'event_at'    => date('Y-m-d H:i:s'),
            'created_by'  => $actingUserId,
        ]);

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

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

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

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

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

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

        if (($company['status'] ?? '') !== ($data['status'] ?? '')) {
            $this->history->insert([
                'company_id'  => $id,
                'event_type'  => 'status_change',
                'title'       => 'Status changed to ' . ($data['status'] ?? 'active'),
                'description' => null,
                'event_at'    => date('Y-m-d H:i:s'),
                'created_by'  => $actingUserId,
            ]);
        }

        return ['success' => true];
    }

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

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

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

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

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'name'              => trim($input['name']),
            'email'             => trim($input['email'] ?? '') ?: null,
            'phone'             => trim($input['phone'] ?? '') ?: null,
            'website'           => trim($input['website'] ?? '') ?: null,
            'industry'          => trim($input['industry'] ?? '') ?: null,
            'customer_group_id' => ! empty($input['customer_group_id']) ? (int) $input['customer_group_id'] : null,
            'address'           => trim($input['address'] ?? '') ?: null,
            'city'              => trim($input['city'] ?? '') ?: null,
            'country'           => trim($input['country'] ?? '') ?: null,
            'status'            => $input['status'] ?? 'active',
            'notes'             => $input['notes'] ?: null,
        ];
    }
}
