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

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

$api_key = isset($_POST['api_key']) ? trim($_POST['api_key']) : '';
$sender_id = isset($_POST['sender_id']) ? trim($_POST['sender_id']) : '';
$test_number = isset($_POST['test_number']) ? trim($_POST['test_number']) : '';

if (empty($api_key) || empty($sender_id) || empty($test_number)) {
    $result['error'] = 1;
    $result['error_msg'] = "API Key, Sender ID, and Test Number are required";
    echo json_encode($result);
    exit;
}

// Clean the test number
$test_number = preg_replace('/[^0-9]/', '', $test_number);

$api_url = "https://raspaysms.in/send-message";

// Get site name
$site_name = isset($res_site[0]['site_name']) ? $res_site[0]['site_name'] : 'Your Site';

// Prepare test message
$test_message = "This is a test message from " . $site_name . " WhatsApp API integration. If you received this, your API is working correctly!";

$post_data = array(
    'api_key' => $api_key,
    'sender' => $sender_id,
    'number' => $test_number,
    'message' => $test_message,
    'footer' => 'Test Message - ' . date('Y-m-d H:i:s')
);

// 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);

if ($curl_error) {
    $result['error'] = 1;
    $result['error_msg'] = "Connection error: " . $curl_error;
    echo json_encode($result);
    exit;
}

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

if ($response_data && isset($response_data['status']) && $response_data['status'] == true) {
    $result['error'] = 0;
    $result['error_msg'] = "Test message sent successfully to " . $test_number . "! Check your WhatsApp.";
} else {
    $error_msg = isset($response_data['msg']) ? $response_data['msg'] : 'Unknown error';
    $result['error'] = 1;
    $result['error_msg'] = "Failed to send test message: " . $error_msg;
}

echo json_encode($result);
