<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\CustomerInvoiceModel;
use App\Models\CustomerReceiptModel;

class CustomerReceiptService
{
    protected CustomerReceiptModel $receipts;
    protected CompanyModel $companies;
    protected CustomerInvoiceModel $invoices;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->receipts  = new CustomerReceiptModel();
        $this->companies = new CompanyModel();
        $this->invoices  = new CustomerInvoiceModel();
        $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->receipts->nextNumber();
        $data['status']     = 'draft';
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

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

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

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

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

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

        return ['success' => true];
    }

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

        $amount = (float) $receipt['amount'];
        if ($amount <= 0) {
            return ['success' => false, 'error' => 'Receipt amount must be greater than zero.'];
        }

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

        if (! empty($receipt['customer_invoice_id'])) {
            $this->applyToInvoice((int) $receipt['customer_invoice_id'], $amount, $actingUserId);
        }

        $this->activity->log('customer_receipts', 'posted', $actingUserId, "Posted customer receipt #{$id}", (string) $id);

        return ['success' => true];
    }

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

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

        return ['success' => true];
    }

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

        $this->receipts->delete($id);
        $this->activity->log('customer_receipts', 'deleted', $actingUserId, "Deleted customer receipt #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function applyToInvoice(int $invoiceId, float $amount, ?int $actingUserId): void
    {
        $invoice = $this->invoices->find($invoiceId);
        if (! $invoice) {
            return;
        }
        if (! in_array($invoice['status'], ['posted', 'partially_paid', 'overdue'], true)) {
            return;
        }

        $total = (float) $invoice['total'];
        $paid  = round((float) $invoice['amount_paid'] + $amount, 2);
        $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->invoices->update($invoiceId, $update);
    }

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