<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\RefundModel;

class RefundService
{
    protected RefundModel $refunds;
    protected CompanyModel $companies;
    protected ActivityLogModel $activity;

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

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

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

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

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

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

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $refund = $this->refunds->find($id);
        if (! $refund) {
            return ['success' => false, 'errors' => ['id' => 'Refund not found.']];
        }
        if (! in_array($refund['status'], ['draft', 'pending'], true)) {
            return ['success' => false, 'errors' => ['status' => 'Only draft or pending refunds can be edited.']];
        }

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

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

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

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

        return ['success' => true];
    }

    public function submit(int $id, ?int $actingUserId): array
    {
        $refund = $this->refunds->find($id);
        if (! $refund) {
            return ['success' => false, 'error' => 'Refund not found.'];
        }
        if ($refund['status'] !== 'draft') {
            return ['success' => false, 'error' => 'Only draft refunds can be submitted.'];
        }

        $this->refunds->update($id, ['status' => 'pending', 'updated_by' => $actingUserId]);
        $this->activity->log('refunds', 'submitted', $actingUserId, "Submitted refund #{$id}", (string) $id);

        return ['success' => true];
    }

    public function process(int $id, ?int $actingUserId): array
    {
        $refund = $this->refunds->find($id);
        if (! $refund) {
            return ['success' => false, 'error' => 'Refund not found.'];
        }
        if ($refund['status'] !== 'pending') {
            return ['success' => false, 'error' => 'Only pending refunds can be processed.'];
        }

        $this->refunds->update($id, [
            'status'       => 'processed',
            'processed_at' => date('Y-m-d H:i:s'),
            'updated_by'   => $actingUserId,
        ]);
        $this->activity->log('refunds', 'processed', $actingUserId, "Processed refund #{$id}", (string) $id);

        return ['success' => true];
    }

    public function cancel(int $id, ?int $actingUserId): array
    {
        $refund = $this->refunds->find($id);
        if (! $refund) {
            return ['success' => false, 'error' => 'Refund not found.'];
        }
        if (in_array($refund['status'], ['processed', 'cancelled'], true)) {
            return ['success' => false, 'error' => 'Refund cannot be cancelled.'];
        }

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

        return ['success' => true];
    }

    public function delete(int $id, ?int $actingUserId): array
    {
        $refund = $this->refunds->find($id);
        if (! $refund) {
            return ['success' => false, 'error' => 'Refund not found.'];
        }
        if (! in_array($refund['status'], ['draft', 'cancelled'], true)) {
            return ['success' => false, 'error' => 'Only draft or cancelled refunds can be deleted.'];
        }

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

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'company_id'      => (int) $input['company_id'],
            'invoice_id'      => ! empty($input['invoice_id']) ? (int) $input['invoice_id'] : null,
            'sales_return_id' => ! empty($input['sales_return_id']) ? (int) $input['sales_return_id'] : null,
            'refund_date'     => $input['refund_date'] ?? date('Y-m-d'),
            'amount'          => round((float) ($input['amount'] ?? 0), 2),
            'method'          => trim((string) ($input['method'] ?? '')) ?: null,
            'notes'           => $input['notes'] ?: null,
        ];
    }
}
