<?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 SendWhatsappMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $examination;

    /**
     * Create a new job instance.
     *
     * @param Examination $examination
     */
    public function __construct(Examination $examination)
    {
        $this->examination = $examination;
    }

    /**
     * Execute the job.
     */
    public function handle(WhatsAppService $whatsAppService)
    {
        // Determine the template code based on the examination status
        $template_code = $this->getTemplateCode($this->examination->status);

        // Fetch WhatsApp settings and the template
        $whatsapp = Whatsapp::first();
        $template = WhatsAppTemplate::where('code', $template_code)->first();

        // Ensure WhatsApp and template are active
        if ($whatsapp && $whatsapp->active && $template && $template->active) {
            try {
                // Prepare placeholders for the message template
                $placeholders = [
                    'examination_number' => $this->examination->code,
                    'name' => $this->examination->client->first_name.' '.$this->examination->client->last_name ,
                    'date' => now()->format('Y-m-d H:i:s'),
                    'type' => $this->examination->type ?? 'الفحص',
                ];

                // Send the message using the WhatsApp service
                $response = $whatsAppService->sendTemplateMessage(
                    $template_code,
                    $this->examination->client->phone,
                    $placeholders
                );

                // Log warning if the message sending failed
                if (!isset($response['message_status']) || $response['message_status'] !== 'Success') {
                    Log::warning('WhatsApp message failed for examination ' . $this->examination->code);
                }
            } catch (\Exception $e) {
                // Log any exceptions
                Log::error('Error sending WhatsApp message: ' . $e->getMessage());
            }
        } else {
            // Log if WhatsApp or template is not active
            Log::warning('WhatsApp or template not active for examination ' . $this->examination->code);
        }
    }

    /**
     * Get the template code based on the examination status.
     *
     * @param string $status
     * @return string
     */
    private function getTemplateCode($status)
    {
        $templates = [
            'في انتظار التاكيد'=>'add_examination',
            'ارسال الي المشغل'=>'reception_confirmation',
            'تم الاستلام'=>'examination_delivered',
            'الغاء'=>'examination_cancelled',
        ];


        // return $templates[$status] ?? 'examination_update';
        return $templates[trim($status)] ?? 'examination_update';
    }
}
