<?php

namespace App\Models;

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

class HousekeepingTask extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'room_id',
        'booking_id',
        'task_type',
        'priority',
        'status',
        'description',
        'estimated_duration',
        'due_time',
        'started_at',
        'completed_at',
        'cancelled_at',
        'assigned_at',
        'assigned_to',
        'completed_by',
        'cancelled_by',
        'notes',
        'checklist',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    protected $casts = [
        'due_time' => 'datetime',
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
        'cancelled_at' => 'datetime',
        'assigned_at' => 'datetime',
        'checklist' => 'array',
    ];

    // Relationships
    public function room()
    {
        return $this->belongsTo(MsRooms::class, 'room_id');
    }

    public function booking()
    {
        return $this->belongsTo(Booking::class, 'booking_id');
    }

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

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

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

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

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

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

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

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

    public function scopeUrgent($query)
    {
        return $query->where('priority', 'urgent');
    }

    public function scopeOverdue($query)
    {
        return $query->where('due_time', '<', now())
                    ->where('status', '!=', 'completed');
    }

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

    // Accessors
    public function getStatusBadgeAttribute()
    {
        $badges = [
            'pending' => 'bg-warning',
            'in_progress' => 'bg-info',
            'completed' => 'bg-success',
            'cancelled' => 'bg-secondary'
        ];

        return $badges[$this->status] ?? 'bg-secondary';
    }

    public function getPriorityBadgeAttribute()
    {
        $badges = [
            'low' => 'bg-light text-dark',
            'normal' => 'bg-primary',
            'high' => 'bg-warning',
            'urgent' => 'bg-danger'
        ];

        return $badges[$this->priority] ?? 'bg-secondary';
    }

    public function getDurationFormattedAttribute()
    {
        if (!$this->estimated_duration) return '-';
        
        $hours = floor($this->estimated_duration / 60);
        $minutes = $this->estimated_duration % 60;
        
        if ($hours > 0) {
            return $hours . 'h ' . $minutes . 'm';
        }
        
        return $minutes . 'm';
    }

    public function getIsOverdueAttribute()
    {
        return $this->due_time && 
               $this->due_time->isPast() && 
               $this->status !== 'completed';
    }

    public function getTaskTypeDisplayAttribute()
    {
        $types = [
            'checkout_cleaning' => 'Pembersihan Checkout',
            'maintenance' => 'Maintenance',
            'deep_cleaning' => 'Deep Cleaning',
            'inspection' => 'Inspeksi'
        ];

        return $types[$this->task_type] ?? $this->task_type;
    }

    // NEW: Status update methods with room status integration
    public function startTask($userId = null)
    {
        $this->update([
            'status' => 'in_progress',
            'started_at' => now(),
            'updated_by' => $userId ?? auth()->id(),
        ]);

        // Update room status based on task type
        $this->updateRoomStatusOnStart();

        \Log::info("Housekeeping task {$this->id} started for room {$this->room->room_number}");
        
        return $this;
    }

    public function completeTask($userId = null, $notes = null)
    {
        $this->update([
            'status' => 'completed',
            'completed_at' => now(),
            'completed_by' => $userId ?? auth()->id(),
            'notes' => $notes ? $this->notes . "\n" . $notes : $this->notes,
            'updated_by' => $userId ?? auth()->id(),
        ]);

        // Update room status after completion
        $this->updateRoomStatusOnCompletion();

        \Log::info("Housekeeping task {$this->id} completed for room {$this->room->room_number}");
        
        return $this;
    }

    public function cancelTask($userId = null, $reason = null)
    {
        $this->update([
            'status' => 'cancelled',
            'cancelled_at' => now(),
            'cancelled_by' => $userId ?? auth()->id(),
            'cancellation_reason' => $reason,
            'updated_by' => $userId ?? auth()->id(),
        ]);

        // Update room status after cancellation
        $this->updateRoomStatusOnCancellation();

        \Log::info("Housekeeping task {$this->id} cancelled for room {$this->room->room_number}");
        
        return $this;
    }

    // NEW: Room status update methods
    protected function updateRoomStatusOnStart()
    {
        if (!$this->room) return;

        switch ($this->task_type) {
            case 'maintenance':
                $this->room->setMaintenance("Task {$this->id} started");
                break;
            
            case 'checkout_cleaning':
            case 'deep_cleaning':
            case 'inspection':
                $this->room->setCleaning("Task {$this->id} started");
                break;
        }
    }

    protected function updateRoomStatusOnCompletion()
    {
        if (!$this->room) return;

        // Check if there are other active tasks for this room
        $otherActiveTasks = HousekeepingTask::where('room_id', $this->room_id)
            ->where('id', '!=', $this->id)
            ->whereIn('status', ['pending', 'in_progress'])
            ->whereNull('deleted_at')
            ->exists();

        if (!$otherActiveTasks) {
            // No other active tasks - room can be available
            $this->room->autoSetAvailableIfPossible();
        } else {
            // Update status based on remaining tasks
            $this->room->updateStatusBasedOnHousekeeping();
        }
    }

    protected function updateRoomStatusOnCancellation()
    {
        if (!$this->room) return;

        // Update room status based on remaining active tasks
        $this->room->updateStatusBasedOnHousekeeping();
    }

    // Boot method to handle model events
    protected static function boot()
    {
        parent::boot();

        // When task status is updated
        static::updated(function ($task) {
            if ($task->wasChanged('status')) {
                \Log::info("Housekeeping task {$task->id} status changed to {$task->status}");
                
                // Update room status when task status changes
                if ($task->room) {
                    switch ($task->status) {
                        case 'in_progress':
                            $task->updateRoomStatusOnStart();
                            break;
                        case 'completed':
                            $task->updateRoomStatusOnCompletion();
                            break;
                        case 'cancelled':
                            $task->updateRoomStatusOnCancellation();
                            break;
                    }
                }
            }
        });

        // When task is created
        static::created(function ($task) {
            \Log::info("New housekeeping task {$task->id} created for room {$task->room->room_number}");
            
            // If task is created as in_progress, update room status
            if ($task->status === 'in_progress') {
                $task->updateRoomStatusOnStart();
            }
        });

        // When task is deleted
        static::deleted(function ($task) {
            \Log::info("Housekeeping task {$task->id} deleted for room {$task->room->room_number}");
            
            // Update room status after task deletion
            if ($task->room) {
                $task->room->updateStatusBasedOnHousekeeping();
            }
        });
    }

    // Helper method to get task color for UI
    public function getTaskColorAttribute()
    {
        $colors = [
            'checkout_cleaning' => 'primary',
            'maintenance' => 'warning',
            'deep_cleaning' => 'success',
            'inspection' => 'info'
        ];

        return $colors[$this->task_type] ?? 'secondary';
    }

    // Method to check if task affects room status
    public function affectsRoomStatus()
    {
        return in_array($this->task_type, ['checkout_cleaning', 'maintenance', 'deep_cleaning', 'inspection']);
    }
}