<?php

namespace App\Jobs;

use App\Models\Whatsapp;
use App\Models\Examination;
use Illuminate\Bus\Queueable;
use App\Models\WhatsAppTemplate;
use App\Services\WhatsAppService;
use Illuminate\Support\Facades\Log;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class SendWhatsappMessageForOperations implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $examination;
    protected $status;

    public function __construct(Examination $examination, $status)
    {
        $this->examination = $examination;
        $this->status = $status;
    }

    public function handle()
    {
        // Set the template code based on the new status
        $template_code = $this->status === 'تم التجهيز'
            ? 'examination_pending_delivery'
            : 'examination_cancelled';

        // Check for WhatsApp configuration
        $whatsapp = Whatsapp::first();
        $template = WhatsAppTemplate::where('code', $template_code)->first();

        if ($whatsapp && $whatsapp->active == 1 && $template && $template->active == 1) {
            try {
                $response = app(WhatsAppService::class)->sendTemplateMessage(
                    $template_code,
                     $this->examination->client->phone,
                    [
                        'examination_number' => $this->examination->code,
                        'name' => $this->examination->client->first_name.' '.$this->examination->client->last_name ,
                        'date' => now(),
                        'type' => $this->examination->type,
                    ]
                );

                // Check the response from WhatsApp
                if (isset($response['message_status']) && $response['message_status'] === 'Success') {
                    Log::info("Message sent successfully to: " . $this->examination->client->phone);
                } else {
                    Log::error('Failed to send WhatsApp message to: ' . $this->examination->client->phone);
                }
            } catch (\Exception $e) {
                Log::error('Error while sending WhatsApp message: ' . $e->getMessage());
            }
        }
    }
}
