<?php

namespace App\Jobs;

use App\Jobs\Job;
use App\Modules\Bookings\Task;
use App\Modules\Bookings\Comment;

use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Modules\Bookings\MobileToken;
use Illuminate\Support\Facades\Log;
use App\Services\SmsManager;
use App\Models\Setting;

class sendRepairUpdateToMobile extends Job implements ShouldQueue
{
	use InteractsWithQueue, SerializesModels;
	protected $repair;
	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct(Task $repair)
	{
		$this->repair = $repair;
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle()
	{
                $repair = $this->repair;
                $status = $repair->status;

                // Only send notifications for these specific status changes
                if ($status->name == 'Booked In' || $status->name == 'Work in progress' || $status->name == 'Quality Control' || $status->name == 'Work Completed') {

                    // Check if any SMS provider is enabled
                    $smsEnabled = Setting::get('integrations.twilio.enabled', false) ||
                                  Setting::get('integrations.textmagic.enabled', false);

                    if (!$smsEnabled) {
                        Log::info('SMS disabled in admin settings, skipping notification', [
                            'repair_id' => $repair->id,
                            'status' => $status->name
                        ]);
                        return;
                    }

                    try {
                        // Use SMS Manager to send via active provider
                        $smsManager = new SmsManager();

                        // Get the client phone number for SMS notifications
                        $phoneNumber = null;
                        if ($repair->client_type === 'customer' && $repair->client) {
                            $phoneNumber = $repair->client->phone_number;
                        } elseif ($repair->client_type === 'client' && $repair->client) {
                            $phoneNumber = $repair->client->phone_number;
                        }

                        if (!$phoneNumber) {
                            Log::info('No phone number available for SMS notification', [
                                'repair_id' => $repair->id,
                                'client_type' => $repair->client_type,
                                'client_id' => $repair->client_id
                            ]);
                            return;
                        }

                        // Create the SMS message
                        $message = "CA job status update: The status of your {$repair->title} repair has been changed to {$status->name}. Job ID: {$repair->id}, PIN: {$repair->pin}";

                        // Send SMS using SMS Manager (auto-selects active provider)
                        $result = $smsManager->sendTaskSMS($repair->id, $phoneNumber, $message);

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

                            Log::info('Mobile SMS notification sent successfully', [
                                'repair_id' => $repair->id,
                                'status' => $status->name,
                                'provider' => $result['provider'] ?? 'unknown',
                                'to_number' => $phoneNumber,
                                'message_sid' => $result['message_sid'] ?? null,
                                'notification_id' => $result['notification_id'] ?? null
                            ]);

                            // Add a public comment to task history
                            Comment::create([
                                'related_id' => $repair->id,
                                'related_type' => 'task',
                                'type' => 'task',
                                'message' => "📱 Status update SMS sent to customer via {$provider}\n\nPhone: {$phoneNumber}\n\nMessage:\n{$message}",
                                'public' => 1,
                                'created_by' => 0, // System user
                                'style' => 'info'
                            ]);
                        } else {
                            Log::error('Failed to send mobile SMS notification', [
                                'repair_id' => $repair->id,
                                'status' => $status->name,
                                'provider' => $result['provider'] ?? 'unknown',
                                'error' => $result['error'] ?? 'Unknown error',
                                'phone_number' => $phoneNumber
                            ]);
                        }

                    } catch (\Exception $e) {
                        Log::error('Exception in mobile SMS notification job', [
                            'repair_id' => $repair->id,
                            'status' => $status->name,
                            'error' => $e->getMessage(),
                            'trace' => $e->getTraceAsString()
                        ]);
                    }
                }
        }
        
        
}
