<?php

namespace Modules\Procurement\Services;

use App\Models\ActivityLogModel;
use App\Models\SupplierModel;
use App\Models\SupplierPaymentModel;
use App\Models\VendorBillModel;

class SupplierPaymentService
{
    protected SupplierPaymentModel $payments;
    protected SupplierModel $suppliers;
    protected VendorBillModel $bills;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->payments  = new SupplierPaymentModel();
        $this->suppliers = new SupplierModel();
        $this->bills     = new VendorBillModel();
        $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('supplier_payments', 'created', $actingUserId, "Created supplier 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' => 'Supplier payment not found.']];
        }
        if (! in_array($payment['status'], ['draft', 'pending'], true)) {
            return ['success' => false, 'errors' => ['status' => 'Only draft or pending 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('supplier_payments', 'updated', $actingUserId, "Updated supplier payment #{$id}", (string) $id);

        return ['success' => true];
    }

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

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

        return ['success' => true];
    }

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

        $this->payments->update($id, [
            'status'       => 'processed',
            'processed_at' => date('Y-m-d H:i:s'),
            'updated_by'   => $actingUserId,
        ]);

        if (! empty($payment['vendor_bill_id'])) {
            $bill = $this->bills->find((int) $payment['vendor_bill_id']);
            if ($bill) {
                $paid  = round((float) $bill['amount_paid'] + (float) $payment['amount'], 2);
                $total = (float) $bill['total'];
                $status = $paid >= $total ? 'paid' : 'partially_paid';
                $update = [
                    'amount_paid' => $paid >= $total ? $total : $paid,
                    'status'      => $status,
                    'updated_by'  => $actingUserId,
                ];
                if ($status === 'paid') {
                    $update['paid_at'] = date('Y-m-d H:i:s');
                }
                $this->bills->update((int) $bill['id'], $update);
            }
        }

        $this->activity->log('supplier_payments', 'processed', $actingUserId, "Processed supplier 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' => 'Supplier payment not found.'];
        }
        if (in_array($payment['status'], ['processed', 'cancelled'], true)) {
            return ['success' => false, 'error' => 'Supplier payment cannot be cancelled.'];
        }

        $this->payments->update($id, ['status' => 'cancelled', 'updated_by' => $actingUserId]);
        $this->activity->log('supplier_payments', 'cancelled', $actingUserId, "Cancelled supplier 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' => 'Supplier 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('supplier_payments', 'deleted', $actingUserId, "Deleted supplier payment #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'supplier_id'    => (int) $input['supplier_id'],
            'vendor_bill_id' => ! empty($input['vendor_bill_id']) ? (int) $input['vendor_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,
        ];
    }
}
