<?php

namespace App\Notifications;

use Illuminate\Notifications\AnonymousNotifiable;

class WahitsChannel
{
    /**
     * Send the given notification.
     */
    public function send(object $notifiable, WaNotification $notification): void
    {


        $phone = $notifiable instanceof AnonymousNotifiable
        ? $notifiable->routeNotificationFor('wa')
        : $notifiable->phone;

        $phones = explode("/", $phone);

        foreach($phones as $phone){

            $phone = trim($phone);
            $phone = substr($phone,0,1) == "0" ? "62".substr($phone,1,strlen($phone)):$phone;
            $phone = preg_replace("/[^0-9]/", "",$phone);

            $payload = $notification->toWa($notifiable);
            $message = $payload["text"];
            $image = @$payload["image"];
            $link = @$payload["link"];

            $token = config("wahits.token");

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://wa.wahits.com/api/send_message',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => "token=$token&number=$phone&message=$message&link=$link",
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/x-www-form-urlencoded'
                ),
            ));
            $response = curl_exec($curl);
\Log::info($response);
            curl_close($curl);
        }
    }
}
