<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
    $customer_phone = $_POST['customer_phone'] ?? '';
    $message_type = $_POST['message_type'] ?? '';
    $message = $_POST['message'] ?? '';
    
    // Validate inputs
    if (!$order_id || !$customer_phone || !$message) {
        header('Location: view_order.php?id=' . $order_id . '&error=Missing required fields');
        exit();
    }
    
    // Get SMS settings
    $sql_settings = "SELECT setting_key, setting_value FROM settings 
                     WHERE setting_key IN ('sms_provider', 'at_username', 'at_api_key', 'at_sender_id',
                                          'twilio_sid', 'twilio_token', 'twilio_from',
                                          'custom_sms_url', 'custom_sms_key', 'custom_sms_secret',
                                          'company_name')";
    $result_settings = $conn->query($sql_settings);
    
    $settings = [];
    while ($row = $result_settings->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    function getSetting($key, $default = '') {
        global $settings;
        return $settings[$key] ?? $default;
    }
    
    // Send SMS based on provider
    $sms_result = sendSMS($customer_phone, $message, $settings);
    
    if ($sms_result['success']) {
        // Log SMS activity
        $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values, ip_address) 
                        VALUES (?, 'CREATE', 'SMS', ?, ?, ?)";
        $stmt = $conn->prepare($activity_sql);
        $log_data = json_encode([
            'phone' => $customer_phone,
            'message_type' => $message_type,
            'message_length' => strlen($message),
            'provider' => getSetting('sms_provider')
        ]);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $stmt->bind_param("isss", $user_id, $order_id, $log_data, $ip_address);
        $stmt->execute();
        
        header('Location: view_order.php?id=' . $order_id . '&success=SMS sent successfully to ' . $customer_phone);
    } else {
        header('Location: view_order.php?id=' . $order_id . '&error=Failed to send SMS: ' . $sms_result['error']);
    }
    exit();
}

/**
 * Send SMS based on configured provider
 */
function sendSMS($phone, $message, $settings) {
    $provider = $settings['sms_provider'] ?? 'disabled';
    
    if ($provider === 'disabled') {
        return ['success' => false, 'error' => 'SMS service is disabled'];
    }
    
    // Clean phone number
    $phone = cleanPhoneNumber($phone);
    
    if (!$phone) {
        return ['success' => false, 'error' => 'Invalid phone number format'];
    }
    
    switch ($provider) {
        case 'africas_talking':
            return sendAfricasTalkingSMS($phone, $message, $settings);
            
        case 'twilio':
            return sendTwilioSMS($phone, $message, $settings);
            
        case 'custom':
            return sendCustomSMS($phone, $message, $settings);
            
        default:
            return ['success' => false, 'error' => 'Unknown SMS provider'];
    }
}

/**
 * Send SMS via Africa's Talking
 */
function sendAfricasTalkingSMS($phone, $message, $settings) {
    $username = $settings['at_username'] ?? '';
    $apiKey = base64_decode($settings['at_api_key'] ?? '');
    $senderId = $settings['at_sender_id'] ?? '';
    
    if (!$username || !$apiKey) {
        return ['success' => false, 'error' => 'Africa\'s Talking credentials not configured'];
    }
    
    $url = 'https://api.africastalking.com/version1/messaging';
    
    $postData = [
        'username' => $username,
        'to' => $phone,
        'message' => $message
    ];
    
    if ($senderId) {
        $postData['from'] = $senderId;
    }
    
    $headers = [
        'Content-Type: application/x-www-form-urlencoded',
        'apiKey: ' . $apiKey,
        'Accept: application/json'
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return ['success' => false, 'error' => 'cURL error: ' . $error];
    }
    
    if ($httpCode !== 201) {
        return ['success' => false, 'error' => 'HTTP error: ' . $httpCode . ' - ' . $response];
    }
    
    $result = json_decode($response, true);
    
    if (isset($result['SMSMessageData']['Recipients'][0]['status']) && 
        $result['SMSMessageData']['Recipients'][0]['status'] === 'Success') {
        return ['success' => true, 'response' => $result];
    } else {
        $errorMsg = $result['SMSMessageData']['Recipients'][0]['status'] ?? 'Unknown error';
        return ['success' => false, 'error' => $errorMsg];
    }
}

/**
 * Send SMS via Twilio
 */
function sendTwilioSMS($phone, $message, $settings) {
    $accountSid = $settings['twilio_sid'] ?? '';
    $authToken = base64_decode($settings['twilio_token'] ?? '');
    $fromNumber = $settings['twilio_from'] ?? '';
    
    if (!$accountSid || !$authToken || !$fromNumber) {
        return ['success' => false, 'error' => 'Twilio credentials not configured'];
    }
    
    $url = "https://api.twilio.com/2010-04-01/Accounts/$accountSid/Messages.json";
    
    $postData = [
        'From' => $fromNumber,
        'To' => $phone,
        'Body' => $message
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_USERPWD, $accountSid . ':' . $authToken);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return ['success' => false, 'error' => 'cURL error: ' . $error];
    }
    
    $result = json_decode($response, true);
    
    if ($httpCode === 201 && isset($result['sid'])) {
        return ['success' => true, 'response' => $result];
    } else {
        $errorMsg = $result['message'] ?? 'HTTP error: ' . $httpCode;
        return ['success' => false, 'error' => $errorMsg];
    }
}

/**
 * Send SMS via Custom API
 */
function sendCustomSMS($phone, $message, $settings) {
    $apiUrl = $settings['custom_sms_url'] ?? '';
    $apiKey = base64_decode($settings['custom_sms_key'] ?? '');
    $apiSecret = base64_decode($settings['custom_sms_secret'] ?? '');
    
    if (!$apiUrl || !$apiKey) {
        return ['success' => false, 'error' => 'Custom SMS API not configured'];
    }
    
    // Generic implementation - adjust based on your SMS provider's API
    $postData = [
        'to' => $phone,
        'message' => $message,
        'api_key' => $apiKey
    ];
    
    if ($apiSecret) {
        $postData['api_secret'] = $apiSecret;
    }
    
    $headers = [
        'Content-Type: application/json',
        'Accept: application/json'
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return ['success' => false, 'error' => 'cURL error: ' . $error];
    }
    
    $result = json_decode($response, true);
    
    // Adjust this based on your API's success response format
    if ($httpCode === 200 && isset($result['status']) && $result['status'] === 'success') {
        return ['success' => true, 'response' => $result];
    } else {
        $errorMsg = $result['message'] ?? 'HTTP error: ' . $httpCode;
        return ['success' => false, 'error' => $errorMsg];
    }
}

/**
 * Clean and format phone number
 */
function cleanPhoneNumber($phone) {
    // Remove all non-numeric characters except +
    $phone = preg_replace('/[^\d+]/', '', $phone);
    
    // Handle Kenyan numbers
    if (preg_match('/^0([17]\d{8})$/', $phone, $matches)) {
        // Convert 07xxxxxxxx to +2547xxxxxxxx
        return '+254' . $matches[1];
    } elseif (preg_match('/^([17]\d{8})$/', $phone, $matches)) {
        // Convert 7xxxxxxxx to +2547xxxxxxxx
        return '+254' . $matches[1];
    } elseif (preg_match('/^254([17]\d{8})$/', $phone, $matches)) {
        // Convert 2547xxxxxxxx to +2547xxxxxxxx
        return '+254' . $matches[1];
    } elseif (preg_match('/^\+254([17]\d{8})$/', $phone)) {
        // Already in correct format
        return $phone;
    } elseif (preg_match('/^\+\d{10,15}$/', $phone)) {
        // International format
        return $phone;
    }
    
    return false; // Invalid format
}

/**
 * Get SMS template based on message type
 */
function getSMSTemplate($messageType, $orderData, $companyName) {
    $templates = [
        'status_update' => "Hi {customer_name}, your order {order_number} status has been updated to {status}. Thank you for choosing {company_name}.",
        
        'payment_reminder' => "Hi {customer_name}, this is a reminder that order {order_number} has a pending balance of KES {balance}. Please settle at your convenience. {company_name}",
        
        'pickup_reminder' => "Hi {customer_name}, your order {order_number} is ready for pickup. Please collect it at your convenience. {company_name}",
        
        'delivery_notification' => "Hi {customer_name}, your order {order_number} is out for delivery and will arrive shortly. Thank you for choosing {company_name}.",
        
        'order_received' => "Hi {customer_name}, we have received your order {order_number}. Estimated ready time: {estimated_delivery}. {company_name}",
        
        'order_ready' => "Great news {customer_name}! Your order {order_number} is now ready for collection. Total: KES {total_amount}. {company_name}",
        
        'order_delivered' => "Hi {customer_name}, your order {order_number} has been successfully delivered. Thank you for choosing {company_name}!",
        
        'payment_received' => "Hi {customer_name}, we have received your payment of KES {paid_amount} for order {order_number}. Balance: KES {balance}. Thank you! {company_name}",
        
        'welcome_customer' => "Welcome to {company_name}! Your customer code is {customer_code}. We look forward to serving you with quality laundry services."
    ];
    
    return $templates[$messageType] ?? '';
}

/**
 * Replace template variables with actual data
 */
function replaceSMSVariables($template, $orderData, $companyName) {
    $variables = [
        '{customer_name}' => $orderData['customer_name'] ?? 'Valued Customer',
        '{order_number}' => $orderData['order_number'] ?? '',
        '{status}' => $orderData['status'] ?? '',
        '{balance}' => number_format($orderData['balance_amount'] ?? 0, 2),
        '{total_amount}' => number_format($orderData['total_amount'] ?? 0, 2),
        '{paid_amount}' => number_format($orderData['paid_amount'] ?? 0, 2),
        '{estimated_delivery}' => $orderData['estimated_delivery'] ?? '',
        '{company_name}' => $companyName,
        '{customer_code}' => $orderData['customer_code'] ?? ''
    ];
    
    return str_replace(array_keys($variables), array_values($variables), $template);
}

/**
 * Validate message length and content
 */
function validateSMSMessage($message) {
    $message = trim($message);
    
    if (empty($message)) {
        return ['valid' => false, 'error' => 'Message cannot be empty'];
    }
    
    if (strlen($message) > 160) {
        return ['valid' => false, 'error' => 'Message exceeds 160 characters limit'];
    }
    
    // Check for potentially problematic characters
    if (preg_match('/[^\x20-\x7E\x0A\x0D]/', $message)) {
        return ['valid' => false, 'error' => 'Message contains unsupported characters'];
    }
    
    return ['valid' => true];
}

/**
 * Log SMS activity to database
 */
function logSMSActivity($conn, $orderId, $phone, $message, $messageType, $status, $provider, $response, $userId) {
    try {
        $sql = "INSERT INTO sms_log (order_id, phone_number, message_content, message_type, status, provider, provider_response, sent_by, sent_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        // Create table if it doesn't exist
        $createTable = "CREATE TABLE IF NOT EXISTS sms_log (
            id INT AUTO_INCREMENT PRIMARY KEY,
            order_id INT NULL,
            phone_number VARCHAR(20) NOT NULL,
            message_content TEXT NOT NULL,
            message_type VARCHAR(50) NULL,
            status ENUM('SENT', 'FAILED', 'PENDING') NOT NULL,
            provider VARCHAR(50) NULL,
            provider_response TEXT NULL,
            sent_by INT NOT NULL,
            sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_order (order_id),
            INDEX idx_phone (phone_number),
            INDEX idx_status (status)
        )";
        $conn->query($createTable);
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("issssssi", $orderId, $phone, $message, $messageType, $status, $provider, $response, $userId);
        $stmt->execute();
        
        return true;
    } catch (Exception $e) {
        error_log("SMS Log Error: " . $e->getMessage());
        return false;
    }
}

/**
 * Send bulk SMS to multiple customers
 */
function sendBulkSMS($phones, $message, $settings) {
    $results = [];
    $provider = $settings['sms_provider'] ?? 'disabled';
    
    foreach ($phones as $phone) {
        $result = sendSMS($phone, $message, $settings);
        $results[] = [
            'phone' => $phone,
            'success' => $result['success'],
            'error' => $result['error'] ?? null
        ];
        
        // Add small delay to prevent rate limiting
        if ($provider === 'africas_talking') {
            usleep(100000); // 0.1 second delay
        } elseif ($provider === 'twilio') {
            usleep(50000); // 0.05 second delay
        }
    }
    
    return $results;
}

/**
 * Schedule SMS for later sending
 */
function scheduleSMS($conn, $phone, $message, $messageType, $scheduleDateTime, $orderId = null, $userId) {
    try {
        // Create scheduled_sms table if it doesn't exist
        $createTable = "CREATE TABLE IF NOT EXISTS scheduled_sms (
            id INT AUTO_INCREMENT PRIMARY KEY,
            order_id INT NULL,
            phone_number VARCHAR(20) NOT NULL,
            message_content TEXT NOT NULL,
            message_type VARCHAR(50) NULL,
            scheduled_for DATETIME NOT NULL,
            status ENUM('PENDING', 'SENT', 'FAILED', 'CANCELLED') DEFAULT 'PENDING',
            created_by INT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            sent_at TIMESTAMP NULL,
            INDEX idx_scheduled (scheduled_for, status),
            INDEX idx_order (order_id)
        )";
        $conn->query($createTable);
        
        $sql = "INSERT INTO scheduled_sms (order_id, phone_number, message_content, message_type, scheduled_for, created_by) 
                VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("issssi", $orderId, $phone, $message, $messageType, $scheduleDateTime, $userId);
        
        if ($stmt->execute()) {
            return ['success' => true, 'scheduled_id' => $conn->insert_id];
        } else {
            return ['success' => false, 'error' => 'Failed to schedule SMS'];
        }
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

// If called directly (for testing)
if (basename($_SERVER['PHP_SELF']) === 'send_sms.php' && isset($_GET['test'])) {
    // Test SMS functionality
    header('Content-Type: application/json');
    
    $testPhone = $_GET['phone'] ?? '+254700000000';
    $testMessage = $_GET['message'] ?? 'Test message from QuickWash Laundry System';
    
    // Get settings
    $sql_settings = "SELECT setting_key, setting_value FROM settings 
                     WHERE setting_key LIKE '%sms%' OR setting_key LIKE '%twilio%' OR setting_key LIKE '%at_%'";
    $result_settings = $conn->query($sql_settings);
    
    $settings = [];
    while ($row = $result_settings->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    $result = sendSMS($testPhone, $testMessage, $settings);
    
    echo json_encode([
        'success' => $result['success'],
        'message' => $result['success'] ? 'SMS sent successfully' : $result['error'],
        'details' => $result
    ]);
    exit();
}

$conn->close();
?>