<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Order extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'branch_id',
        'user_id',
        'order_number',
        'is_temp_bill',
        'bill_number',
        'bill_type',
        'status',
        'order_type',
        'table_number',
        'customer_name',
        'customer_phone',
        'customer_address',
        'subtotal',
        'tax_amount',
        'discount_amount',
        'discount_reason',
        'total_amount',
        'payment_received',
        'change_amount',
        'remaining_amount',
        'notes',
        'completed_at',
        'cancelled_at',
        'cancellation_reason',
        'finalized_at',
        'locked_at',
        'converted_to_final_at',
        'original_temp_bill_id',
        'print_count',
    ];

    protected $casts = [
        'subtotal' => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'payment_received' => 'decimal:2',
        'change_amount' => 'decimal:2',
        'remaining_amount' => 'decimal:2',
        'is_temp_bill' => 'boolean',
        'print_count' => 'integer',
        'completed_at' => 'datetime',
        'cancelled_at' => 'datetime',
        'finalized_at' => 'datetime',
        'locked_at' => 'datetime',
        'converted_to_final_at' => 'datetime',
    ];

    public const STATUS_TEMP_BILL = 'temp_bill';
    public const STATUS_PENDING = 'pending';
    public const STATUS_PREPARING = 'preparing';
    public const STATUS_READY = 'ready';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_CANCELLED = 'cancelled';
    public const STATUS_AWAITING_PAYMENT = 'awaiting_payment';

    public const TYPE_DINE_IN = 'dine_in';
    public const TYPE_TAKEAWAY = 'takeaway';
    public const TYPE_DELIVERY = 'delivery';

    public const BILL_TYPE_TEMP = 'temp';
    public const BILL_TYPE_FINAL = 'final';

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function items(): HasMany
    {
        return $this->hasMany(OrderItem::class);
    }

    public function payments(): HasMany
    {
        return $this->hasMany(Payment::class);
    }

    public function statusHistory(): HasMany
    {
        return $this->hasMany(OrderStatusHistory::class);
    }

    public function modifications(): HasMany
    {
        return $this->hasMany(BillModification::class);
    }

    public function originalTempBill(): BelongsTo
    {
        return $this->belongsTo(Order::class, 'original_temp_bill_id');
    }

    public function scopeForBranch($query, int $branchId)
    {
        return $query->where('branch_id', $branchId);
    }

    public function scopeByStatus($query, string $status)
    {
        return $query->where('status', $status);
    }

    public function scopeActive($query)
    {
        return $query->whereNotIn('status', [self::STATUS_COMPLETED, self::STATUS_CANCELLED]);
    }

    public function scopeTempBills($query)
    {
        return $query->where('is_temp_bill', true)->where('status', self::STATUS_TEMP_BILL);
    }

    public function scopeFinalBills($query)
    {
        return $query->where('is_temp_bill', false)->orWhere(function ($q) {
            $q->where('is_temp_bill', true)->whereNotNull('finalized_at');
        });
    }

    public function scopeToday($query)
    {
        return $query->whereDate('created_at', today());
    }

    public function calculateTotals(): void
    {
        $subtotal = $this->items->sum('total_price');
        // Use existing tax_amount if already set (from POS), otherwise calculate 0
        $taxAmount = $this->tax_amount ?? 0;
        $discountAmount = $this->discount_amount ?? 0;
        $total = $subtotal + $taxAmount - $discountAmount;

        $this->update([
            'subtotal' => $subtotal,
            'tax_amount' => $taxAmount,
            'total_amount' => max(0, $total),
        ]);
    }

    public function getTotalPaid(): float
    {
        return $this->payments()
            ->where('status', 'completed')
            ->sum('amount');
    }

    public function getRemainingBalance(): float
    {
        return max(0, $this->total_amount - $this->getTotalPaid());
    }

    public function isFullyPaid(): bool
    {
        return $this->getRemainingBalance() <= 0;
    }

    public static function generateOrderNumber(int $branchId): string
    {
        $prefix = 'ORD-' . $branchId . '-' . date('Ymd');
        $lastOrder = static::where('order_number', 'like', $prefix . '%')
            ->orderBy('order_number', 'desc')
            ->first();

        if ($lastOrder) {
            $lastNumber = (int) substr($lastOrder->order_number, -4);
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }

        return $prefix . '-' . str_pad($newNumber, 4, '0', STR_PAD_LEFT);
    }

    public static function generateBillNumber(int $branchId): string
    {
        $prefix = 'BILL-' . $branchId . '-' . date('Ymd');
        $lastBill = static::where('bill_number', 'like', $prefix . '%')
            ->orderBy('bill_number', 'desc')
            ->first();

        if ($lastBill) {
            $lastNumber = (int) substr($lastBill->bill_number, -4);
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }

        return $prefix . '-' . str_pad($newNumber, 4, '0', STR_PAD_LEFT);
    }

    public function isTempBill(): bool
    {
        return $this->is_temp_bill && $this->status === self::STATUS_TEMP_BILL;
    }

    public function isFinalized(): bool
    {
        return $this->is_temp_bill && $this->finalized_at !== null;
    }

    public function incrementPrintCount(): void
    {
        $this->increment('print_count');
    }

    public function canBeEdited(): bool
    {
        return $this->isTempBill() && !$this->locked_at;
    }

    public function isLocked(): bool
    {
        return !is_null($this->locked_at);
    }

    public function calculateRemaining(): float
    {
        return max(0, (float)$this->total_amount - (float)$this->payment_received);
    }

    public function calculateChange(): float
    {
        return max(0, (float)$this->payment_received - (float)$this->total_amount);
    }

    public static function generateTempOrderNumber(int $branchId): string
    {
        $prefix = 'TEMP-' . $branchId . '-' . date('Ymd');
        $lastOrder = static::where('order_number', 'like', $prefix . '%')
            ->orderBy('order_number', 'desc')
            ->first();

        if ($lastOrder) {
            $lastNumber = (int) substr($lastOrder->order_number, -4);
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }

        return $prefix . '-' . str_pad($newNumber, 4, '0', STR_PAD_LEFT);
    }

    public function scopeAwaitingPayment($query)
    {
        return $query->where('status', self::STATUS_AWAITING_PAYMENT);
    }
}
