<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Exception;

class SmsHelper
{
    /**
     * Send status-based approval SMS
     */
    public static function sendApprovalSMS(int $status, string $serviceName, string $applicationId, ?string $approverName, string $mobile): bool
    {
        try {
            // Fetch configuration
            $smsApiUrl     = config('sms.api_url');
            $apiKey        = config('sms.api_key');
            $dltEntityId   = config('sms.dlt_entity_id');
            $templates     = config('sms.templates');
            $senders       = config('sms.senders');
            $paymentLink   = config('sms.payment_link');

            // Build message based on status
            switch ($status) {
                case 0: // Application received
                    $text = "Dear Citizen, your application {$applicationId} for {$serviceName} has been successfully received under RTS.Regards, Mira Bhayandar Municipal Corporation";
                    $templateId = $templates['received'];
                    $sender = $senders['pt'];
                    break;

                case 1: // Approved at current level
                    $text = "Dear Citizen, your application {$applicationId} for {$serviceName} has been approved at current level. Regards, Mira Bhayandar Municipal Corporation";
                    $templateId = $templates['approved_level'];
                    $sender = $senders['pt'];
                    break;

                case 2: // Rejected
                    $text = "Dear Citizen, your application {$applicationId} for {$serviceName} has been rejected. Regards, Mira Bhayandar Municipal Corporation";
                    $templateId = $templates['rejected'];
                    $sender = $senders['rt'];
                    break;

                case 4: // Final approval
                    $text = "Dear Citizen, your application {$applicationId} for {$serviceName} has been approved. Regards, Mira Bhayandar Municipal Corporation";
                    $templateId = $templates['approved_final'];
                    $sender = $senders['pt'];
                    break;

                case 5: // Payment link
                    $text = "Dear Citizen, please pay for your application {$applicationId} using the link {$paymentLink}. Regards, Mira Bhayandar Municipal Corporation";
                    $templateId = $templates['payment_link'];
                    $sender = $senders['wt'];
                    break;

                default:
                    Log::warning("Unhandled SMS status: {$status}");
                    return false;
            }

            // Validate mobile number
            $mobile = preg_replace('/[^0-9]/', '', $mobile);
            if (strlen($mobile) !== 10) {
                Log::warning("Invalid mobile number: {$mobile}");
                return false;
            }

            // Prepare API request parameters
            $params = [
                'ver'              => '1.0',
                'encrpt'           => '0',
                'type'             => 'UC',
                'dest'             => '91' . $mobile,
                'send'             => $sender,
                'text'             => $text,
                'dlt_entity_id'    => $dltEntityId,
                'dlt_template_id'  => $templateId,
            ];

            // Send SMS
            $response = Http::timeout(10)->get($smsApiUrl, array_merge(['key' => $apiKey], $params));

            Log::channel('sms')->info('SMS sent successfully', [
                'mobile' => $mobile,
                'status' => $status,
                'service' => $serviceName,
                'template_id' => $templateId,
                'response' => $response->body(),
            ]);

            return $response->successful();
        } catch (Exception $e) {
            Log::channel('sms')->error('SMS sending failed', [
                'error' => $e->getMessage(),
                'mobile' => $mobile ?? 'unknown',
                'status' => $status,
            ]);
            return false;
        }
    }

    /**
     * Send payment link SMS
     */
    public static function sendPaymentLinkSMS(string $mobile, string $applicationId, string $paymentLink = null): bool
    {
        $link = $paymentLink ?? config('sms.payment_link');
        return self::sendApprovalSMS(5, 'Payment', $applicationId, null, $mobile);
    }
}
