<?php
require_once('../database/header.php');

// Check if user is admin
if($userdata['usertype'] != 'mainadmin') {
    header("Location: ../index.php");
    exit();
}

// Function to send SMS via MerchantAPI
function sendSMS($mobile, $message) {
    $api_key = "b0rgYSiyG7KMuLb2Z6OKDq5b2JLYxw";
    $sender = "919157455623"; // Your sender number with country code
    
    // Prepare API URL
    $url = "https://send.merchantapi.in/send-message?" . http_build_query([
        'api_key' => $api_key,
        'sender' => $sender,
        'number' => '91' . $mobile, // Adding country code for India
        'message' => $message
    ]);
    
    // Initialize cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    // Execute and get response
    $response = curl_exec($ch);
    curl_close($ch);
    
    // Check response (modify based on MerchantAPI's actual response format)
    return strpos($response, 'success') !== false;
}

// Function to send message to all users
function sendMessageToAllUsers() {
    global $conn;
    
    // Verify database connection
    if(!$conn) {
        return [
            'success' => 0, 
            'failed' => 0, 
            'total_users' => 0,
            'error' => '数据库连接失败。请检查您的数据库配置。'
        ];
    }
    
    try {
        // First check if status column exists
        $checkStatus = $conn->query("SHOW COLUMNS FROM loginusers LIKE 'status'");
        $statusExists = ($checkStatus->rowCount() > 0);
        
        // Prepare base query
        $query = "SELECT mobile_no, owner_name FROM loginusers 
                 WHERE mobile_no IS NOT NULL 
                 AND mobile_no != ''";
        
        if($statusExists) {
            $query .= " AND status = 'approved'";
        }
        
        // Execute query
        $stmt = $conn->query($query);
        $userCount = $stmt->rowCount();
        
        if($userCount == 0) {
            return [
                'success' => 0, 
                'failed' => 0, 
                'total_users' => 0,
                'error' => '未找到具有有效手机号码的活跃用户。'
            ];
        }
        
        $successCount = 0;
        $failCount = 0;
        
        while($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
            // Verify mobile number format
            $mobile = trim($user['mobile_no']);
            if(empty($mobile) || !preg_match('/^[0-9]{10,15}$/', $mobile)) {
                $failCount++;
                continue;
            }
            
            // Prepare message
            $msg = "Dear *".htmlspecialchars($user['owner_name'])."*,%0A%0A"
                  ."Important Notice:%0A"
                  ."1. All failed transactions will be deleted tonight at 12 AM%0A"
                  ."2. Take backup before 12 PM if needed%0A"
                  ."3. Current offer ends today%0A%0A"
                  ."For details, WhatsApp: 9157455623%0A%0A"
                  ."Regards,%0A"
                  ."*Support Team*";
            
            // Send SMS via MerchantAPI
            $sms_sent = sendSMS($mobile, urldecode($msg));
            
            if($sms_sent) {
                $successCount++;
            } else {
                $failCount++;
                error_log("Failed to send SMS to: $mobile");
            }
        }
        
        return [
            'success' => $successCount,
            'failed' => $failCount,
            'total_users' => $userCount
        ];
        
    } catch(PDOException $e) {
        return [
            'success' => 0, 
            'failed' => 0, 
            'total_users' => 0,
            'error' => '数据库错误: '.$e->getMessage()
        ];
    }
}

// Process form submission
if(isset($_POST['send_message'])) {
    $result = sendMessageToAllUsers();
    
    // Prepare result message
    $message = "<div class='alert alert-".(($result['success'] > 0) ? 'success' : 'danger')."'>";
    $message .= "<h5><i class='fas fa-info-circle'></i> 消息传递报告</h5>";
    $message .= "<p>总用户数: ".$result['total_users']."</p>";
    $message .= "<p>成功发送: ".$result['success']."</p>";
    $message .= "<p>发送失败: ".$result['failed']."</p>";
    
    if(isset($result['error'])) {
        $message .= "<div class='alert alert-warning mt-3'><strong>错误:</strong> ".$result['error']."</div>";
    }
    
    $message .= "</div>";
}
?>

<div class="main-panel">
    <div class="content-wrapper">
        <div class="row">
            <div class="col-md-12 stretch-card">
                <div class="card shadow mb-4">
                    <div class="card-header py-3 bg-primary">
                        <h6 class="m-0 font-weight-bold text-white">
                            <i class="fas fa-bullhorn"></i> 向用户广播消息
                        </h6>
                    </div>
                    <div class="card-body">
                        <?php if(isset($message)) echo $message; ?>
                        
                        <div class="alert alert-info">
                            <h5><i class="fas fa-envelope"></i> 消息预览</h5>
                            <div class="message-preview">
                                <p><strong>Dear [用户名称],</strong></p>
                                <p><strong>Important Notice:</strong></p>
                                <ol>
                                    <li>All failed transactions will be deleted tonight at 12 AM</li>
                                    <li>Take backup before 12 PM if needed</li>
                                    <li>Current offer ends today</li>
                                </ol>
                                <p><strong>For details, WhatsApp: 9157455623</strong></p>
                                <p>Regards,<br>Support Team</p>
                            </div>
                        </div>
                        
                        <form method="post" onsubmit="return confirm('这将向所有活跃用户发送消息。继续吗？');">
                            <button type="submit" name="send_message" class="btn btn-primary btn-lg">
                                <i class="fas fa-paper-plane"></i> 发送广播消息
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
require_once('../database/footer.php');
?>