<?php
session_start();
include 'include.php';

$result = array();
$result['error'] = 1;
$result['error_msg'] = "Something went wrong";

// Get WhatsApp settings from database
$sql_whatsapp = "SELECT * FROM whatsapp_settings WHERE is_active = 1 LIMIT 1";
$res_whatsapp = getXbyY($sql_whatsapp);

if (empty($res_whatsapp) || empty($res_whatsapp[0]['api_key']) || empty($res_whatsapp[0]['sender_id'])) {
    $result['error'] = 1;
    $result['error_msg'] = "WhatsApp API is not configured. Please configure it in WhatsApp Settings.";
    echo json_encode($result);
    exit;
}

$api_key = $res_whatsapp[0]['api_key'];
$sender_id = $res_whatsapp[0]['sender_id'];
$api_url = "https://raspaysms.in/send-message";

if (isset($_POST['updte']) && $_POST['updte'] == 1) {
    $user_type = isset($_POST['user_type']) ? $_POST['user_type'] : '0';
    // Accept both 'phone_number' and 'mobile' parameters
    $phone_number = isset($_POST['phone_number']) ? trim($_POST['phone_number']) : '';
    if (empty($phone_number) && isset($_POST['mobile'])) {
        $phone_number = trim($_POST['mobile']);
    }
    $message = isset($_POST['message']) ? trim($_POST['message']) : '';
    $footer = isset($_POST['footer']) ? trim($_POST['footer']) : '';

    if (empty($message)) {
        $result['error'] = 1;
        $result['error_msg'] = "Message cannot be empty";
        echo json_encode($result);
        exit;
    }

    $numbers_to_send = array();
    $log_messages = array();

    // If specific phone number is provided
    if (!empty($phone_number)) {
        // Remove any non-numeric characters
        $phone_number = preg_replace('/[^0-9]/', '', $phone_number);
        // Add country code if not present (assuming India - 91)
        if (strlen($phone_number) == 10) {
            $phone_number = '91' . $phone_number;
        }
        $numbers_to_send[] = $phone_number;
    }

    // If user type is selected, get all users of that type
    if ($user_type != '0') {
        $con = connect_database();
        if ($user_type == 'All') {
            $sql = "SELECT mobile FROM users WHERE mobile IS NOT NULL AND mobile != '' AND is_active = 1";
        } else {
            $safe_user_type = mysqli_real_escape_string($con, $user_type);
            $sql = "SELECT mobile FROM users WHERE user_type = '$safe_user_type' AND mobile IS NOT NULL AND mobile != '' AND is_active = 1";
        }
        $res_users = getXbyY($sql);
        $con->close();

        foreach ($res_users as $user) {
            $mobile = preg_replace('/[^0-9]/', '', $user['mobile']);
            // Add country code if not present (assuming India - 91)
            if (strlen($mobile) == 10) {
                $mobile = '91' . $mobile;
            }
            if (!in_array($mobile, $numbers_to_send)) {
                $numbers_to_send[] = $mobile;
            }
        }
    }

    if (empty($numbers_to_send)) {
        $result['error'] = 1;
        $result['error_msg'] = "No valid phone numbers found to send message";
        echo json_encode($result);
        exit;
    }

    $success_count = 0;
    $fail_count = 0;

    foreach ($numbers_to_send as $number) {
        // Prepare API request
        $post_data = array(
            'api_key' => $api_key,
            'sender' => $sender_id,
            'number' => $number,
            'message' => $message
        );

        if (!empty($footer)) {
            $post_data['footer'] = $footer;
        }

        // Send API request using cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

        // Parse response
        $response_data = json_decode($response, true);

        if ($response_data && isset($response_data['status']) && $response_data['status'] == true) {
            $success_count++;
            $log_messages[] = "<span class='text-success'><i class='fas fa-check-circle'></i> " . $number . " - Sent successfully</span>";
        } else {
            $fail_count++;
            $error_msg = isset($response_data['msg']) ? $response_data['msg'] : 'Unknown error';
            $log_messages[] = "<span class='text-danger'><i class='fas fa-times-circle'></i> " . $number . " - Failed: " . $error_msg . "</span>";
        }

        // Small delay between messages to avoid rate limiting
        if (count($numbers_to_send) > 1) {
            usleep(500000); // 0.5 second delay
        }
    }

    // Prepare result
    $total = count($numbers_to_send);
    if ($success_count > 0) {
        $result['error'] = 0;
        $result['error_msg'] = "WhatsApp message sent successfully! (Success: $success_count / $total)";
        if ($fail_count > 0) {
            $result['error_msg'] .= " | Failed: $fail_count";
        }
    } else {
        $result['error'] = 1;
        $result['error_msg'] = "Failed to send WhatsApp message. Please check settings and try again.";
    }

    $result['log'] = implode("<br>", $log_messages);
    $result['success_count'] = $success_count;
    $result['fail_count'] = $fail_count;

} else {
    $result['error'] = 1;
    $result['error_msg'] = "Invalid request";
}

echo json_encode($result);
