<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\CreditNoteLineModel;
use App\Models\CreditNoteModel;
use App\Models\CustomerInvoiceModel;

class CreditNoteService
{
    protected CreditNoteModel $notes;
    protected CreditNoteLineModel $lines;
    protected CompanyModel $companies;
    protected CustomerInvoiceModel $invoices;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->notes     = new CreditNoteModel();
        $this->lines     = new CreditNoteLineModel();
        $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->notes->nextNumber();
        $data['status']     = 'draft';
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

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

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

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

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

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

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

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

        return ['success' => true];
    }

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

        $lines = $this->lines->getForNote($id);
        $hasPositive = false;
        foreach ($lines as $line) {
            if ((float) ($line['line_total'] ?? 0) > 0) {
                $hasPositive = true;
                break;
            }
        }
        if (! $hasPositive && (float) ($note['total'] ?? 0) <= 0) {
            return ['success' => false, 'error' => 'Credit note must have at least one line with a total greater than zero.'];
        }

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

        if (! empty($note['customer_invoice_id'])) {
            $fresh = $this->notes->find($id);
            $this->applyToInvoice((int) $note['customer_invoice_id'], (float) ($fresh['total'] ?? $note['total']), $actingUserId);
        }

        $this->activity->log('credit_notes', 'posted', $actingUserId, "Posted credit note #{$id}", (string) $id);

        return ['success' => true];
    }

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

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

        return ['success' => true];
    }

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

        $this->lines->where('credit_note_id', $id)->delete();
        $this->notes->delete($id);
        $this->activity->log('credit_notes', 'deleted', $actingUserId, "Deleted credit note #{$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,
            'credit_date'         => $input['credit_date'] ?? date('Y-m-d'),
            'notes'               => $input['notes'] ?: null,
        ];
    }
}
