<?php

namespace App\Models;

use App\Models\Traits\HasAuditFields;
use App\Models\Traits\HasScopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class SalesOrder extends Model
{
    use HasFactory, HasScopes, SoftDeletes, HasAuditFields;

    /**
     * Status constants
     */
    public const STATUS_PENDING = 'pending';
    public const STATUS_CONFIRMED = 'confirmed';
    public const STATUS_IN_PRODUCTION = 'in_production';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_CANCELLED = 'cancelled';

    /**
     * Custom column mapping for HasScopes trait
     */
    protected string $dateColumn = 'sales_order_date';
    protected string $companyColumn = 'company_name';

    protected $fillable = [
        'sales_order_no',
        'sales_order_date',
        'grn_no',
        'customer_ref_no',
        'company_name',
        'company_address',
        'company_gstn',
        'company_phone',
        'company_email',
        'quotation_no',
        'quotation_date',
        'rfq_no',
        'rfq_date',
        'part_no',
        'project_material_no',
        'drawing_no',
        'drawing_rev',
        'description',
        'bill_address',
        'ship_address',
        'product_type',
        'inr_in_words',
        'subtotal',
        'sgst_amount',
        'cgst_amount',
        'igst_amount',
        'round_up',
        'grand_total',
        'status',
        'customer_so_path',
        'approved_by',
        'approved_at',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'sales_order_date' => 'date',
        'quotation_date' => 'date',
        'rfq_date' => 'date',
        'subtotal' => 'decimal:2',
        'sgst_amount' => 'decimal:2',
        'cgst_amount' => 'decimal:2',
        'igst_amount' => 'decimal:2',
        'round_up' => 'decimal:2',
        'grand_total' => 'decimal:2',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    // ──────────────────────────────────────────────────────────────────────────
    // RELATIONSHIPS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Order items
     */
    public function items()
    {
        return $this->hasMany(SalesOrderItem::class, 'sales_order_id');
    }

    /**
     * Customer relationship
     */
    public function customer()
    {
        return $this->belongsTo(CustomerVendor::class, 'company_name', 'id');
    }

    /**
     * Related quotation
     */
    public function quotation()
    {
        return $this->belongsTo(Quotation::class, 'quotation_no', 'quotation_no');
    }

    /**
     * Route card for this order
     */
    public function routeCard()
    {
        return $this->hasOne(RouteCard::class, 'order_no', 'sales_order_no');
    }

    /**
     * Invoices generated from this order
     */
    public function invoices()
    {
        return $this->hasMany(TaxInvoice::class, 'buyer_order_no', 'sales_order_no');
    }

    // ──────────────────────────────────────────────────────────────────────────
    // SCOPES
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Filter confirmed orders
     */
    public function scopeConfirmed(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_CONFIRMED);
    }

    /**
     * Filter orders in production
     */
    public function scopeInProduction(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_IN_PRODUCTION);
    }

    /**
     * Filter completed orders
     */
    public function scopeCompleted(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_COMPLETED);
    }

    /**
     * Filter orders with route cards
     */
    public function scopeWithRouteCard(Builder $query): Builder
    {
        return $query->whereHas('routeCard');
    }

    /**
     * Filter orders without route cards
     */
    public function scopeWithoutRouteCard(Builder $query): Builder
    {
        return $query->whereDoesntHave('routeCard');
    }

    /**
     * Search by order number or customer
     */
    public function scopeSearchOrder(Builder $query, string $term): Builder
    {
        return $query->where(function ($q) use ($term) {
            $q->where('sales_order_no', 'LIKE', "%{$term}%")
              ->orWhere('customer_ref_no', 'LIKE', "%{$term}%")
              ->orWhereHas('customer', function ($cq) use ($term) {
                  $cq->where('company', 'LIKE', "%{$term}%");
              });
        });
    }

    // ──────────────────────────────────────────────────────────────────────────
    // ACCESSORS & HELPERS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Get all valid statuses
     */
    public static function getStatuses(): array
    {
        return [
            self::STATUS_PENDING,
            self::STATUS_CONFIRMED,
            self::STATUS_IN_PRODUCTION,
            self::STATUS_COMPLETED,
            self::STATUS_CANCELLED,
        ];
    }

    /**
     * Check if order has route card
     */
    public function hasRouteCard(): bool
    {
        return $this->routeCard()->exists();
    }

    /**
     * Check if order can be modified
     */
    public function canModify(): bool
    {
        return in_array($this->status, [self::STATUS_PENDING, self::STATUS_CONFIRMED]);
    }

    /**
     * Get production status from route card
     */
    public function getProductionStatus(): ?string
    {
        return $this->routeCard?->status;
    }

    /**
     * Calculate tax total
     */
    public function getTaxTotal(): float
    {
        return ($this->sgst_amount ?? 0) + ($this->cgst_amount ?? 0) + ($this->igst_amount ?? 0);
    }
}
