<?php
namespace App\Services;

use App\Models\SmsQueue;
use Exception;

class SmsService
{
    protected string $apiToken;
    protected string $endpoint;
    protected string $defaultSenderId;

    public function __construct()
    {
        // These constants should be defined in your bootstrap.php or config file
        $this->apiToken = defined('BULKSMS_API_TOKEN') ? BULKSMS_API_TOKEN : '';
        $this->endpoint = defined('BULKSMS_ENDPOINT') ? BULKSMS_ENDPOINT : 'https://www.bulksmsnigeria.com/api/v2/sms';
        $this->defaultSenderId = defined('BULKSMS_SENDER_ID') ? BULKSMS_SENDER_ID : 'EmberAlert';
    }

    /**
     * Send a single SMS or to a comma-separated list of numbers
     */
    public function sendSms(string $to, string $body, ?string $senderId = null): array
    {
        $payload = [
            'from'    => $senderId ?? $this->defaultSenderId,
            'to'      => $to,
            'body'    => $body,
            'gateway' => 'premium' // Forces delivery via DND bypass route
        ];

        $ch = curl_init($this->endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->apiToken,
            'Content-Type: application/json',
            'Accept: application/json'
        ]);
        
        // Add timeout to prevent hanging the queue
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); 

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        
        curl_close($ch);

        if ($curlError) {
            return [
                'success' => false,
                'response' => json_encode(['network_error' => $curlError])
            ];
        }

        $responseData = json_decode($response, true);
        $isSuccess = ($httpCode === 200 && isset($responseData['status']) && $responseData['status'] === 'success');

        return [
            'success' => $isSuccess,
            'response' => $response // Raw JSON string to store in database for debugging
        ];
    }

    /**
     * Process multiple queued SMS messages
     */
    public function sendQueuedSms(array $smsList): void
    {
        foreach ($smsList as $sms) {
            $result = $this->sendSms(
                $sms['phone_number'],
                $sms['message'],
                $sms['sender_id'] ?? null
            );

            SmsQueue::updateStatus(
                $sms['id'],
                $result['success'] ? 'sent' : 'failed',
                $result['response'],
                $result['success'] ? date('Y-m-d H:i:s') : null
            );
        }
    }
}