<?php

namespace Modules\Procurement\Services;

use App\Models\ActivityLogModel;
use App\Models\SupplierModel;
use App\Models\VendorBillLineModel;
use App\Models\VendorBillModel;

class VendorBillService
{
    protected VendorBillModel $bills;
    protected VendorBillLineModel $lines;
    protected SupplierModel $suppliers;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->bills     = new VendorBillModel();
        $this->lines     = new VendorBillLineModel();
        $this->suppliers = new SupplierModel();
        $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->bills->nextNumber();
        $data['status']      = 'draft';
        $data['amount_paid'] = 0;
        $data['created_by']  = $actingUserId;
        $data['updated_by']  = $actingUserId;

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

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

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

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

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

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

        $this->activity->log('vendor_bills', 'updated', $actingUserId, "Updated vendor bill #{$id}", (string) $id);

        return ['success' => true];
    }

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

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

        return ['success' => true];
    }

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

        $this->bills->update($id, ['status' => 'cancelled', 'updated_by' => $actingUserId]);
        $this->activity->log('vendor_bills', 'cancelled', $actingUserId, "Cancelled vendor bill #{$id}", (string) $id);

        return ['success' => true];
    }

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

        $this->lines->where('vendor_bill_id', $id)->delete();
        $this->bills->delete($id);
        $this->activity->log('vendor_bills', 'deleted', $actingUserId, "Deleted vendor bill #{$id}", (string) $id);

        return ['success' => true];
    }

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