<?php

namespace Modules\Procurement\Services;

use App\Models\ActivityLogModel;
use App\Models\PurchaseOrderLineModel;
use App\Models\PurchaseOrderModel;
use App\Models\SupplierModel;
use App\Models\SupplierQuotationLineModel;
use App\Models\SupplierQuotationModel;

class PurchaseOrderService
{
    protected PurchaseOrderModel $orders;
    protected PurchaseOrderLineModel $lines;
    protected SupplierModel $suppliers;
    protected SupplierQuotationModel $supplierQuotations;
    protected SupplierQuotationLineModel $supplierQuotationLines;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->orders                 = new PurchaseOrderModel();
        $this->lines                  = new PurchaseOrderLineModel();
        $this->suppliers              = new SupplierModel();
        $this->supplierQuotations     = new SupplierQuotationModel();
        $this->supplierQuotationLines = new SupplierQuotationLineModel();
        $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->orders->nextNumber();
        $data['status']     = in_array($input['status'] ?? 'draft', ['draft', 'pending_approval'], true)
            ? ($input['status'] ?? 'draft')
            : 'draft';
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

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

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

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

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

    public function createFromSupplierQuotation(int $sqId, ?int $userId): array
    {
        $quotation = $this->supplierQuotations->find($sqId);
        if (! $quotation) {
            return ['success' => false, 'error' => 'Supplier quotation not found.'];
        }
        if (! in_array($quotation['status'], ['approved', 'sent'], true)) {
            return ['success' => false, 'error' => 'Only approved or sent supplier quotations can be converted.'];
        }

        $qLines = $this->supplierQuotationLines->getForSupplierQuotation($sqId);
        $input = [
            'supplier_id'           => $quotation['supplier_id'],
            'supplier_quotation_id' => $sqId,
            'order_date'            => date('Y-m-d'),
            'tax_amount'            => $quotation['tax_amount'],
            'notes'                 => $quotation['notes'],
            'status'                => 'draft',
            'lines'                 => $qLines,
        ];

        $result = $this->create($input, $userId);
        if ($result['success']) {
            $this->supplierQuotations->update($sqId, [
                'status'     => 'converted',
                'updated_by' => $userId,
            ]);
            $this->activity->log(
                'supplier_quotations',
                'converted',
                $userId,
                "Converted supplier quotation #{$sqId} to purchase order #{$result['id']}",
                (string) $sqId
            );
        }

        return $result;
    }

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $order = $this->orders->find($id);
        if (! $order) {
            return ['success' => false, 'errors' => ['id' => 'Purchase order not found.']];
        }
        if (! in_array($order['status'], ['draft', 'rejected'], true)) {
            return ['success' => false, 'errors' => ['status' => 'Only draft or rejected purchase orders 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->orders->update($id, $data)) {
            return ['success' => false, 'errors' => $this->orders->errors()];
        }

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

        $this->activity->log('purchase_orders', 'updated', $actingUserId, "Updated purchase order #{$id}", (string) $id);

        return ['success' => true];
    }

    public function submitForApproval(int $id, ?int $actingUserId): array
    {
        $order = $this->orders->find($id);
        if (! $order) {
            return ['success' => false, 'error' => 'Purchase order not found.'];
        }
        if (! in_array($order['status'], ['draft', 'rejected'], true)) {
            return ['success' => false, 'error' => 'Only draft or rejected purchase orders can be submitted.'];
        }

        $this->orders->update($id, [
            'status'           => 'pending_approval',
            'rejection_reason' => null,
            'updated_by'       => $actingUserId,
        ]);
        $this->activity->log('purchase_orders', 'submitted', $actingUserId, "Submitted purchase order #{$id} for approval", (string) $id);

        return ['success' => true];
    }

    public function approve(int $id, ?int $actingUserId): array
    {
        $order = $this->orders->find($id);
        if (! $order) {
            return ['success' => false, 'error' => 'Purchase order not found.'];
        }
        if ($order['status'] !== 'pending_approval') {
            return ['success' => false, 'error' => 'Purchase order is not pending approval.'];
        }

        $this->orders->update($id, [
            'status'           => 'approved',
            'rejection_reason' => null,
            'approved_by'      => $actingUserId,
            'approved_at'      => date('Y-m-d H:i:s'),
            'updated_by'       => $actingUserId,
        ]);
        $this->activity->log('purchase_orders', 'approved', $actingUserId, "Approved purchase order #{$id}", (string) $id);

        return ['success' => true];
    }

    public function reject(int $id, string $reason, ?int $actingUserId): array
    {
        $order = $this->orders->find($id);
        if (! $order) {
            return ['success' => false, 'error' => 'Purchase order not found.'];
        }
        if ($order['status'] !== 'pending_approval') {
            return ['success' => false, 'error' => 'Purchase order is not pending approval.'];
        }

        $this->orders->update($id, [
            'status'           => 'rejected',
            'rejection_reason' => trim($reason) ?: 'Rejected',
            'updated_by'       => $actingUserId,
        ]);
        $this->activity->log('purchase_orders', 'rejected', $actingUserId, "Rejected purchase order #{$id}", (string) $id);

        return ['success' => true];
    }

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

        $this->orders->update($id, ['status' => 'cancelled', 'updated_by' => $actingUserId]);
        $this->activity->log('purchase_orders', 'cancelled', $actingUserId, "Cancelled purchase order #{$id}", (string) $id);

        return ['success' => true];
    }

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

        $this->lines->where('purchase_order_id', $id)->delete();
        $this->orders->delete($id);
        $this->activity->log('purchase_orders', 'deleted', $actingUserId, "Deleted purchase order #{$id}", (string) $id);

        return ['success' => true];
    }

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