<?php

namespace App\Libraries;

use CodeIgniter\HTTP\CURLRequest;

class EmergencyService {
    // Replace with your actual API keys from the provider
    protected $apiKey = 'YOUR_API_KEY';
    protected $smsUrl = 'https://api.messagebot.in/v1/sms/send'; 
    protected $voiceUrl = 'https://api.messagebot.in/v1/voice/call';
    protected $apiToken = 'YOUR_MESSAGEBOT_TOKEN';
    protected $senderId = 'SAFAPP'; // Your DLT Header
    
    public function triggerFullAlert($mobile, $name, $location) {
        // 1. Try sending SMS first
        $smsSent = $this->sendSms($mobile, "EMERGENCY: $name needs help! Loc: $location");

        // 2. Fallback: Trigger Voice Call regardless of SMS status for safety
        // Or you can put this in an 'if (!$smsSent)' block
        $voiceStarted = $this->triggerVoiceCall($mobile, $name);

        return [
            'sms' => $smsSent,
            'voice' => $voiceStarted
        ];
    }

    private function sendMessageSms($mobile, $message) {
        $client = \Config\Services::curlrequest();
        try {
            $response = $client->post($this->smsUrl, [
                'form_params' => [
                    'api_key' => $this->apiKey,
                    'to'      => $mobile,
                    'message' => $message,
                    // For testing without DLT on Fast2SMS, route would be 'quick_sms'
                ]
            ]);
            return $response->getStatusCode() === 200;
        } catch (\Exception $e) {
            return false;
        }
    }

    private function triggerVoiceCall($mobile, $name) {
        $client = \Config\Services::curlrequest();
        try {
            // Voice APIs usually use Text-to-Speech (TTS)
            $response = $client->post($this->voiceUrl, [
                'form_params' => [
                    'api_key' => $this->apiKey,
                    'to'      => $mobile,
                    'text'    => "Alert. This is an emergency call from $name's safety app. Please check your messages immediately.",
                    'language'=> 'en-IN', // Indian English accent
                    'retries' => 2        // Call again if they don't pick up
                ]
            ]);
            return $response->getStatusCode() === 200;
        } catch (\Exception $e) {
            return false;
        }
    }


    public function triggerAlert($mobile, $message) {
        //WHEN MESSAGEBOT API ACTIVE UNCOMMENT THESE LINES
        
        /*$client = \Config\Services::curlrequest();

        $payload = [
            "apiToken" => $this->apiToken,
            "messageType" => "1", // 1 for Transactional
            "destinationAddress" => "91" . $mobile,
            "sourceAddress" => $this->senderId,
            "messageText" => $message,
            "dltEntityId" => "YOUR_DLT_ENTITY_ID",
            "dltEntityTemplateId" => "YOUR_DLT_TEMPLATE_ID"
        ];

        // MessageBot Endpoint (V2)
        $response = $client->post('http://papi.messagebot.in/SendSmsV2', [
            'json' => $payload,
            'headers' => ['Content-Type' => 'application/json']
        ]);

        return json_decode($response->getBody());*/
        
        $this->sendSMS($mobile, $message);
    }
    
    private function sendSMS($mobile, $message)
    {
        $queueFile = FCPATH . '../../prescription_app/otp_queue.json';
        //$queueFile = FCPATH . '../otp_queue.json';
        log_message('error', 'Resolved OTP Queue Path: ' . $queueFile);

        $queueData = [];

        if (file_exists($queueFile)) {
            $queueData = json_decode(file_get_contents($queueFile), true) ?? [];
        }

        $queueData[$mobile] = [
            'mobile' => $mobile,
            'otp' => $message,
            'timestamp' => time()
        ];

        file_put_contents($queueFile, json_encode($queueData, JSON_PRETTY_PRINT));
        log_message('error', 'OTP Queue Saved: ' . json_encode($queueData));
        
    }    
    
}