<?php
namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Crypt;
class SendMessgeService
{
    private $secretKey;
    private $userid;
    private $url;
    private $timestamp;

    public function __construct()
    {
        $this->secretKey = "4siCISCjV9BKdM38";
        $this->userid = "FSKDX";
        $this->url = "http://10.50.120.91:8081/umc/message/send2";
        $this->timestamp=now()->format('YmdHis') . '00';
    }

    private function encrypt($data)
    {

        // $iv = substr($this->secretKey, 0,16);
        $iv = $this->timestamp;
        $key = substr($this->secretKey, 0, 16);

        $cipher = "AES-128-CBC";
        $encrypted = openssl_encrypt($data, $cipher, $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($encrypted);
    }

    public function sendMessage($mobiles, $content, $type = 2)
    {

        // $timestamp = now()->format('YmdHis') . '00';

        $body = json_encode([
            'mobiles' => $mobiles,
            'content' => $content,
            'userid' => $this->userid,
            'type' => $type
        ]);

        $encryptedBody = $this->encrypt($body);
        $response = Http::withHeaders([
            'Content-Type' => 'application/json; charset=utf-8'
        ])->post($this->url, [
            'timestamp' => $this->timestamp,
            'userid' => $this->userid,
            'cntx' => $encryptedBody,
            'custid' => $this->timestamp  // For example purposes, use timestamp as custid
        ]);
        $res=$response->json();
//        if(isset($res['result']) and $res['result']==="0"){
//
//        }



        return $res;
    }
}
