<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\SalesActivityModel;

class SalesActivityService
{
    protected SalesActivityModel $activities;
    protected CompanyModel $companies;
    protected ActivityLogModel $activity;

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

    public function create(array $input, ?int $actingUserId): array
    {
        $companyId = ! empty($input['company_id']) ? (int) $input['company_id'] : null;
        if ($companyId && ! $this->companies->find($companyId)) {
            return ['success' => false, 'errors' => ['company_id' => 'Company not found.']];
        }

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

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

        $id = $this->activities->getInsertID();
        $type = $data['activity_type'] ?? 'activity';
        $this->activity->log('sales_activities', 'created', $actingUserId, "Created {$type} activity #{$id}", (string) $id);

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

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

        $companyId = ! empty($input['company_id']) ? (int) $input['company_id'] : null;
        if ($companyId && ! $this->companies->find($companyId)) {
            return ['success' => false, 'errors' => ['company_id' => 'Company not found.']];
        }

        $data = $this->mapInput($input);
        // Preserve activity_type on update unless explicitly provided
        if (empty($data['activity_type'])) {
            $data['activity_type'] = $entry['activity_type'];
        }
        $data['updated_by'] = $actingUserId;

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

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

        return ['success' => true];
    }

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

        $this->activities->update($id, [
            'status'       => 'completed',
            'completed_at' => date('Y-m-d H:i:s'),
            'updated_by'   => $actingUserId,
        ]);
        $this->activity->log('sales_activities', 'completed', $actingUserId, "Completed activity #{$id}", (string) $id);

        return ['success' => true];
    }

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

        $this->activities->update($id, [
            'status'     => 'cancelled',
            'updated_by' => $actingUserId,
        ]);
        $this->activity->log('sales_activities', 'cancelled', $actingUserId, "Cancelled activity #{$id}", (string) $id);

        return ['success' => true];
    }

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

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

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'activity_type'    => $input['activity_type'] ?? null,
            'subject'          => trim($input['subject'] ?? ''),
            'opportunity_id'   => ! empty($input['opportunity_id']) ? (int) $input['opportunity_id'] : null,
            'company_id'       => ! empty($input['company_id']) ? (int) $input['company_id'] : null,
            'contact_id'       => ! empty($input['contact_id']) ? (int) $input['contact_id'] : null,
            'status'           => $input['status'] ?? 'planned',
            'priority'         => $input['priority'] ?? 'normal',
            'scheduled_at'     => $this->normalizeDateTime($input['scheduled_at'] ?? null),
            'due_at'           => $this->normalizeDateTime($input['due_at'] ?? null),
            'duration_minutes' => isset($input['duration_minutes']) && $input['duration_minutes'] !== ''
                ? (int) $input['duration_minutes']
                : null,
            'description'      => ! empty($input['description']) ? $input['description'] : null,
        ];
    }

    protected function normalizeDateTime($value): ?string
    {
        $value = trim((string) ($value ?? ''));
        if ($value === '') {
            return null;
        }

        // datetime-local yields Y-m-d\TH:i — convert and append seconds
        $value = str_replace('T', ' ', $value);
        if (strlen($value) === 16) {
            $value .= ':00';
        }

        return $value;
    }
}
