<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use GuzzleHttp\Client;

class SendRechargePrepaidSmsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $profile;
    protected $prepaidSummary;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($profile, $prepaidSummary)
    {
        $this->profile = $profile;
        $this->prepaidSummary = $prepaidSummary;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $sms = $this->buildSms();
        $to = $this->recoverPhoneNumber();
        if ($to){
            $client = new Client();
            $apiKey = config('sms.api_key');
            $res = $client->request('POST', 'https://api.httpsms.com/v1/messages/send', [
                'headers' => [
                    'x-api-key' => $apiKey,
                ],
                'json'    => [
                    'content' => $sms,
                    'from'    => config('sms.from_number'),
                    'to'      => $to
                ]
            ]);
            $response = $res->getBody();
            \Log::channel('sms')->info($response);
        } else {
            \Log::channel('sms')->info("No tiene numero de telefono");
        }
    }

    private function recoverPhoneNumber()
    {
        if ($this->profile->phone) {
            $to = $this->profile->phone;
            if (substr($to, 0, 1) == '0') {
                $to = substr($to, 1);
            }
            return "+58" . $to;
        } else {
            return null;
        }
    }

    private function buildSms()
    {
        $card = $this->prepaidSummary->prepaidCard;
        $ammount = $this->prepaidSummary->amount;
        $ref = substr($this->prepaidSummary->code, -8);
        $sms = "Peaje El Cardenalito informa, hemos registrado una recarga en tu carnet " . $card->code . " por un monto de ". $ammount ."Bs. Ref: ". $ref ;
        return $sms;
    }
}
