<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\DebitNoteLineModel;
use App\Models\DebitNoteModel;
use App\Models\SupplierModel;

class DebitNoteService
{
    protected DebitNoteModel $notes;
    protected DebitNoteLineModel $lines;
    protected SupplierModel $suppliers;
    protected SupplierBillService $billService;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->notes       = new DebitNoteModel();
        $this->lines       = new DebitNoteLineModel();
        $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->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('debit_notes', 'created', $actingUserId, "Created debit 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' => 'Debit note not found.']];
        }
        if ($note['status'] !== 'draft') {
            return ['success' => false, 'errors' => ['status' => 'Only draft debit notes 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->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('debit_notes', 'updated', $actingUserId, "Updated debit 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' => 'Debit note not found.'];
        }
        if ($note['status'] !== 'draft') {
            return ['success' => false, 'error' => 'Only draft debit notes can be posted.'];
        }

        $lines = $this->lines->getForNote($id);
        if (count($lines) === 0 || (float) $note['total'] <= 0) {
            return ['success' => false, 'error' => 'Debit note must have lines and a total greater than zero.'];
        }

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

        $this->notes->update($id, [
            'status'     => 'posted',
            'posted_at'  => date('Y-m-d H:i:s'),
            'updated_by' => $actingUserId,
        ]);
        $this->activity->log('debit_notes', 'posted', $actingUserId, "Posted debit 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' => 'Debit note not found.'];
        }
        if (in_array($note['status'], ['posted', 'cancelled'], true)) {
            return ['success' => false, 'error' => 'Debit note cannot be cancelled.'];
        }

        $this->notes->update($id, ['status' => 'cancelled', 'updated_by' => $actingUserId]);
        $this->activity->log('debit_notes', 'cancelled', $actingUserId, "Cancelled debit 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' => 'Debit note not found.'];
        }
        if (! in_array($note['status'], ['draft', 'cancelled'], true)) {
            return ['success' => false, 'error' => 'Only draft or cancelled debit notes can be deleted.'];
        }

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