<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;

class TopluSmsService
{
    protected $base;
    protected $apiKey;
    protected $apiHash;
    protected $sender;

    public function __construct()
    {
        $this->base = 'https://api.iletimerkezi.com/v1/'; // TopluSMS API URL
        $this->apiKey = 'c795de6bfdb1b05ad7f0df936cea00e5';
        $this->apiHash = '2233e1be6657b7d94d53a4a2e6fd5c38e1ddc212beae514c6690b3d371ffc13d';
        $this->sender = 'serversist';
    }

    public function sendSms($phoneNumber, $message)
    {
        $xml = <<<EOS
<request>
  <authentication>
    <key>{$this->apiKey}</key>
    <hash>{$this->apiHash}</hash>
  </authentication>
  <order>
    <sender>{$this->sender}</sender>
    <sendDateTime></sendDateTime>
    <iys>0</iys>
    <iysList>BIREYSEL</iysList>
    <message>
      <text><![CDATA[{$message}]]></text>
      <receipents>
        <number>{$phoneNumber}</number>
      </receipents>
    </message>
  </order>
</request>
EOS;

        $response = $this->request('send-sms', $xml);

        if ($response === false) {
            Log::error('cURL Error:', ['error' => curl_error($ch)]);
            return false;
        }

        Log::info('SMS API Response:', ['response' => $response]);

        return $response;
    }

    private function request($type, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->base . $type);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/xml']);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);

        $result = curl_exec($ch);
        if ($result === false) {
            Log::error('cURL Error:', ['error' => curl_error($ch)]);
        }
        curl_close($ch);

        return $result;
    }
}
