<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\SupplierBillLineModel;
use App\Models\SupplierBillModel;
use App\Models\SupplierModel;

class SupplierBillService
{
    protected SupplierBillModel $bills;
    protected SupplierBillLineModel $lines;
    protected SupplierModel $suppliers;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->bills     = new SupplierBillModel();
        $this->lines     = new SupplierBillLineModel();
        $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('supplier_bills', 'created', $actingUserId, "Created supplier 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' => 'Supplier bill not found.']];
        }
        if ($bill['status'] !== 'draft') {
            return ['success' => false, 'errors' => ['status' => 'Only draft supplier 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('supplier_bills', 'updated', $actingUserId, "Updated supplier bill #{$id}", (string) $id);

        return ['success' => true];
    }

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

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

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

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

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

        return ['success' => true];
    }

    /**
     * Apply a credit (payment or debit note) to a supplier bill's amount_paid.
     */
    public function applyCredit(int $billId, float $amount, ?int $actingUserId): array
    {
        $bill = $this->bills->find($billId);
        if (! $bill) {
            return ['success' => false, 'error' => 'Supplier bill not found.'];
        }
        if (! in_array($bill['status'], ['posted', 'partially_paid', 'overdue'], true)) {
            return ['success' => false, 'error' => 'Credits can only be applied to posted, partially paid, or overdue bills.'];
        }

        $paid  = round((float) $bill['amount_paid'] + $amount, 2);
        $total = (float) $bill['total'];
        $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->bills->update($billId, $update);

        return ['success' => true];
    }

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