<?php
include('../../config/database.php');
header('Content-Type: application/json');

function sendSMS($recipients, $message) {
    $endPoint = 'https://api.mnotify.com/api/sms/quick';
    $apiKey = 'jv1ZgHaszsAKtS3Y4QlSFvUfJ';
    $url = $endPoint . '?key=' . $apiKey;
    $data = [
        'recipient' => $recipients,
        'sender' => 'iHub',
        'message' => $message,
        'is_schedule' => 'false',
        'schedule_date' => ''
    ];

    $ch = curl_init();
    $headers = array("Content-Type: application/json");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $result = curl_exec($ch);

    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        return [
            'status' => 'error',
            'message' => $error_msg
        ];
    }

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $result = json_decode($result, TRUE);
    curl_close($ch);

    return [
        'status' => $http_code == 200 ? 'success' : 'error',
        'result' => $result,
        'http_code' => $http_code
    ];
}

$data = json_decode(file_get_contents('php://input'), true);
$phones = $data['phones'];
$names = $data['names'];
$action = $data['action'];

$results = [];
foreach ($phones as $index => $phone) {
    $name = $names[$index];
    if ($action === 'accept') {
        $message = "Dear $name, congratulations! Your business idea has been accepted to the next round of the iHub competition. We are excited to see your progress. Best wishes, iHub Team";
    } else {
        $message = "Dear $name, thank you for submitting your business idea to the iHub competition. After careful consideration, we regret to inform you that your proposal was not selected for the next round. We encourage you to continue developing your idea and wish you the best in your future endeavors. Sincerely, iHub Team";
    }

    $results[] = sendSMS([$phone], $message);
}

echo json_encode($results);
?>
