<?php

ini_set('display_errors', 1);

require_once '/home/rejoicebilldesk/public_html/rjllearning_development/resources/base_path_include.php';

// function sendSmsAndUpdateCounter($workspace_id, $institution_id, $branch_id, $numbers, $message, $conn_rjllearning,$white_label_message_header =  null) {

//     require_once $GLOBALS['base_path_to_learning_resources']  .'lib/cron_jobs/function/function.php';
//     // Account details
//     $apiKey = urlencode('NDc1YTQyNjU0YTRiMzYzOTU0NjY3MTM0NjgzNTZjNTM=');
    
//     if (!is_array($numbers)) {
//         $numbers = [$numbers];
//     }
    
//     if (!empty($numbers)) {
//         // $sender = urlencode('RJLRNG');
//         $sender = urlencode('RJLRNG');
//         $message = rawurlencode($message);
//         $numbersString = implode(',', $numbers);
       
//         // Prepare data for POST request
//         $data = [
//             'apikey' => $apiKey,
//             'numbers' => $numbersString,
//             'sender' => $sender,
//             'message' => $message
//         ];
        
//         // Send the POST request with cURL
//         $ch = curl_init('https://api.textlocal.in/send/');
//         curl_setopt($ch, CURLOPT_POST, true);
//         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//         $response = curl_exec($ch);
//         curl_close($ch);
        
//         // Decode response
//         $response_data = json_decode($response, true);
        
        
//         if (!$response_data) {
//             errorreturn(["error" => "Invalid API response."]);
//         }
        
//         // Extract balance
//         if (!isset($response_data['balance'])) {
//             errorreturn(["error" => "Failed to fetch SMS balance."]);
//         }
//         $balance = (int) $response_data['balance'];
        
//         // Check if SMS was sent successfully
//         if (!isset($response_data['status']) || $response_data['status'] !== "success") {
//             errorreturn(["error" => "SMS sending failed."]);
//         }
        
//         $credit = count($numbers); // Number of messages sent
        
//         // Update the SMS counter
//         updateMailSmsCount($workspace_id, $institution_id, $branch_id, 0, $credit, 0, 'sms', $conn_rjllearning);
        
//         // Update SMS credit balance
//         // $smsCreditUpdate = smscredit($workspace_id, $credit, $balance, $conn_rjllearning);
//         // if ($smsCreditUpdate !== true) {
//         //     return $smsCreditUpdate;
//         // }
        
//       return true;
//     }
    
//     return true;
// }



// function sendSmsAndUpdateCounter($workspace_id, $institution_id, $branch_id, $numbers, $message, $conn_rjllearning, $white_label_message_header = null) {

//     require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/function/function.php';

//     // AmazeSMS API credentials
//     $user = 'rejoicelearningllp';
// $authkey = '92N2gPlnbzXk';
// $sender = 'RJLRNG';
// $entityid = '1001678027933277599';
// $templateid = '1007575635315663801';


//     if (!is_array($numbers)) {
//         $numbers = [$numbers];
//     }

//     if (!empty($numbers)) {
//         foreach ($numbers as $number) {
//             $encodedMessage = urlencode($message);

//             // Build the full URL
//             $url = "https://amazesms.in/api/pushsms?" . http_build_query([
//                 'user'       => $user,
//                 'authkey'    => $authkey,
//                 'sender'     => $sender,
//                 'mobile'     => $number,
//                 'text'       => $message,
//                 'entityid'   => $entityid,
//                 'templateid' => $templateid
//             ]);

//             // Send request using cURL
//             $ch = curl_init($url);
//             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//             $response = curl_exec($ch);
//             $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//             curl_close($ch);

//             // Check for valid response
//             if ($httpCode !== 200 || !$response) {
//                 errorreturn(["error" => "Failed to send SMS via AmazeSMS."]);
//             }

//             // Optionally decode and check AmazeSMS response
//             $response_data = json_decode($response, true);
          
//             if (isset($response_data['status']) && $response_data['status'] != 'success') {
//                 errorreturn(["error" => "SMS sending failed via AmazeSMS."]);
//             }
//         }

//         $credit = count($numbers); // Number of messages sent

//         // Update the SMS counter
//         updateMailSmsCount($workspace_id, $institution_id, $branch_id, 0, $credit, 0, 'sms', $conn_rjllearning);

//         return true;
//     }

//     return true;
// }



function sendSmsAndUpdateCounter($workspace_id, $institution_id, $branch_id, $numbers, $message, $conn_rjllearning, $white_label_message_header = null, $module = null) {
    require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/function/function.php';

    // AmazeSMS API credentials
    $user = 'rejoicelearningllp';
    $authkey = '92N2gPlnbzXk';
    $sender = 'RJLRNG';
    $entityid = '1001678027933277599';

    // Define template ID based on valid modules
    $templateid = null;
    switch ($module) {
        case 'item_distribution':
            $templateid = '1007159645428219380';
            break;
        case 'forgotpassword':
            $templateid = '1007575635315663801';
            break;
        case 'facultygatepass':
            $templateid = '1007635644502997112';
            break;
        case 'gatepass':
            $templateid = '1007706064666084840';
            break;
        case 'principal_gatepass_alert':
            $templateid = '1007949251327189132';
            break;
    }

    // If module is invalid, skip silently
    if (!$templateid) {
        return true;
    }

    // Ensure $numbers is array
    if (!is_array($numbers)) {
        $numbers = [$numbers];
    }

    if (!empty($numbers)) {
        foreach ($numbers as $number) {
            $url = "https://amazesms.in/api/pushsms?" . http_build_query([
                'user'       => $user,
                'authkey'    => $authkey,
                'sender'     => $sender,
                'mobile'     => $number,
                'text'       => $message,
                'entityid'   => $entityid,
                'templateid' => $templateid
            ]);

            // Send SMS via cURL
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $response_data = json_decode($response, true);

            // Log error instead of errorreturn()
            if (
                $httpCode !== 200 ||
                !isset($response_data['RESPONSE']['CODE']) ||
                $response_data['RESPONSE']['CODE'] !== '100' ||
                !isset($response_data['STATUS']) ||
                strtoupper($response_data['STATUS']) !== 'OK'
            ) {
                $logDir = __DIR__; 
                
                $logFile = $logDir . "/sms_error_log_" . date('Y_m_d_H') . ".log";

                $errorMessage = "[" . date('Y-m-d H:i:s') . "] " .
                    "SMS sending failed. Number: {$number}, Module: {$module}, HTTP Code: {$httpCode}, Response: {$response}" . PHP_EOL;

                file_put_contents($logFile, $errorMessage, FILE_APPEND);
            }
        }

        // Update SMS usage count
        $credit = count($numbers);
        updateMailSmsCount($workspace_id, $institution_id, $branch_id, 0, $credit, 0, 'sms', $conn_rjllearning);
    }

    return true;
}

function smscredit($workspace_id, $credit, $balance, $conn_rjllearning) {
    try {
        $shouldCommit = false;
        if (!$conn_rjllearning->inTransaction()) {
            $conn_rjllearning->beginTransaction();
            $shouldCommit = true;
        }

        $stmt = $conn_rjllearning->prepare("SELECT credit FROM email_sms_credit WHERE workspace_id = ? FOR UPDATE");
        $stmt->execute([$workspace_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $current_credit = $row ? (int) $row['credit'] : 0;

        if (!$row) {
            $stmt = $conn_rjllearning->prepare("INSERT INTO email_sms_credit (workspace_id, credit) VALUES (?, ?)");
            $stmt->execute([$workspace_id, 0]);
        }

        if ($current_credit + $credit > $balance) {
            if ($shouldCommit) $conn_rjllearning->rollBack();
            errorreturn(["error" => "No balance remaining."]);
        }

        $stmt = $conn_rjllearning->prepare("UPDATE email_sms_credit SET credit = credit + ? WHERE workspace_id = ?");
        $stmt->execute([$credit, $workspace_id]);

        if ($shouldCommit) $conn_rjllearning->commit();
        return true;
    } catch (Exception $e) {
        if ($conn_rjllearning->inTransaction()) {
            $conn_rjllearning->rollBack();
        }
        errorreturn(["error" => "Error updating credit: " . $e->getMessage()]);
    }
}
