<?php
/**
 * SMS Functions
 * GHAMECC Choir Management Platform
 * 
 * This file contains functions for sending SMS messages using MNotify.
 */

require_once __DIR__ . '/../config/mnotify.php';
require_once __DIR__ . '/../config/logger.php';

/**
 * Send SMS using MNotify API
 * 
 * @param string|array $recipients Phone number(s) to send SMS to (can be string or array)
 * @param string $message Message content
 * @param string $sender_id Optional custom sender ID (defaults to configured sender ID)
 * @return array Response from MNotify API
 */
function sendSMS($recipients, $message, $sender_id = null) {
    // Check if SMS is enabled
    if (!defined('SMS_ENABLED') || !SMS_ENABLED) {
        logInfo('SMS sending skipped - SMS functionality disabled', [
            'recipients' => $recipients,
            'message_length' => strlen($message)
        ]);
        return [
            'status' => 'disabled',
            'message' => 'SMS functionality is currently disabled'
        ];
    }
    
    // Log SMS sending attempt
    logInfo('SMS sending attempt started', [
        'recipients' => $recipients,
        'message_length' => strlen($message),
        'sender_id' => $sender_id
    ]);
    
    // Format recipients - MNotify expects array format
    if (is_string($recipients)) {
        $recipients = [$recipients];
        logInfo('Recipients converted to array format', ['recipients' => $recipients]);
    }
    
    // Use default sender ID if not specified
    if (empty($sender_id)) {
        $sender_id = MNOTIFY_SENDER_ID;
        logInfo('Using default sender ID', ['sender_id' => $sender_id]);
    }
    
    // Build URL with API key parameter - exactly as per MNotify docs
    $endPoint = 'https://api.mnotify.com/api/sms/quick';
    $url = $endPoint . '?key=' . MNOTIFY_API_KEY;
    
    // Log API configuration (without exposing full API key)
    logInfo('API Configuration check', [
        'api_url' => $url,
        'sender_id' => $sender_id,
        'api_key_length' => strlen(MNOTIFY_API_KEY),
        'api_key_prefix' => substr(MNOTIFY_API_KEY, 0, 10) . '...'
    ]);
    
    // Prepare data exactly as per MNotify documentation
    $data = [
        'recipient' => $recipients,
        'sender' => $sender_id,
        'message' => $message,
        'is_schedule' => false,
        'schedule_date' => ''
        // Note: sms_type is omitted as per docs - only include for OTP
    ];
    
    logInfo('SMS request data prepared', [
        'recipient' => $recipients,
        'sender' => $sender_id,
        'message_preview' => substr($message, 0, 50) . '...',
        'is_schedule' => false
    ]);
    
    // Initialize cURL and set options exactly as per MNotify docs
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL verification (not recommended for production)
    
    logInfo('cURL options configured, making API request');
    
    // Execute the request
    $response = curl_exec($ch);
    $error = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // Log raw response details
    logInfo('API response received', [
        'http_code' => $httpCode,
        'curl_error' => $error,
        'response_length' => strlen($response),
        'response_preview' => substr($response, 0, 200)
    ]);
    
    // Close cURL session
    curl_close($ch);
    
    // Handle response
    if ($error) {
        logError('MNotify SMS API cURL Error', [
            'error' => $error,
            'recipients' => $recipients,
            'http_code' => $httpCode
        ]);
        return [
            'status' => 'error',
            'message' => 'Failed to send SMS: ' . $error
        ];
    }
    
    // Decode JSON response exactly as per MNotify docs
    $result = json_decode($response, true);
    
    // Log decoded response
    logInfo('API response decoded', [
        'decoded_response' => $result,
        'json_decode_error' => json_last_error_msg()
    ]);
    
    // Log the result - Updated to handle MNotify response format
    if (isset($result['status']) && $result['status'] === 'success') {
        logInfo('SMS sent successfully', [
            'recipients' => $recipients,
            'message_length' => strlen($message),
            'response' => $result
        ]);
    } elseif (isset($result['code']) && $result['code'] === '2000') {
        // MNotify success response format
        logInfo('SMS sent successfully', [
            'recipients' => $recipients,
            'message_length' => strlen($message),
            'response' => $result
        ]);
        $result['status'] = 'success'; // Normalize response
    } else {
        logError('Failed to send SMS', [
            'recipients' => $recipients,
            'message_length' => strlen($message),
            'response' => $result,
            'http_code' => $httpCode
        ]);
    }
    
    return $result;
}

/**
 * Check MNotify SMS balance
 * 
 * @return array Balance information or error
 */
function checkSMSBalance() {
    // Initialize cURL session
    $ch = curl_init();
    
    // Set cURL options - Updated to match official documentation
    curl_setopt($ch, CURLOPT_URL, MNOTIFY_BALANCE_URL . '?key=' . MNOTIFY_API_KEY);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL verification (not recommended for production)
    
    // Execute the request
    $response = curl_exec($ch);
    $error = curl_error($ch);
    
    // Close cURL session
    curl_close($ch);
    
    // Handle response
    if ($error) {
        logError('MNotify Balance API Error', ['error' => $error]);
        return [
            'status' => 'error',
            'message' => 'Failed to check SMS balance: ' . $error
        ];
    }
    
    // Decode JSON response
    $result = json_decode($response, true);
    
    return $result;
}

/**
 * Send conference delegate notification SMS
 * 
 * @param int $member_id Member ID of the delegate
 * @param int $conference_id Conference ID
 * @param string $conference_name Conference name
 * @param string $conference_date Conference date
 * @return array Response from MNotify API
 */
function sendDelegateNotificationSMS($member_id, $conference_id, $conference_name, $conference_date) {
    global $conn;
    
    // Get member's phone number
    $query = "SELECT first_name, last_name, contact_number 
              FROM members 
              WHERE id = ?";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $member_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $member = $result->fetch_assoc();
    $stmt->close();
    
    if (!$member || empty($member['contact_number'])) {
        logError('Failed to send delegate SMS - invalid member or missing phone number', [
            'member_id' => $member_id,
            'conference_id' => $conference_id
        ]);
        return [
            'status' => 'error',
            'message' => 'Invalid member or missing phone number'
        ];
    }
    
    // Format the message
    $message = "Dear {$member['first_name']}, you have been registered as a delegate for {$conference_name} scheduled for {$conference_date}. Please contact your society secretary for more details.";
    
    // Send the SMS
    return sendSMS($member['contact_number'], $message);
}

/**
 * Send accommodation assignment notification SMS
 * 
 * @param int $registration_id Conference registration ID
 * @param string $room_number Room number assigned
 * @param string $accommodation_type Type of accommodation
 * @param string $check_in_date Check-in date
 * @param string $check_out_date Check-out date
 * @param string $notes Additional notes (optional)
 * @return array Response from MNotify API
 */
function sendAccommodationAssignmentSMS($registration_id, $room_number, $accommodation_type, $check_in_date, $check_out_date, $notes = '') {
    // Get database connection - try multiple methods
    $conn = null;
    
    // Method 1: Try global variable
    if (isset($GLOBALS['conn'])) {
        $conn = $GLOBALS['conn'];
    }
    
    // Method 2: Try to include database config if connection not available
    if (!$conn || !($conn instanceof mysqli)) {
        // Include database connection
        require_once __DIR__ . '/../config/database.php';
        // The $conn variable should now be available from the included file
        if (isset($conn) && $conn instanceof mysqli) {
            // Connection is now available
        } else {
            logError('Failed to get database connection in SMS function', [
                'registration_id' => $registration_id,
                'conn_type' => gettype($conn ?? 'null'),
                'globals_conn_exists' => isset($GLOBALS['conn'])
            ]);
            return [
                'status' => 'error',
                'message' => 'Database connection not available'
            ];
        }
    }
    
    // Check if database connection exists and is valid
    if (!$conn || !($conn instanceof mysqli)) {
        logError('Failed to send accommodation SMS - no database connection', [
            'registration_id' => $registration_id,
            'conn_available' => isset($conn),
            'conn_type' => gettype($conn ?? 'null')
        ]);
        return [
            'status' => 'error',
            'message' => 'Database connection not available'
        ];
    }
    
    // Get member and conference details
    $query = "SELECT 
                m.first_name, 
                m.last_name, 
                m.contact_number,
                c.name as conference_name,
                c.start_date,
                c.end_date
              FROM conference_registrations cr
              JOIN members m ON cr.member_id = m.id
              JOIN conferences c ON cr.conference_id = c.id
              WHERE cr.id = ?";
    
    $stmt = $conn->prepare($query);
    
    // Check if prepare was successful
    if (!$stmt) {
        logError('Failed to prepare accommodation SMS query', [
            'registration_id' => $registration_id,
            'error' => $conn->error
        ]);
        return [
            'status' => 'error',
            'message' => 'Database query preparation failed: ' . $conn->error
        ];
    }
    
    $stmt->bind_param('i', $registration_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    
    if (!$data || empty($data['contact_number'])) {
        logError('Failed to send accommodation SMS - invalid registration or missing phone number', [
            'registration_id' => $registration_id
        ]);
        return [
            'status' => 'error',
            'message' => 'Invalid registration or missing phone number'
        ];
    }
    
    // Format the message
    $message = "Dear {$data['first_name']}, your accommodation has been assigned for {$data['conference_name']}.\n\n";
    $message .= "Details:\n";
    $message .= "Room: {$room_number}\n";
    $message .= "Type: {$accommodation_type}\n";
    $message .= "Check-in: {$check_in_date}\n";
    $message .= "Check-out: {$check_out_date}\n";
    
    if (!empty($notes)) {
        $message .= "Notes: {$notes}\n";
    }
    
    $message .= "\nPlease arrive on time and bring valid identification. Contact your society secretary for any questions.";
    
    // Log the accommodation assignment
    logInfo('Sending accommodation assignment SMS', [
        'registration_id' => $registration_id,
        'member_name' => $data['first_name'] . ' ' . $data['last_name'],
        'phone' => $data['contact_number'],
        'room_number' => $room_number,
        'accommodation_type' => $accommodation_type
    ]);
    
    // Send the SMS
    return sendSMS($data['contact_number'], $message);
}
