<?php

namespace App\Modules\Bookings\events;

use App\Modules\Bookings\Task;
use App\Modules\Bookings\Comment;
use App\Modules\Bookings\CustomerNotification;
use App\Services\SmsManager;
use App\Models\Setting;
use Illuminate\Support\Facades\Log;

class TaskCompletionObserver
{
    /**
     * Handle the Task "updated" event.
     *
     * @param  \App\Modules\Bookings\Task  $task
     * @return void
     */
    public function updated(Task $task)
    {
        // Check if task was just marked as completed
        if ($task->isDirty('completed') && $task->completed == 1) {
            $this->handleTaskCompletion($task);
        }
    }

    /**
     * Handle task completion and send SMS notification.
     *
     * @param  \App\Modules\Bookings\Task  $task
     * @return void
     */
    protected function handleTaskCompletion(Task $task)
    {
        try {
            // Check if SMS notifications are enabled
            if (!$this->isSmsEnabled()) {
                Log::info('SMS notifications disabled - skipping task completion SMS', ['task_id' => $task->id]);
                return;
            }

            // Get customer phone number
            $phoneNumber = $this->getCustomerPhoneNumber($task);
            if (!$phoneNumber) {
                Log::info('No phone number found for task completion SMS', ['task_id' => $task->id]);
                return;
            }

            // Create SMS message
            $message = $this->createCompletionMessage($task);

            // Send SMS
            $this->sendCompletionSMS($task, $phoneNumber, $message);

        } catch (\Exception $e) {
            Log::error('Failed to send task completion SMS', [
                'task_id' => $task->id,
                'error' => $e->getMessage()
            ]);
        }
    }

    /**
     * Check if automatic SMS notifications are enabled in settings.
     *
     * @return bool
     */
    protected function isSmsEnabled()
    {
        $autoSmsEnabled = Setting::get('notifications.sms_enabled', false);
        $providerEnabled = Setting::get('integrations.twilio.enabled', false) ||
                          Setting::get('integrations.textmagic.enabled', false) ||
                          Setting::get('integrations.sms_gateway.enabled', false);

        return $autoSmsEnabled && $providerEnabled;
    }

    /**
     * Get customer phone number from task.
     *
     * @param  \App\Modules\Bookings\Task  $task
     * @return string|null
     */
    protected function getCustomerPhoneNumber(Task $task)
    {
        // Load the client relationship if not already loaded
        if (!$task->relationLoaded('client')) {
            $task->load('client');
        }

        if (!$task->client) {
            return null;
        }

        // For customers, check mobile first, then phone
        if ($task->client_type === 'customer') {
            return $task->client->mobile ?: $task->client->phone;
        }

        // For business clients, check site users first
        if ($task->client_type === 'client') {
            // Load site user if available
            if (!$task->relationLoaded('site_user')) {
                $task->load('site_user');
            }

            if ($task->site_user) {
                return $task->site_user->mobile ?: $task->site_user->phone;
            }

            // Fall back to site primary phone
            if (!$task->relationLoaded('site')) {
                $task->load('site');
            }

            if ($task->site) {
                return $task->site->primary_phone;
            }
        }

        return null;
    }

    /**
     * Create completion message for SMS.
     *
     * @param  \App\Modules\Bookings\Task  $task
     * @return string
     */
    protected function createCompletionMessage(Task $task)
    {
        $companyName = Setting::get('company.name', 'Computer Assistance');
        
        $message = "Hello from {$companyName}! ";
        $message .= "Your service request #{$task->id}";
        
        if ($task->title) {
            $message .= " ({$task->title})";
        }
        
        $message .= " has been completed. ";
        
        // Add custom completion message if configured
        $customMessage = Setting::get('notifications.sms_completion_message', '');
        if ($customMessage) {
            $message .= $customMessage . " ";
        }
        
        $message .= "Thank you for choosing {$companyName}!";
        
        return $message;
    }

    /**
     * Send SMS notification for task completion.
     *
     * @param  \App\Modules\Bookings\Task  $task
     * @param  string  $phoneNumber
     * @param  string  $message
     * @return void
     */
    protected function sendCompletionSMS(Task $task, $phoneNumber, $message)
    {
        try {
            $smsManager = new SmsManager();

            // Check if SMS manager is available
            if (!$smsManager->isAvailable()) {
                Log::info('SMS notifications disabled - no provider enabled', [
                    'task_id' => $task->id
                ]);
                return;
            }

            $result = $smsManager->sendCompletionSMS($task->id, $phoneNumber, $message);

            if ($result['success']) {
                $provider = ucfirst($result['provider'] ?? 'SMS');

                Log::info('Task completion SMS sent successfully', [
                    'task_id' => $task->id,
                    'phone_number' => $phoneNumber,
                    'provider' => $result['provider'] ?? 'unknown',
                    'message_sid' => $result['message_sid'] ?? null,
                    'notification_id' => $result['notification_id'] ?? null
                ]);

                // Add a public comment to task history
                Comment::create([
                    'related_id' => $task->id,
                    'related_type' => 'task',
                    'type' => 'task',
                    'message' => "📱 SMS sent to customer via {$provider}\n\nPhone: {$phoneNumber}\n\nMessage:\n{$message}",
                    'public' => 1,
                    'created_by' => 0, // System user
                    'style' => 'info'
                ]);
            } else {
                throw new \Exception('SMS sending failed: ' . ($result['error'] ?? 'Unknown error'));
            }
        } catch (\Exception $e) {
            Log::error('Failed to send task completion SMS', [
                'task_id' => $task->id,
                'phone_number' => $phoneNumber,
                'error' => $e->getMessage()
            ]);

            // Don't re-throw - we don't want SMS failures to break task completion
            // Just log it and continue
        }
    }
} 