<?php

namespace App\Jobs;

use App\Jobs\Job;
use App\Modules\Bookings\MobileToken;
use App\Modules\Bookings\Repair;
use App\Modules\Bookings\Comment;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Log;
use App\Modules\Twilio\Services\TwilioService;
use App\Modules\Bookings\Task;
//use \Mail;

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

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle()
	{

                //Comment b a model
		$comment = $this->comment;

                //Get the task associated with the comment
                $task = $comment->related;

                // Get the repair associated with the comment
                $repair = Repair::find($comment->related_id);
                
                // Get the customer phone number from the repair
                $customerPhone = $repair->client->mobile ?? $repair->client->phone;
                
                if ($customerPhone) {
                    $twilioService = new TwilioService();
                    $message = "CA Comment: A comment has been added to your repair #{$repair->pin}: " . $comment->message;
                    
                    try {
                        $result = $twilioService->sendSMS($customerPhone, $message);
                        Log::info('SMS sent for repair comment', [
                            'repair_id' => $repair->id,
                            'phone' => $customerPhone,
                            'message' => $message
                        ]);
                    } catch (\Exception $e) {
                        Log::error('Failed to send SMS for repair comment', [
                            'repair_id' => $repair->id,
                            'phone' => $customerPhone,
                            'error' => $e->getMessage()
                        ]);
                    }
                } else {
                    Log::info('No phone number found for customer notification', [
                        'repair_id' => $repair->id,
                        'customer_id' => $repair->client->id ?? null
                    ]);
                }

	}
}
