<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use GuzzleHttp\Client;
use App\Models\Visitor;
use App\Models\Template;
use App\Models\WhatsappLog;
use Illuminate\Foundation\Bus\Dispatchable;

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

    protected $visitorId;
    protected $templateId;
    protected $whatsappConfig;
    protected $fkwhatsappCountId;

    /**
     * Create a new job instance.
     *
     * @param int $visitorId
     * @param int $templateId
     * @param object $whatsappConfig
     */
    public function __construct($visitorId, $templateId, $whatsappConfig,$fkwhatsappCountId = null)
    {
        $this->onConnection('database');  
        $this->visitorId = $visitorId;
        $this->templateId = $templateId;
        $this->whatsappConfig = $whatsappConfig;
        $this->fkwhatsappCountId = $fkwhatsappCountId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $visitor = Visitor::find($this->visitorId);
        if (!$visitor || empty($visitor->mobile_no)) {
            return; // Skip if the visitor doesn't exist or has no mobile number
        }

        $template = Template::find($this->templateId);
        if (!$template) {
            return; // Skip if the template doesn't exist
        }

        $messageData = $this->prepareMessageData($template);
        $messageData['to'] = $visitor->mobile_no;

        $client = new Client();
        try {
            $response = $client->post('https://graph.facebook.com/v21.0/' . $this->whatsappConfig->phone_id . '/messages', [
                'json' => $messageData,
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $this->whatsappConfig->token,
                ],
            ]);

            $data = json_decode($response->getBody(), true);

            // Log the message
            $this->logWhatsappMessage($visitor, $this->templateId, $data,$this->fkwhatsappCountId);

        } catch (\Exception $e) {
            // Log the error
            \Log::error('Error sending WhatsApp message: ' . $e->getMessage());
        }
    }

 

    /**
     * Log the WhatsApp message (customize this as needed).
     *
     * @param Visitor $visitor
     * @param int $templateId
     * @param array $response
     */
   private function logWhatsappMessage($visitor, $request , $data,$fkwhatsappCountId = null)
    {

      // Check if the 'messages' key exists and has a valid value
        if (isset($data['messages']) && !empty($data['messages'][0])) {
            // Extract the necessary information
            $messageId = $data['messages'][0]['id'];
            $messageStatus = $data['messages'][0]['message_status'];

            // Get the wa_id from the contacts array
            $wa_id = $data['contacts'][0]['wa_id'] ?? null;
        
            // Prepare data for logging
            $requestData = [
                'user_id' => auth()->id(),
                'visitor_id' => $visitor->id,
                'template_id' => $request,
                'mobile' => $wa_id ?? $visitor->mobile_no,
                'wamid' => $messageId,
                'status' => $messageStatus,
                'fk_whatsapp_batch_id'=>$fkwhatsappCountId
            ];
        
            // Save to WhatsappLog only if the conditions are met
            WhatsappLog::create($requestData);
        }
    }


     private function prepareMessageData($template)
    {       
        if ($template->file_type) {
            if ($template->file_type == 'image') {
                return [
                    "messaging_product" => "whatsapp",
                    "type" => "template",
                    "template" => [
                        "name" => $template->name,
                        "language" => ["code" => "en"],
                        "components" => [
                            [
                                "type" => "header",
                                "parameters" => [
                                    ["type" => "image", "image" => ["id" => $template->whatsapp_file_id]]
                                ]
                            ]
                        ]
                    ]
                ];
            } else {
                return [
                    "messaging_product" => "whatsapp",
                    "type" => "template",
                    "template" => [
                        "name" => $template->name,
                        "language" => ["code" => "en"],
                        "components" => [
                            [
                                "type" => "header",
                                "parameters" => [
                                    ["type" => "DOCUMENT", "document" => ["id" => $template->whatsapp_file_id]]
                                ]
                            ]
                        ]
                    ]
                ];
            }
        } else {
            return [
                "messaging_product" => "whatsapp",
                "type" => "template",
                "template" => [
                    "name" => $template->name,
                    "language" => ["code" => "en"]
                ]
            ];
        }
    }

}
