<?php

namespace app\Helpers;
use App\Models\Sales\Ticket;
use App\Models\Facility\Facility;
use App\Models\Sales\Invoice;
use App\Models\Sales\TicketSeat;
use App\Models\Settings\Configuration;
use App\Models\Sales\CancelTicket;
use App\Models\Facility\ShowTimings;
use App\Models\Mail\SMSLog;


class SMSClass {

    // Hardcoded API credentials
    const ACCESS_TOKEN = 'DBKV39MLJ9DDAI';
    const ACCESS_TOKEN_KEY = 'GTzAX3*iCyhVg%cMFSQmsd6IRbK|oU-q';
    const BASE_URL = 'http://4sms.alp-ts.com/api/sms/v1.0';
    const DEFAULT_SMS_HEADER = 'KSSTMU';
    const DEFAULT_COUNTRY_CODE = '91'; // India
    const ENTITY_ID = '1701165278892672283'; // Entity ID from SMS panel
    
    // Template IDs for different SMS types
    //const TEMPLATE_ID_OTP = '1707170617787366035'; // Welcome to KSSTM Online ticketing Your OTP is {#var#} KSSTM
    const TEMPLATE_ID_OTP = '1707177977971842138'; // Welcome to KSSTM Online ticketing Your OTP is {#var#} KSSTM
    const TEMPLATE_ID_BOOKED = '1707165330332554513'; // You have successfully booked ticket {#var#} on {#var#} at {#var#} KSSTM
    const TEMPLATE_ID_REGISTERED = '1707165330323034317'; // You have registered successfully on KSSTM Online Ticketing Application KSSTM
    const TEMPLATE_ID_CANCEL = '1707165330353047846'; // Your ticket {#var#} has been cancelled. Refund of Rs.{#var#} will be credited to your account KSSTM.
    const TEMPLATE_ID_CANCEL2 = '1707170617820398790'; // Your ticket {#var#} has been cancelled Refund of Rs {#var#} will be credited to your account KSSTM
    const TEMPLATE_ID_SHOWCANCEL = '1707170617835701694'; // We are sorry to inform you that {#var#} show has been cancelled for {#var#} {#var#} KSSTM
    
    // Default template ID (rejection template)
    const TEMPLATE_ID = self::TEMPLATE_ID_OTP;


    public function sendNewSms($recipients, $templateId, $message)
    {
        $header = self::DEFAULT_SMS_HEADER;

        $recipientArray = is_array($recipients) ? $recipients : [$recipients];

        $validatedRecipients = [];
        foreach ($recipientArray as $recipient) 
        {
            // Use validatePhoneNumber() function to validate and format phone number
            $validatedPhone = self::validatePhoneNumber($recipient);
            
            // If validation successful, add to recipients array
            if ($validatedPhone !== false) {
                $validatedRecipients[] = $validatedPhone;
            } 
            // Invalid phone number, log warning
            else {
                //Log::warning("Invalid phone number: {$recipient}");
            }
        }
        
        $processedMessage = $message;

        // Request path for send-sms endpoint
        $requestFor = 'send-sms';

        $signatureData = self::generateSignature($requestFor);
        $expire = $signatureData['expire'];
        $authSignature = $signatureData['signature'];

        // API endpoint URL
        $apiEndpoint = self::BASE_URL . '/' . $requestFor;

        // Use provided templateId or default to rejection template
        $usedTemplateId = $templateId;

        // Prepare request payload according to API documentation
        // Matching the cURL example format exactly
        $payload = [
            'accessToken' => self::ACCESS_TOKEN,
            'expire' => $expire,
            'authSignature' => $authSignature,
            'route' => 'transactional', // Route type: transactional (from image)
            'smsHeader' => $header, // SMS Header: KSSTMU (from image)
            'messageContent' => $processedMessage,
            'recipients' => $validatedRecipients, // Array of phone numbers with country code
            'contentType' => 'text', // text or unicode
            'entityId' => self::ENTITY_ID, // Entity ID: 1701165278892672283 (from image)
            'templateId' => $usedTemplateId, // Template ID (can be different for each template)
            'removeDuplicateNumbers' => '1', // String "1" not boolean true (as per cURL example)
            // Note: countryCode and webHookId are not included as per cURL example
        ];

        // Convert payload to JSON
        $payloadJson = json_encode($payload);

        // Prepare HTTP headers
        $headers = [
            'Content-Type: application/json',
            'Accept: application/json',
        ];

        // Initialize cURL request
        $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $apiEndpoint,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $payloadJson,
                CURLOPT_HTTPHEADER => $headers,
            ]);


        // Execute cURL request
        $response = curl_exec($curl);
        
        // Get HTTP response code
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        
        $isError = '';
        // Check for cURL errors
        if (curl_errno($curl)) {
            $isError = true;
            $errorMessage = curl_error($curl);
        }
        
        // Close cURL handle
        curl_close($curl);

        // Parse JSON response
        //$responseData = json_decode($response, true);


        ////insert into sms log table//////////////////
        $smstime = date("Y-m-d H:i:s");
        $sms_functionality = "Send OTP through SMS";

        if($templateId == '1707177977971842138')
            $sms_functionality = "OTP SMS";
        if($templateId == '1707165330332554513')
            $sms_functionality = "BOOKED TICKET SMS";
        if($templateId == '1707165330323034317')
            $sms_functionality = "REGISTERED SMS";
        if($templateId == '1707165330353047846')
            $sms_functionality = "CANCELLED SMS";
        if($templateId == '1707170617820398790')
            $sms_functionality = "CANCELLED SMS";
        if($templateId == '1707170617835701694')
            $sms_functionality = "SHOW CANCELLED SMS";
        if($templateId == '1707165330341920175')
            $sms_functionality = "PASSWORD SEND";

        $insert_smslog = SMSLog::create([
                'sms_content' => $message,
                'sms_functionality' => $sms_functionality,
                'curl_output' => $response,
                'curl_output_code' => $httpCode,
                'mobile_number' => $recipients,
                'sms_time' => $smstime,
            ]);
        //////////////////////////////////////////
        if($isError){
            return array('error' => 1 , 'message' => $errorMessage);
        }else{
            return array('error' => 0, 'message' => $response );
        }




    }

    public static function generateSignature($requestFor = 'send-sms', $expire = null)
    {
        // Use provided expire or generate new one (1 minute from now)
        if ($expire === null) {
            $expire = strtotime("+1 minute");
        }

        // Step 1: Create timeKey = md5(requestFor + "sms@rits-v1.0" + expire)
        $timeKey = md5($requestFor . "sms@rits-v1.0" . $expire);

        // Step 2: Create timeAccessTokenKey = md5(accessToken + timeKey)
        $timeAccessTokenKey = md5(self::ACCESS_TOKEN . $timeKey);

        // Step 3: Create signature = md5(timeAccessTokenKey + accessTokenKey)
        $signature = md5($timeAccessTokenKey . self::ACCESS_TOKEN_KEY);

        return [
            'signature' => $signature,
            'expire' => $expire
        ];
    }

    public static function validatePhoneNumber($phoneNumber)
    {
        // Remove all non-numeric characters
        $phone = preg_replace('/[^0-9]/', '', $phoneNumber);
        
        // If 10 digits, add country code 91
        if (strlen($phone) == 10) {
            return self::DEFAULT_COUNTRY_CODE . $phone;
        } 
        // If already has country code (12 digits starting with 91)
        elseif (strlen($phone) == 12 && substr($phone, 0, 2) == '91') {
            return $phone;
        }
        
        // Invalid phone number
        return false;
    }

    public function sendSMS($OTP, $mobileNumber, $country_code='+91'){
        

        $message = "Welcome to KSSTM Online ticketing, Your OTP is : $OTP KSSTM";


        return $this->sendNewSms($mobileNumber, 1707177977971842138, $message);

        

    }

    public function resendSMS($mobileNumber, $country_code='+91'){
        $isError = 0;
        $errorMessage = true;
        $isError = '';
        $output = '';
        $curl_response_code ='';
        //get OTP from session variable
        $OTP = \Session::get('OTP');


        if($OTP)
        {
            $message = "Welcome to KSSTM Online ticketing, Your OTP is : $OTP KSSTM";


            return $this->sendNewSms($mobileNumber, 1707177977971842138, $message);


        }
        else
        {
            return array('error' => 1, 'message' => "No Otp in session" );
        }

       
     
        
       
    }

    public function sendSMSRegistration($mobileNumber,$country_code='+91')
    {

        $message = "You have Registered successfully on KSSTM Online Ticketing Application.";


        return $this->sendNewSms($mobileNumber, 1707165330323034317, $message);


    }

    public function sendSMSticket($invoice_id, $mobileNumber, $country_code='+91')
    {

        $isError = 0;
        $errorMessage = true;
        $isError = '';
        $output = '';
        $curl_response_code = "";
        //Your message to send, Adding URL encoding.
        
        $invoices = Invoice::where('id',$invoice_id)->where('status',1)->first();
        if(isset($invoices))
        {
            $invoice_date = $invoices->invoice_date;
            $invoice_date_new = date("d-M-Y", strtotime($invoice_date));
            $show_date = $invoices->show_date;
            $show_date = date("d-M-Y", strtotime($show_date));
            $invoice_month = date('m',strtotime($invoice_date));
            $invoice_year = date('Y',strtotime($invoice_date));
            $invoice_no = $invoices->invoice_no;
            $org_code = $invoices->organisation->short_code;
            if($invoice_month<4)
                $invoice_year--;
            $nextyear = $invoice_year+1;
            $invoice_number = $org_code.'/'.$invoice_no.'/'.$invoice_year.'-'.$nextyear;

            $org_name = $invoices->organisation->organisation_name;
            $cityname = $invoices->organisation->city;
            $center = $org_name." ".$cityname;
        }

        $message = "Welcome to KSSTM Online ticketing, You have successfully booked ticket $invoice_number on $show_date at $center.";


        return $this->sendNewSms($mobileNumber, 1707165330332554513, $message);

        
    }

    public function sendSMSpassword($password,$mobileNumber,$country_code='+91')
    {

        $message = "Your Password is reset for this mobile number on KSSTM Online Ticketing Application. Your new Password is $password";


        return $this->sendNewSms($mobileNumber, 1707165330341920175, $message);


        
    }

    public function sendSMSCancelTicket($invoice_id, $mobileNumber, $country_code='+91')
    {
        $isError = 0;
        $errorMessage = true;
        $isError = '';
        $output = '';
        $curl_response_code = "";
        //Your message to send, Adding URL encoding.
        
        $invoices = Invoice::where('id',$invoice_id)->first();
        if(isset($invoices))
        {
            $invoice_date = $invoices->invoice_date;
            $invoice_date_new = date("d-M-Y", strtotime($invoice_date));
            $show_date = $invoices->show_date;
            $show_date = date("d-M-Y", strtotime($show_date));
            $invoice_month = date('m',strtotime($invoice_date));
            $invoice_year = date('Y',strtotime($invoice_date));
            $invoice_no = $invoices->invoice_no;
            $org_code = $invoices->organisation->short_code;
            if($invoice_month<4)
                $invoice_year--;
            $nextyear = $invoice_year+1;
            $invoice_number = $org_code.'/'.$invoice_no.'/'.$invoice_year.'-'.$nextyear;

            $org_name = $invoices->organisation->organisation_name;
            $cityname = $invoices->organisation->city;
            $center = $org_name." ".$cityname;
        }
        //dd("here");
        $cancelticket = CancelTicket::where('invoice_id',$invoice_id)->where('refund_status',0)->first();
        //dd($cancelticket);
        if(isset($cancelticket))
        {
            $refund_amount  = $cancelticket->refund_amount;
        }
        //dd($refund_amount);
        $message = "Your ticket $invoice_number has been cancelled. Refund of Rs. $refund_amount will be credited to your account.";


        return $this->sendNewSms($mobileNumber, 1707165330353047846, $message);



        
    }  

    public function sendSMSCancelShows($facility_id, $show_time_id, $show_date, $mobileNumber, $country_code='+91')
    {
        $isError = 0;
        $errorMessage = true;
        $isError = '';
        $output = '';
        $curl_response_code = "";
        //Your message to send, Adding URL encoding.
        
        $facility = Facility::where('id',$facility_id)->where('active_flag',1)->first();
        if(isset($facility))
        {
            $facility_name = $facility->facility_name;
        }
        $showtimings = ShowTimings::where('id',$show_time_id)->where('active_flag',1)->first();
        if(isset($showtimings))
        {
            $from_time = $showtimings->from_time;
            $from_time = date("g:i A", strtotime($from_time));
            $to_time = $showtimings->to_time;
            $to_time = date("g:i A", strtotime($to_time));
            $show_time = $from_time ." - ".$to_time;
        }

        $message = "We are sorry to inform you that $facility_name show has been cancelled for $show_date, $show_time";


        return $this->sendNewSms($mobileNumber, 1707170617835701694, $message);

        
    }      

}
?>