<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class DirectBookingRequest extends Model
{
    use HasFactory;

    protected $primaryKey = 'booking_request_id';

    protected $fillable = [
        'parent_id',
        'babysitter_id',
        'booking_type_id',
        'occupation_category_id',
        'start_date',
        'end_date',
        'expected_hours_per_week',
        'hourly_rate',
        'requested_currency',
        'exchange_rate',
        'total_expected_amount',
        'care_type',
        'number_of_recipients',
        'recipient_names',
        'recipient_ages',
        'gender_preference',
        'health_mobility_details',
        'special_instructions_allergies',
        'request_status',
        'payment_status', // ✅ NEW FIELD ADDED
        'expires_at',
        'babysitter_viewed_at',
        'babysitter_responded_at'
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'hourly_rate' => 'decimal:2',
        'total_expected_amount' => 'decimal:2',
        'exchange_rate' => 'decimal:6',
        'expires_at' => 'datetime',
        'parent_submitted_at' => 'datetime',
        'babysitter_viewed_at' => 'datetime',
        'babysitter_responded_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    // Relationships
    public function parent()
    {
        return $this->belongsTo(User::class, 'parent_id', 'user_id');
    }

    public function babysitter()
    {
        return $this->belongsTo(User::class, 'babysitter_id', 'user_id')
                    ->with('babysitterProfile');
    }

    public function bookingType()
    {
        return $this->belongsTo(BookingType::class, 'booking_type_id', 'type_id');
    }

    public function occupationCategory()
    {
        return $this->belongsTo(OccupationCategory::class, 'occupation_category_id', 'category_id');
    }

    // Scopes
    public function scopePending($query)
    {
        return $query->where('request_status', 'pending');
    }

    public function scopeActive($query)
    {
        return $query->whereIn('request_status', ['pending', 'accepted']);
    }

    public function scopeByParent($query, $parentId)
    {
        return $query->where('parent_id', $parentId);
    }

    public function scopeByBabysitter($query, $babysitterId)
    {
        return $query->where('babysitter_id', $babysitterId);
    }

    public function scopeExpired($query)
    {
        return $query->where('expires_at', '<', now())
                    ->where('request_status', 'pending');
    }

    public function scopeAboutToExpire($query, $hours = 24)
    {
        return $query->where('expires_at', '<', now()->addHours($hours))
                    ->where('expires_at', '>', now())
                    ->where('request_status', 'pending');
    }

    public function scopeStartDatePassed($query)
    {
        return $query->where('start_date', '<', now()->toDateString())
                    ->whereIn('request_status', ['pending', 'accepted']);
    }

    // ✅ NEW: Payment Status Scopes
    public function scopePaymentStatus($query, $status)
    {
        return $query->where('payment_status', $status);
    }

    public function scopePaymentPending($query)
    {
        return $query->where('payment_status', 'pending');
    }

    public function scopePaymentSuccessful($query)
    {
        return $query->where('payment_status', 'success');
    }

    public function scopePaymentFailed($query)
    {
        return $query->where('payment_status', 'failed');
    }

    public function scopePaymentCompleted($query)
    {
        return $query->where('payment_status', 'success');
    }

    // ✅ NEW: Combined Scopes
    public function scopePendingWithSuccessfulPayment($query)
    {
        return $query->where('request_status', 'pending')
                    ->where('payment_status', 'success');
    }

    public function scopeAcceptedWithFailedPayment($query)
    {
        return $query->where('request_status', 'accepted')
                    ->where('payment_status', 'failed');
    }

    // Methods
    public function markAsViewed()
    {
        $this->update(['babysitter_viewed_at' => now()]);
    }

    public function markAsResponded()
    {
        $this->update(['babysitter_responded_at' => now()]);
    }

    public function accept()
    {
        $this->update(['request_status' => 'accepted']);
        $this->markAsResponded();
    }

    public function reject()
    {
        $this->update(['request_status' => 'rejected']);
        $this->markAsResponded();
    }

    public function cancel()
    {
        $this->update(['request_status' => 'cancelled']);
    }

    public function expire()
    {
        $this->update(['request_status' => 'expired']);
    }

    // ✅ NEW: Payment Status Methods
    public function markPaymentAsSuccess()
    {
        $this->update(['payment_status' => 'success']);

        \Illuminate\Support\Facades\Log::info('✅ DIRECT BOOKING PAYMENT - Marked as success:', [
            'booking_request_id' => $this->booking_request_id,
            'parent_id' => $this->parent_id,
            'babysitter_id' => $this->babysitter_id
        ]);
    }

    public function markPaymentAsFailed()
    {
        $this->update(['payment_status' => 'failed']);

        \Illuminate\Support\Facades\Log::info('❌ DIRECT BOOKING PAYMENT - Marked as failed:', [
            'booking_request_id' => $this->booking_request_id,
            'parent_id' => $this->parent_id,
            'babysitter_id' => $this->babysitter_id
        ]);
    }

    public function markPaymentAsPending()
    {
        $this->update(['payment_status' => 'pending']);

        \Illuminate\Support\Facades\Log::info('⏳ DIRECT BOOKING PAYMENT - Marked as pending:', [
            'booking_request_id' => $this->booking_request_id,
            'parent_id' => $this->parent_id,
            'babysitter_id' => $this->babysitter_id
        ]);
    }

    // Check payment status methods
    public function isPaymentSuccessful(): bool
    {
        return $this->payment_status === 'success';
    }

    public function isPaymentPending(): bool
    {
        return $this->payment_status === 'pending' || $this->payment_status === null;
    }

    public function isPaymentFailed(): bool
    {
        return $this->payment_status === 'failed';
    }

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

    public function canProcessPayment(): bool
    {
        return $this->request_status === 'accepted' &&
               $this->isPaymentPending();
    }

    public function isPaymentProcessable(): bool
    {
        return in_array($this->request_status, ['pending', 'accepted']) &&
               $this->isPaymentPending();
    }

    // Status Check Methods
    public function isExpired()
    {
        return $this->expires_at && $this->expires_at->lt(now());
    }

    public function isAboutToExpire($hours = 24)
    {
        return $this->expires_at &&
               $this->expires_at->gt(now()) &&
               $this->expires_at->lt(now()->addHours($hours));
    }

    public function hasStartDatePassed()
    {
        return $this->start_date && $this->start_date->lt(now()->toDateString());
    }

    public function calculateTotalAmount()
{
    // Simply multiply hourly rate by expected hours per week
    return $this->hourly_rate * $this->expected_hours_per_week;
}

    public function getRemainingHours()
    {
        if (!$this->expires_at) return 0;

        $remaining = now()->diffInHours($this->expires_at, false);
        return max(0, $remaining);
    }

    public function shouldAutoExpire()
    {
        return $this->request_status === 'pending' &&
               ($this->isExpired() || $this->hasStartDatePassed());
    }

    // ✅ NEW: Payment related methods
    public function getPaymentStatusText(): string
    {
        $statusMap = [
            'pending' => 'Payment Pending',
            'success' => 'Payment Successful',
            'failed' => 'Payment Failed'
        ];

        return $statusMap[$this->payment_status] ?? 'Payment Status Unknown';
    }

    public function getPaymentStatusColor(): string
    {
        $colorMap = [
            'pending' => 'warning',
            'success' => 'success',
            'failed' => 'danger'
        ];

        return $colorMap[$this->payment_status] ?? 'secondary';
    }

    public function canRetryPayment(): bool
    {
        return $this->isPaymentFailed() &&
               $this->request_status === 'accepted' &&
               !$this->isExpired();
    }

    public function getPaymentEligibility(): array
    {
        return [
            'can_process_payment' => $this->canProcessPayment(),
            'is_payment_successful' => $this->isPaymentSuccessful(),
            'is_payment_pending' => $this->isPaymentPending(),
            'is_payment_failed' => $this->isPaymentFailed(),
            'can_retry_payment' => $this->canRetryPayment(),
            'request_status' => $this->request_status,
            'payment_status' => $this->payment_status,
            'is_expired' => $this->isExpired(),
            'has_start_date_passed' => $this->hasStartDatePassed(),
            'is_about_to_expire' => $this->isAboutToExpire()
        ];
    }

    // ✅ NEW: Get payment summary
    public function getPaymentSummary(): array
    {
        return [
            'booking_request_id' => $this->booking_request_id,
            'total_expected_amount' => $this->total_expected_amount,
            'hourly_rate' => $this->hourly_rate,
            'expected_hours_per_week' => $this->expected_hours_per_week,
            'duration_weeks' => $this->end_date
                ? ceil($this->start_date->diffInDays($this->end_date) / 7)
                : 4,
            'payment_status' => $this->payment_status,
            'payment_status_text' => $this->getPaymentStatusText(),
            'payment_status_color' => $this->getPaymentStatusColor(),
            'can_process_payment' => $this->canProcessPayment(),
            'is_payment_required' => $this->request_status === 'accepted' && $this->isPaymentPending()
        ];
    }

    // Custom Accessor for formatted response
    public function getFormattedBabysitterAttribute()
    {
        if (!$this->babysitter) {
            return null;
        }

        return [
            'babysitter_id' => $this->babysitter->user_id,
            'user_id' => $this->babysitter->user_id,
            'email' => $this->babysitter->email,
            'first_name' => $this->babysitter->first_name,
            'last_name' => $this->babysitter->last_name,
            'phone_number' => $this->babysitter->phone_number,
            'profile_picture_url' => $this->babysitter->profile_picture_url,
            'date_of_birth' => $this->babysitter->date_of_birth,
            'gender' => $this->babysitter->gender,
            'bio' => $this->babysitter->bio,
            'babysitter_profile' => $this->babysitter->babysitterProfile
        ];
    }

    // ✅ NEW: Boot method for default payment status
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->payment_status)) {
                $model->payment_status = 'pending';
            }
        });
    }

    // ✅ NEW: Get all payment status options
    public static function getPaymentStatusOptions(): array
    {
        return [
            'pending' => 'Pending',
            'success' => 'Success',
            'failed' => 'Failed'
        ];
    }

    // ✅ NEW: Get payment statistics for a user
    public static function getUserPaymentStatistics($userId, $userType = 'parent'): array
    {
        $query = self::query();

        if ($userType === 'parent') {
            $query->where('parent_id', $userId);
        } elseif ($userType === 'babysitter') {
            $query->where('babysitter_id', $userId);
        }

        $total = $query->count();
        $pending = $query->clone()->where('payment_status', 'pending')->count();
        $success = $query->clone()->where('payment_status', 'success')->count();
        $failed = $query->clone()->where('payment_status', 'failed')->count();

        return [
            'total' => $total,
            'pending' => $pending,
            'success' => $success,
            'failed' => $failed,
            'success_rate' => $total > 0 ? round(($success / $total) * 100, 2) : 0,
            'pending_rate' => $total > 0 ? round(($pending / $total) * 100, 2) : 0,
            'failed_rate' => $total > 0 ? round(($failed / $total) * 100, 2) : 0
        ];
    }
}
