<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Schema;

class Reservation extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'brand_id',
        'user_id',
        'tour_id',
        'tour_date_id',
        'reservation_code',
        'easy_code',
        'status',
        'total_price',
        'paid_amount',
        'remaining_amount',
        'discount_amount',
        'flight_preference',
        'flight_type',
        'airline',
        'custom_flight_notes',
        'payment_type',
        'cancellation_policy',
        'contact_info',
        // 'merchandise' - handled separately if column exists
        'coupon_id',
        'gift_card_id',
        'notes',
        'admin_notes',
        'approved_by',
        'approved_at',
        'channel',
    ];

    protected $casts = [
        'total_price' => 'decimal:2',
        'paid_amount' => 'decimal:2',
        'remaining_amount' => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'contact_info' => 'array',
        // 'merchandise' => 'array', // Only cast if column exists
        'approved_at' => 'datetime',
    ];
    
    // Accessor for merchandise - handles missing column gracefully
    public function getMerchandiseAttribute($value)
    {
        if (!\Illuminate\Support\Facades\Schema::hasColumn('reservations', 'merchandise')) {
            return null;
        }
        if ($value === null) {
            return null;
        }
        return is_string($value) ? json_decode($value, true) : $value;
    }

    public function brand()
    {
        return $this->belongsTo(Brand::class);
    }

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

    public function tour()
    {
        return $this->belongsTo(Tour::class);
    }

    public function tourDate()
    {
        return $this->belongsTo(TourDate::class);
    }

    public function guests()
    {
        return $this->hasMany(Guest::class);
    }

    public function rooms()
    {
        return $this->hasMany(Room::class);
    }

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

    public function paymentLinks()
    {
        return $this->hasMany(PaymentLink::class);
    }

    public function documents()
    {
        return $this->hasMany(Document::class);
    }

    public function coupon()
    {
        return $this->belongsTo(Coupon::class);
    }

    public function giftCard()
    {
        return $this->belongsTo(GiftCard::class);
    }

    public function approvedBy()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function survey()
    {
        return $this->hasOne(Survey::class);
    }

    public function messages()
    {
        return $this->hasMany(Message::class);
    }

    public function invoice()
    {
        return $this->hasOne(Invoice::class);
    }

    /**
     * Generate a unified reservation code based on brand
     */
    public static function generateUnifiedCode(?int $brandId): string
    {
        $prefix = 'AVG';
        if ($brandId) {
            $brand = Brand::find($brandId);
            if ($brand) {
                $prefix = $brand->getReservationPrefix();
            }
        }
        
        // Sequential Number Logic: Find last code with this prefix and 5 digits
        // Old random codes were 6 digits (length: prefix + 1 + 6)
        // New sequential codes are 5 digits (length: prefix + 1 + 5)
        $expectedLength = strlen($prefix) + 6; // prefix + '-' + 5 digits

        $lastReservation = self::where('reservation_code', 'like', "$prefix-%")
            ->whereRaw('LENGTH(reservation_code) = ?', [$expectedLength])
            ->orderBy('id', 'desc')
            ->first();

        if ($lastReservation) {
            $parts = explode('-', $lastReservation->reservation_code);
            $lastNumber = (int) end($parts);
            $nextNumber = $lastNumber + 1;
        } else {
            $nextNumber = 1;
        }

        return $prefix . '-' . str_pad($nextNumber, 5, '0', STR_PAD_LEFT);
    }
}
