<?php

namespace Modules\Accounting\Services;

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

class CustomerInvoiceService
{
    protected CustomerInvoiceModel $invoices;
    protected CustomerInvoiceLineModel $lines;
    protected CompanyModel $companies;
    protected ActivityLogModel $activity;

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

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

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

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

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

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

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

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

        return ['success' => true];
    }

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

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

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

        return ['success' => true];
    }

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

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

        return ['success' => true];
    }

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

        $this->lines->where('customer_invoice_id', $id)->delete();
        $this->invoices->delete($id);
        $this->activity->log('customer_invoices', 'deleted', $actingUserId, "Deleted customer invoice #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'company_id'   => (int) $input['company_id'],
            'invoice_date' => $input['invoice_date'] ?? date('Y-m-d'),
            'due_date'     => ! empty($input['due_date']) ? $input['due_date'] : null,
            'notes'        => $input['notes'] ?: null,
        ];
    }
}
