<?php

function handleOther($conn, $number, $message, $timestamp) {
    // Determine if the message is from a group or a private chat
    $isGroup = strpos($number, '@g.us') !== false; // Check if the number contains '@g.us'

    if ($isGroup) {
        $normalizedMessage = strtolower($message);
        if ($normalizedMessage === "help") {
            // Respond to the group asking for general help
            sendWhatsAppMessage($number, "Please describe your issue in detail, and our team will review it as soon as possible. Thank you!");

            // Notify the team in a specific group
            $helpGroupId = '120363376465503407@g.us'; // Replace with your actual group ID
            $notificationMessage = "Help needed: A user in group $number has requested assistance.";
            sendWhatsAppMessage($helpGroupId, $notificationMessage);
        } else {
            // Inform about correct usage within the group
            $responseMessage = "We couldn't understand your request. Please use one of the following formats:\n" .
                               "- order_id speed up\n" .
                               "- order_id cancel\n" .
                               "- order_id refill\n" .
                               "- order_id less delivery\n" .
                               "- order_id not started\n" .
                               "If you need further assistance, please type 'help'.";
            sendWhatsAppMessage($number, $responseMessage);
        }
    }

    // Log the unhandled message for review
    error_log("Unhandled message from $number at $timestamp: $message");
}

function sendWhatsAppMessage($number, $message) {
    // Ensure number is in the correct format without '@c.us'
    $formattedNumber = str_replace('@c.us', '', $number); // Strip out the suffix if present

    $url = 'http://147.93.136.172:3001/send-group';
    $data = json_encode(["groupId" => $formattedNumber, "message" => $message]);
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    
    if ($err = curl_error($ch)) {
        error_log("Curl error in sendWhatsAppMessage to $formattedNumber: $err");
    } else {
        $responseData = json_decode($response, true);
        if (isset($responseData['error'])) {
            error_log("Failed to send message to $formattedNumber: " . json_encode($responseData));
        } else {
            error_log("Success other handler sending message to $formattedNumber: " . $response);
        }
    }
    curl_close($ch);
}



?>
