<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\QuotationLineModel;
use App\Models\QuotationModel;
use App\Models\QuotationTemplateModel;

class QuotationService
{
    protected QuotationModel $quotations;
    protected QuotationLineModel $lines;
    protected CompanyModel $companies;
    protected QuotationTemplateModel $templates;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->quotations = new QuotationModel();
        $this->lines      = new QuotationLineModel();
        $this->companies  = new CompanyModel();
        $this->templates  = new QuotationTemplateModel();
        $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->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 (! empty($data['template_id'])) {
            $template = $this->templates->find($data['template_id']);
            if ($template && empty($data['valid_until']) && ! empty($data['quotation_date'])) {
                $days = (int) $template['default_validity_days'];
                $data['valid_until'] = date('Y-m-d', strtotime($data['quotation_date'] . " +{$days} days"));
            }
        }

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

        $id = (int) $this->quotations->getInsertID();
        $result = $this->lines->replaceForQuotation($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('quotations', 'created', $actingUserId, "Created 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' => 'Quotation not found.']];
        }

        if (! in_array($quotation['status'], ['draft', 'rejected'], true)) {
            return ['success' => false, 'errors' => ['status' => 'Only draft or rejected quotations 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->quotations->update($id, $data)) {
            return ['success' => false, 'errors' => $this->quotations->errors()];
        }

        $result = $this->lines->replaceForQuotation($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('quotations', 'updated', $actingUserId, "Updated 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' => 'Quotation not found.'];
        }
        if (! in_array($quotation['status'], ['draft', 'rejected'], true)) {
            return ['success' => false, 'error' => 'Only draft or rejected quotations can be submitted.'];
        }

        $this->quotations->update($id, [
            'status'           => 'pending_approval',
            'rejection_reason' => null,
            'updated_by'       => $actingUserId,
        ]);
        $this->activity->log('quotations', 'submitted', $actingUserId, "Submitted 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' => 'Quotation not found.'];
        }
        if ($quotation['status'] !== 'pending_approval') {
            return ['success' => false, 'error' => '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('quotations', 'approved', $actingUserId, "Approved 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' => 'Quotation not found.'];
        }
        if ($quotation['status'] !== 'pending_approval') {
            return ['success' => false, 'error' => 'Quotation is not pending approval.'];
        }

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

        return ['success' => true];
    }

    public function markSent(int $id, ?int $actingUserId): array
    {
        $quotation = $this->quotations->find($id);
        if (! $quotation) {
            return ['success' => false, 'error' => 'Quotation not found.'];
        }
        if ($quotation['status'] !== 'approved') {
            return ['success' => false, 'error' => 'Only approved quotations can be marked as sent.'];
        }

        $this->quotations->update($id, ['status' => 'sent', 'updated_by' => $actingUserId]);
        $this->activity->log('quotations', 'sent', $actingUserId, "Marked quotation #{$id} as sent", (string) $id);

        return ['success' => true];
    }

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

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

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

        return ['success' => true];
    }

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