
<?php
// ==========================================
// CONFIGURATION
// ==========================================
// IMPORTANT: Replace with your actual live API key!
$apiKey = '8d18baa9b108227abd7800cb216b4be64383c52632b0b3097582b60d69356fd7'; 
$senderId = 'Drip Dental';

/**
 * Sends SMS using URL/Form-Encoded format for SMSOnlineGH
 */
if (!function_exists('sendSMS')) {
    function sendSMS($to, $message, $sender, $apiKey) {
        $url = 'https://api.smsonlinegh.com/v5/message/sms/send';

        $data = [
            'key'    => $apiKey,
            'text'   => $message,
            'to'     => $to,
            'sender' => $sender,
            'type'   => 0 // 0 for standard text
        ];

        $postFields = http_build_query($data);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        // Fast timeout so it doesn't freeze the system if the SMS server is slow
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/json'
        ]);

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

        if ($curlError) {
            return ['status' => 0, 'response' => $curlError];
        }

        return ['status' => $httpCode, 'response' => json_decode($response, true)];
    }
}

// ==========================================
// PROCESS AND SEND
// ==========================================
// These variables exist in memory because this file is required INSIDE addNewPatient.php
if (isset($mobile) && isset($patient_no) && isset($first_name)) {
    
    // 1. Format the Phone Number safely
    // Strip out any spaces or dashes the receptionist might have typed
    $formatted_mobile = preg_replace('/[^0-9]/', '', $mobile);
    
    // If it starts with a '0' and is exactly 10 digits long, swap the '0' for '233'
    if (strpos($formatted_mobile, '0') === 0 && strlen($formatted_mobile) == 10) {
        $formatted_mobile = '233' . substr($formatted_mobile, 1);
    }

    // 2. Format the Patient's Full Name cleanly
    $full_name = trim("$first_name $middle_name $last_name");
    
    // Strip double spaces in case there is no middle name
    $full_name = preg_replace('/\s+/', ' ', $full_name); 

    // 3. Construct the Message
    // Note: \n creates a new line in the text message
    $sms_message = "Dear {$first_name},\nThank you for choosing Drip Dental Clinic as your preferred healthcare provider.\nYour Patient ID is: {$patient_no}\nFull Name: {$full_name}\nPlease retain this for future enquiries and appointments.\nWe look forward to serving you and supporting your healthcare needs.";

    // 4. Fire the SMS
    // We only send if the formatted mobile looks like a valid international number length (e.g., 12 digits for Ghana)
    if (strlen($formatted_mobile) >= 10) {
        $result = sendSMS($formatted_mobile, $sms_message, $senderId, $apiKey);
        
        // Log errors silently to the server so it doesn't interrupt the receptionist's screen
        if ($result['status'] != 200) {
            error_log("SMS Failed for Patient {$patient_no}: " . print_r($result['response'], true));
        }
    } else {
        error_log("SMS Skipped for Patient {$patient_no}: Invalid phone number length ({$formatted_mobile})");
    }
}
?>