<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\InvoiceLineModel;
use App\Models\InvoiceModel;
use App\Models\SalesOrderLineModel;
use App\Models\SalesOrderModel;

class InvoiceService
{
    protected InvoiceModel $invoices;
    protected InvoiceLineModel $lines;
    protected CompanyModel $companies;
    protected SalesOrderModel $orders;
    protected SalesOrderLineModel $orderLines;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->invoices   = new InvoiceModel();
        $this->lines      = new InvoiceLineModel();
        $this->companies  = new CompanyModel();
        $this->orders     = new SalesOrderModel();
        $this->orderLines = new SalesOrderLineModel();
        $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('invoices', 'created', $actingUserId, "Created invoice #{$id} ({$data['number']})", (string) $id);

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

    public function createFromOrder(int $orderId, ?int $actingUserId): array
    {
        $order = $this->orders->find($orderId);
        if (! $order) {
            return ['success' => false, 'error' => 'Sales order not found.'];
        }
        if (! in_array($order['status'], ['approved', 'confirmed', 'in_progress', 'fulfilled'], true)) {
            return ['success' => false, 'error' => 'Only approved or fulfilled orders can be invoiced.'];
        }

        $orderLines = $this->orderLines->getForOrder($orderId);
        $lines = [];
        foreach ($orderLines as $line) {
            $lines[] = [
                'item_code'  => $line['item_code'],
                'item_name'  => $line['item_name'],
                'quantity'   => $line['quantity'],
                'unit'       => $line['unit'],
                'unit_price' => $line['unit_price'],
            ];
        }

        return $this->create([
            'company_id'     => $order['company_id'],
            'sales_order_id' => $orderId,
            'invoice_date'   => date('Y-m-d'),
            'due_date'       => date('Y-m-d', strtotime('+30 days')),
            'tax_amount'     => $order['tax_amount'],
            'notes'          => 'Created from order ' . $order['number'],
            'lines'          => $lines,
        ], $actingUserId);
    }

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

        return ['success' => true];
    }

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

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

        return ['success' => true];
    }

    public function updatePayment(int $id, array $input, ?int $actingUserId): array
    {
        $invoice = $this->invoices->find($id);
        if (! $invoice) {
            return ['success' => false, 'error' => 'Invoice not found.'];
        }
        if (in_array($invoice['status'], ['draft', 'cancelled'], true)) {
            return ['success' => false, 'error' => 'Cannot update payment on draft or cancelled invoices.'];
        }

        $paid  = round((float) ($input['amount_paid'] ?? 0), 2);
        $total = (float) $invoice['total'];
        if ($paid < 0) {
            return ['success' => false, 'error' => 'Amount paid cannot be negative.'];
        }

        $status = 'issued';
        $paidAt = null;
        if ($paid <= 0) {
            $status = $this->isOverdue($invoice) ? 'overdue' : 'issued';
        } elseif ($paid < $total) {
            $status = 'partially_paid';
        } else {
            $paid  = $total;
            $status = 'paid';
            $paidAt = date('Y-m-d H:i:s');
        }

        if ($status !== 'paid' && $this->isOverdue($invoice) && $paid < $total) {
            $status = $paid > 0 ? 'partially_paid' : 'overdue';
        }

        $this->invoices->update($id, [
            'amount_paid'   => $paid,
            'status'        => $status,
            'payment_notes' => trim((string) ($input['payment_notes'] ?? '')) ?: null,
            'paid_at'       => $paidAt,
            'updated_by'    => $actingUserId,
        ]);
        $this->activity->log('invoices', 'payment_updated', $actingUserId, "Updated payment on 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' => 'Invoice not found.'];
        }
        if (in_array($invoice['status'], ['paid', 'cancelled'], true)) {
            return ['success' => false, 'error' => 'Invoice cannot be cancelled.'];
        }

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

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

        return ['success' => true];
    }

    protected function isOverdue(array $invoice): bool
    {
        return ! empty($invoice['due_date']) && $invoice['due_date'] < date('Y-m-d');
    }

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