<?php

declare(strict_types=1);

namespace PpPhp\Plugins\SmsDrivers;

use PpPhp\Core\SmsDriver;

class Ppsms implements SmsDriver
{
    public function label(): string
    {
        return 'PPSMS (ppradhan.com.np)';
    }

    public function helpText(): string
    {
        return 'Enter your API token (Bearer). Single SMS: enter one phone number. Bulk SMS: enter comma‑separated numbers (e.g., 9841000000,9842000000). Optionally provide a Group ID (from your PPSMS phonebook) to send to an entire group.';
    }

    public function requiredFields(): array
    {
        return [
            'api_token' => 'API Token (Bearer)',
            'from'      => 'Sender ID (optional)',
            'group_id'  => 'Group ID (optional, for bulk to a saved group)',
        ];
    }

    public function send(string $to, string $message, array $config): array
    {
        $token = $config['api_token'] ?? '';
        if (empty($token)) {
            return ['success' => false, 'error' => 'API Token is required.'];
        }

        $from = $config['from'] ?? '';
        $groupId = $config['group_id'] ?? '';

        $isBulk = false;
        $contacts = null;

        if (!empty($groupId)) {
            $isBulk = true;
        } elseif (strpos($to, ',') !== false) {
            $isBulk = true;
            $contacts = array_map('trim', explode(',', $to));
        }

        if ($isBulk) {
            return $this->sendBulk($message, $contacts, $groupId, $token);
        }
        return $this->sendSingle($to, $message, $from, $token);
    }

    private function sendSingle(string $to, string $message, string $from, string $token): array
    {
        $url = 'https://sms.ppradhan.com.np/api/send_sms.php';
        $data = ['to' => $to, 'message' => $message];
        if (!empty($from)) {
            $data['from'] = $from;
        }
        return $this->curlJson($url, $data, $token);
    }

    private function sendBulk(string $message, ?array $contacts, string $groupId, string $token): array
    {
        $url = 'https://sms.ppradhan.com.np/api/send_campaign.php';
        $data = ['message' => $message];
        if (!empty($groupId)) {
            $data['group_id'] = (int)$groupId;
        } elseif (!empty($contacts)) {
            $data['contacts'] = $contacts;
        } else {
            return ['success' => false, 'error' => 'No contacts or group ID provided for bulk SMS.'];
        }
        return $this->curlJson($url, $data, $token);
    }

    private function curlJson(string $url, array $data, string $token): array
    {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($data),
            CURLOPT_HTTPHEADER     => [
                'Authorization: Bearer ' . $token,
                'Content-Type: application/json',
                'Accept: application/json',
            ],
        ]);

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

        // No explicit curl_close – PHP will clean up automatically

        $json = json_decode($response, true);
        if ($json && isset($json['success'])) {
            if ($json['success']) {
                return ['success' => true];
            }
            return ['success' => false, 'error' => $json['message'] ?? 'Unknown error'];
        }

        if ($httpCode >= 200 && $httpCode < 300) {
            return ['success' => true];
        }
        return ['success' => false, 'error' => "HTTP {$httpCode}: " . substr($response, 0, 200)];
    }
}
