<?php

namespace Modules\Procurement\Services;

use App\Models\ActivityLogModel;
use App\Models\PurchaseReturnLineModel;
use App\Models\PurchaseReturnModel;
use App\Models\SupplierModel;

class PurchaseReturnService
{
    protected PurchaseReturnModel $returns;
    protected PurchaseReturnLineModel $lines;
    protected SupplierModel $suppliers;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->returns   = new PurchaseReturnModel();
        $this->lines     = new PurchaseReturnLineModel();
        $this->suppliers = new SupplierModel();
        $this->activity  = new ActivityLogModel();
    }

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

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

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

        $id = (int) $this->returns->getInsertID();
        $result = $this->lines->replaceForReturn($id, $input['lines'] ?? []);
        $tax = (float) ($input['tax_amount'] ?? 0);
        $this->returns->update($id, [
            'subtotal'   => $result['subtotal'],
            'tax_amount' => $tax,
            'total'      => round($result['subtotal'] + $tax, 2),
        ]);

        $this->activity->log('purchase_returns', 'created', $actingUserId, "Created purchase return #{$id} ({$data['number']})", (string) $id);

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

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

        $supplierId = (int) ($input['supplier_id'] ?? 0);
        if (! $this->suppliers->find($supplierId)) {
            return ['success' => false, 'errors' => ['supplier_id' => 'Supplier not found.']];
        }

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

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

        $result = $this->lines->replaceForReturn($id, $input['lines'] ?? []);
        $tax = (float) ($input['tax_amount'] ?? 0);
        $this->returns->update($id, [
            'subtotal'   => $result['subtotal'],
            'tax_amount' => $tax,
            'total'      => round($result['subtotal'] + $tax, 2),
            'updated_by' => $actingUserId,
        ]);

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

        return ['success' => true];
    }

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

        $this->returns->update($id, ['status' => 'submitted', 'updated_by' => $actingUserId]);
        $this->activity->log('purchase_returns', 'submitted', $actingUserId, "Submitted purchase return #{$id}", (string) $id);

        return ['success' => true];
    }

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

        $this->returns->update($id, [
            'status'      => 'approved',
            'approved_by' => $actingUserId,
            'approved_at' => date('Y-m-d H:i:s'),
            'updated_by'  => $actingUserId,
        ]);
        $this->activity->log('purchase_returns', 'approved', $actingUserId, "Approved purchase return #{$id}", (string) $id);

        return ['success' => true];
    }

    public function complete(int $id, ?int $actingUserId): array
    {
        $return = $this->returns->find($id);
        if (! $return) {
            return ['success' => false, 'error' => 'Purchase return not found.'];
        }
        if ($return['status'] !== 'approved') {
            return ['success' => false, 'error' => 'Only approved returns can be completed.'];
        }

        $this->returns->update($id, ['status' => 'completed', 'updated_by' => $actingUserId]);
        $this->activity->log('purchase_returns', 'completed', $actingUserId, "Completed purchase return #{$id}", (string) $id);

        return ['success' => true];
    }

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

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

        return ['success' => true];
    }

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

        $this->lines->where('purchase_return_id', $id)->delete();
        $this->returns->delete($id);
        $this->activity->log('purchase_returns', 'deleted', $actingUserId, "Deleted purchase return #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'supplier_id'       => (int) $input['supplier_id'],
            'purchase_order_id' => ! empty($input['purchase_order_id']) ? (int) $input['purchase_order_id'] : null,
            'goods_receipt_id'  => ! empty($input['goods_receipt_id']) ? (int) $input['goods_receipt_id'] : null,
            'return_date'       => $input['return_date'] ?? date('Y-m-d'),
            'reason'            => $input['reason'] ?: null,
            'notes'             => $input['notes'] ?: null,
        ];
    }
}
