<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\QuotationLineModel;
use App\Models\QuotationModel;
use App\Models\SalesOrderLineModel;
use App\Models\SalesOrderModel;

class SalesOrderService
{
    protected SalesOrderModel $orders;
    protected SalesOrderLineModel $lines;
    protected CompanyModel $companies;
    protected QuotationModel $quotations;
    protected QuotationLineModel $quotationLines;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->orders          = new SalesOrderModel();
        $this->lines           = new SalesOrderLineModel();
        $this->companies       = new CompanyModel();
        $this->quotations      = new QuotationModel();
        $this->quotationLines  = new QuotationLineModel();
        $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->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->replaceForOrder($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('sales_orders', 'created', $actingUserId, "Created sales order #{$id} ({$data['number']})", (string) $id);

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

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

        $qLines = $this->quotationLines->getForQuotation($quotationId);
        $input = [
            'company_id'    => $quotation['company_id'],
            'contact_id'    => $quotation['contact_id'],
            'quotation_id'  => $quotationId,
            'order_date'    => date('Y-m-d'),
            'tax_amount'    => $quotation['tax_amount'],
            'notes'         => $quotation['notes'],
            'status'        => 'draft',
            'lines'         => $qLines,
        ];

        $result = $this->create($input, $actingUserId);
        if ($result['success']) {
            $this->quotations->update($quotationId, [
                'status'     => 'converted',
                'updated_by' => $actingUserId,
            ]);
            $this->activity->log('quotations', 'converted', $actingUserId, "Converted quotation #{$quotationId} to order #{$result['id']}", (string) $quotationId);
        }

        return $result;
    }

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

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

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

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

        return ['success' => true];
    }

    public function updateTracking(int $id, string $status, ?string $trackingNotes, ?int $actingUserId): array
    {
        $order = $this->orders->find($id);
        if (! $order) {
            return ['success' => false, 'error' => 'Sales order not found.'];
        }

        $allowed = ['approved', 'confirmed', 'in_progress', 'fulfilled', 'cancelled'];
        if (! in_array($status, $allowed, true)) {
            return ['success' => false, 'error' => 'Invalid tracking status.'];
        }

        if (! in_array($order['status'], ['approved', 'confirmed', 'in_progress', 'fulfilled'], true)
            && ! ($order['status'] === 'approved' && $status === 'confirmed')) {
            if (! in_array($order['status'], $allowed, true)) {
                return ['success' => false, 'error' => 'Order must be approved before tracking updates.'];
            }
        }

        if (! in_array($order['status'], ['approved', 'confirmed', 'in_progress', 'fulfilled'], true)) {
            return ['success' => false, 'error' => 'Order must be approved before tracking updates.'];
        }

        $this->orders->update($id, [
            'status'         => $status,
            'tracking_notes' => $trackingNotes ?: null,
            'updated_by'     => $actingUserId,
        ]);
        $this->activity->log('sales_orders', 'tracking_updated', $actingUserId, "Updated tracking for order #{$id} to {$status}", (string) $id);

        return ['success' => true];
    }

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

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

        return ['success' => true];
    }

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