<?php

namespace App\Api;

use GuzzleHttp\Client;

class Sms
{
    const URL = '';
    const ORIGINATOR = '';

    protected $client;

    public function __construct()
    {
        $this->client = new Client();
    }

    public function send(int $phone, string $message)
    {
        $data = [
            'messages' => [
                [
                    'recipient' => $phone,
                    'message-id' => time(),
                    'sms' => [
                        'originator' => '3700',
                        'content' => [
                            'text' => $message
                        ]
                    ]
                ]
            ]
        ];

        $data_string = json_encode($data);

        $username = env("SMS_USERNAME");
        $password = env("SMS_PASSWORD");
        $url = env('SMS_URL');

        $debug = [
            'ok' => false,
            'url' => $url,
            'username' => $username,
            'phone' => $phone,
        ];

        if (!$url || !$username || !$password) {
            $debug['error_stage'] = 'env_missing';
            $debug['missing'] = [
                'SMS_URL' => (bool)$url,
                'SMS_USERNAME' => (bool)$username,
                'SMS_PASSWORD' => (bool)$password,
            ];
            return $debug;
        }

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 25);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt(
            $ch,
            CURLOPT_HTTPHEADER,
            [
                'Content-Type: application/json',
                'Accept: application/json',
                'Content-Length: ' . strlen($data_string),
            ]
        );

        $result = curl_exec($ch);

        $debug['curl_errno'] = curl_errno($ch);
        $debug['curl_error'] = curl_error($ch);
        $debug['http_code']  = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $debug['curl_info']  = curl_getinfo($ch);

        $debug['response_head'] = is_string($result) ? mb_substr($result, 0, 2000) : $result;

        curl_close($ch);

        if ($debug['curl_errno'] !== 0) {
            $debug['error_stage'] = 'curl_exec';
            return $debug;
        }

        if ($debug['http_code'] < 200 || $debug['http_code'] >= 300) {
            $debug['error_stage'] = 'http_non_2xx';
            return $debug;
        }

        $debug['ok'] = true;
        $debug['error_stage'] = null;
        return $debug;
    }
}