<?php

namespace App\Seraph\Services;

use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;
use Exception;
use Illuminate\Support\Facades\Mail;

class SMSSender
{
    /**
     * Http Client.
     */
    private $client;

    /**
     * Data to pass to the client.
     */
    private $data = [];

    /**
     * A reference to the Monolog.
     *
     * @var \Illuminate\Log\Writer
     */
    private $log;

    public function __construct(Log $log)
    {
        $this->log = $log;
        // Initialize SMS Gateway with database credentials instead of config
        $this->server = \App\Models\Setting::get('integrations.sms_gateway.server', '');
    }

    /**
     * Create a new task to ask to the client about the previous one.
     *
     * @param  App\Modules\Bookings\Task $task
     *
     * @return string | false
     */
    public function create($send_to, $message)
    {
        $this->setPhoneNumber($send_to);
        $this->setMessage($message);
        $this->client = new Client();
    }

    /**
     * Send a sms with the message contained in data, to the phonenumber contained in data.
     *
     * @return bool
     */
    public function send()
    {
        try {
    /*        Mail::raw('Message sent from Seraph', function($message) {
                // The address is of the format phonenumber@wiseservelab.com
                $address = $this->getPhoneNumber() . '@wiseservelab.com';
                // The subject is the message body sent to the user
                $message->to($address)
                        ->subject($this->data['message']);
            });
	*/
	$client = new Client([
	    'headers' => [ 'Content-Type' => 'application/json' ]
	]);
	$number = $this->getPhoneNumber();
	$message = $this->data['message'];
	$serverUrl = "http://".$this->server."/sms?number=";
	$url = $serverUrl.$number;
	$response = $client->post($url,
	    ['body' => json_encode(
		[
		    'message' => $message
		]
	    )]
	);		
        } catch (Exception $e) {
            $this->log->error($e);

            return false;
        }

        return true;
    }

    /**
     * Clean the html code into message and save it into data.
     *
     * @param  string
     *
     * @return void
     */
    private function setMessage($message)
    {
        $this->data['message'] = preg_replace('/\\n/', '', $message);
    }

    /**
     *Save the phone number given into data.
     *
     * @param  string
     *
     * @return void
     */
    private function setPhoneNumber($phone)
    {
        $this->data['phonenumber'] = $phone;
    }

    /**
     *Save the phone number given into data.
     *
     * @param  string
     *
     * @return void
     */
    private function getPhoneNumber()
    {
        return preg_replace('#\[0[^\]]+\]#', '44', $this->data['phonenumber']);
    }
}
