<?php

namespace App\Models;

use App\Settings\GeneralSettings;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Str;

class Order extends Model
{
    protected $fillable = [
        'order_number',
        'client_id',
        'service_id',
        'technician_id',
        'type',
        'status',
        'scheduled_date',
        'completed_date',
        'price',
        'fee',
        'technician_commission',
        'discount',
        'total',
        'address',
        'city',
        'notes',
        'client_notes',
    ];

    protected function casts(): array
    {
        return [
            'scheduled_date' => 'datetime',
            'completed_date' => 'datetime',
            'price' => 'decimal:2',
            'fee' => 'decimal:2',
            'technician_commission' => 'decimal:2',
            'discount' => 'decimal:2',
            'total' => 'decimal:2',
        ];
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($order) {
            if (empty($order->order_number)) {
                $order->order_number = static::generateOrderNumber();
            }
        });
    }

    /**
     * Generate order number based on settings format
     */
    public static function generateOrderNumber(): string
    {
        try {
            $settings = app(GeneralSettings::class);
            $format = $settings->order_number_format ?? 'ORD-{RANDOM:8}';
        } catch (\Exception $e) {
            $format = 'ORD-{RANDOM:8}';
        }

        return static::formatOrderNumber($format);
    }

    /**
     * Format order number based on template
     * 
     * Supported variables:
     * {YEAR} - Current year (4 digits)
     * {MONTH} - Current month (2 digits)
     * {DAY} - Current day (2 digits)
     * {RANDOM:N} - Random numbers (N = number of digits)
     * {SEQUENCE} - Sequential number (based on total orders count)
     */
    protected static function formatOrderNumber(string $format): string
    {
        $now = now();
        
        // Replace date variables
        $format = str_replace('{YEAR}', $now->format('Y'), $format);
        $format = str_replace('{MONTH}', $now->format('m'), $format);
        $format = str_replace('{DAY}', $now->format('d'), $format);
        
        // Replace random variables {RANDOM:N} - generates random numbers only
        $format = preg_replace_callback('/\{RANDOM:(\d+)\}/', function ($matches) {
            $length = (int) $matches[1];
            $randomNumber = '';
            for ($i = 0; $i < $length; $i++) {
                $randomNumber .= rand(0, 9);
            }
            return $randomNumber;
        }, $format);
        
        // Replace sequence number
        if (strpos($format, '{SEQUENCE}') !== false) {
            $sequence = static::getNextSequenceNumber();
            $format = str_replace('{SEQUENCE}', str_pad($sequence, 6, '0', STR_PAD_LEFT), $format);
        }
        
        return $format;
    }

    /**
     * Get next sequence number for orders
     */
    protected static function getNextSequenceNumber(): int
    {
        $lastOrder = static::orderBy('id', 'desc')->first();
        return $lastOrder ? $lastOrder->id + 1 : 1;
    }

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

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

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

    public function rating(): HasOne
    {
        return $this->hasOne(Rating::class);
    }

    public function getTypeLabelAttribute(): string
    {
        return match($this->type) {
            'urgent' => 'مستعجل',
            'normal' => 'عادي',
            default => $this->type,
        };
    }

    public function getStatusLabelAttribute(): string
    {
        return match($this->status) {
            'pending' => 'قيد الانتظار',
            'confirmed' => 'مؤكد',
            'in_progress' => 'قيد التنفيذ',
            'completed' => 'مكتمل',
            'cancelled' => 'ملغي',
            default => $this->status,
        };
    }

    public function getStatusColorAttribute(): string
    {
        return match($this->status) {
            'pending' => 'warning',
            'confirmed' => 'info',
            'in_progress' => 'primary',
            'completed' => 'success',
            'cancelled' => 'danger',
            default => 'gray',
        };
    }

    public function isUrgent(): bool
    {
        return $this->type === 'urgent';
    }

    public function isCompleted(): bool
    {
        return $this->status === 'completed';
    }

    public function canBeRated(): bool
    {
        return $this->isCompleted() && !$this->rating;
    }
}
