<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\ApPaymentModel;
use App\Models\SupplierModel;

class ApPaymentService
{
    protected ApPaymentModel $payments;
    protected SupplierModel $suppliers;
    protected SupplierBillService $billService;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->payments    = new ApPaymentModel();
        $this->suppliers   = new SupplierModel();
        $this->billService = new SupplierBillService();
        $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->payments->nextNumber();
        $data['status']     = 'draft';
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

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

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

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

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $payment = $this->payments->find($id);
        if (! $payment) {
            return ['success' => false, 'errors' => ['id' => 'Payment not found.']];
        }
        if ($payment['status'] !== 'draft') {
            return ['success' => false, 'errors' => ['status' => 'Only draft payments 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->payments->update($id, $data)) {
            return ['success' => false, 'errors' => $this->payments->errors()];
        }

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

        return ['success' => true];
    }

    public function post(int $id, ?int $actingUserId): array
    {
        $payment = $this->payments->find($id);
        if (! $payment) {
            return ['success' => false, 'error' => 'Payment not found.'];
        }
        if ($payment['status'] !== 'draft') {
            return ['success' => false, 'error' => 'Only draft payments can be posted.'];
        }
        if ((float) $payment['amount'] <= 0) {
            return ['success' => false, 'error' => 'Payment amount must be greater than zero.'];
        }

        if (! empty($payment['supplier_bill_id'])) {
            $applied = $this->billService->applyCredit(
                (int) $payment['supplier_bill_id'],
                (float) $payment['amount'],
                $actingUserId
            );
            if (! $applied['success']) {
                return $applied;
            }
        }

        $this->payments->update($id, [
            'status'     => 'posted',
            'posted_at'  => date('Y-m-d H:i:s'),
            'updated_by' => $actingUserId,
        ]);
        $this->activity->log('ap_payments', 'posted', $actingUserId, "Posted AP payment #{$id}", (string) $id);

        return ['success' => true];
    }

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

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

        return ['success' => true];
    }

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

        $this->payments->delete($id);
        $this->activity->log('ap_payments', 'deleted', $actingUserId, "Deleted AP payment #{$id}", (string) $id);

        return ['success' => true];
    }

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