<?php

namespace Modules\Procurement\Services;

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

class SupplierQuotationService
{
    protected SupplierQuotationModel $quotations;
    protected SupplierQuotationLineModel $lines;
    protected SupplierModel $suppliers;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->quotations = new SupplierQuotationModel();
        $this->lines      = new SupplierQuotationLineModel();
        $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.']];
        }

        $rfqError = $this->validateOptionalRfq($input);
        if ($rfqError !== null) {
            return ['success' => false, 'errors' => ['rfq_id' => $rfqError]];
        }

        $data = $this->mapInput($input);
        $data['number']     = $this->quotations->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->quotations->insert($data, true)) {
            return ['success' => false, 'errors' => $this->quotations->errors()];
        }

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

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

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

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $quotation = $this->quotations->find($id);
        if (! $quotation) {
            return ['success' => false, 'errors' => ['id' => 'Supplier quotation not found.']];
        }

        if (! in_array($quotation['status'], ['draft', 'rejected'], true)) {
            return ['success' => false, 'errors' => ['status' => 'Only draft or rejected supplier quotations can be edited.']];
        }

        $supplierId = (int) ($input['supplier_id'] ?? 0);
        if (! $this->suppliers->find($supplierId)) {
            return ['success' => false, 'errors' => ['supplier_id' => 'Supplier not found.']];
        }

        $rfqError = $this->validateOptionalRfq($input);
        if ($rfqError !== null) {
            return ['success' => false, 'errors' => ['rfq_id' => $rfqError]];
        }

        $data = $this->mapInput($input);
        $data['updated_by'] = $actingUserId;

        if (! $this->quotations->update($id, $data)) {
            return ['success' => false, 'errors' => $this->quotations->errors()];
        }

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

        $this->activity->log('supplier_quotations', 'updated', $actingUserId, "Updated supplier quotation #{$id}", (string) $id);

        return ['success' => true];
    }

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

        $this->quotations->update($id, [
            'status'           => 'pending_approval',
            'rejection_reason' => null,
            'updated_by'       => $actingUserId,
        ]);
        $this->activity->log('supplier_quotations', 'submitted', $actingUserId, "Submitted supplier quotation #{$id} for approval", (string) $id);

        return ['success' => true];
    }

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

        $this->quotations->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('supplier_quotations', 'approved', $actingUserId, "Approved supplier quotation #{$id}", (string) $id);

        return ['success' => true];
    }

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

        $this->quotations->update($id, [
            'status'           => 'rejected',
            'rejection_reason' => trim($reason) ?: 'Rejected',
            'updated_by'       => $actingUserId,
        ]);
        $this->activity->log('supplier_quotations', 'rejected', $actingUserId, "Rejected supplier quotation #{$id}", (string) $id);

        return ['success' => true];
    }

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

        $this->quotations->update($id, ['status' => 'cancelled', 'updated_by' => $actingUserId]);
        $this->activity->log('supplier_quotations', 'cancelled', $actingUserId, "Cancelled supplier quotation #{$id}", (string) $id);

        return ['success' => true];
    }

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

        $this->lines->where('supplier_quotation_id', $id)->delete();
        $this->quotations->delete($id);
        $this->activity->log('supplier_quotations', 'deleted', $actingUserId, "Deleted supplier quotation #{$id}", (string) $id);

        return ['success' => true];
    }

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

    protected function validateOptionalRfq(array $input): ?string
    {
        if (empty($input['rfq_id'])) {
            return null;
        }

        $rfqId = (int) $input['rfq_id'];
        $exists = db_connect()->table('rfqs')->where('id', $rfqId)->countAllResults() > 0;

        return $exists ? null : 'RFQ not found.';
    }
}
