<?php

use WHMCS\Database\Capsule;


$initPath = $_GET['initPath'].'/init.php';

// Path to WHMCS init.php
//$initPath = '/home/hostinoz/public_html/init.php';

// Check if init.php exists
if (!file_exists($initPath)) {
    error_log("WHMCS init.php file not found at $initPath.");
    exit("Error: WHMCS init.php file not found.");
}

// Include WHMCS init.php
require_once $initPath;

// Construct media URL

$invoicepath = 'https://'.$_GET['invoice'].'/pdf/';

$media_url = $invoicepath;
error_log($media_url);

//$media_url = 'https://hostinoz.com/pdf/';

try {
    // Fetch API configuration
    $config = Capsule::table('s10wa_config')->first();

    if ($config) {
        $apiUrl = $config->suiten_email;
        $apiKey = $config->suiten_apikey;
        $sender = $config->suiten_adminwa;

        error_log("API configuration fetched: URL = $apiUrl, API Key = $apiKey, Sender = $sender");

        // Fetch all unsent messages
        $messages = Capsule::table('s10wa_sendmsg')
            ->where('s10wa_status', 0)
            ->get();

        if ($messages->isEmpty()) {
            error_log("No unsent messages found.");
        } else {
            foreach ($messages as $message) {
                $id = $message->s10wa_sendid;
                $number = $message->s10wa_wanumber;
                $textMessage = $message->s10wa_message;
                $msgType = $message->s10wa_msgtype;
                $attachment = $message->s10wa_attachment;

                error_log("Processing message ID: $id, Number: $number, Message: $textMessage, MsgType: $msgType");

                if (!$id) {
                    error_log("Skipping message due to missing ID.");
                    continue;
                }

                // Prepare data for the API request
                $postData = [
                    'api_key' => $apiKey,
                    'sender'  => $sender,
                    'number'  => $number,
                    'message' => $textMessage,
                    'footer' => '',
                ];

                $apiEndpoint = '/send-message';
                $response = sendApiRequest($apiUrl . $apiEndpoint, $postData);

                if ($response['httpCode'] == 200 && $response['body']) {
                    error_log("Message ID $id sent successfully.");
                    Capsule::table('s10wa_sendmsg')
                        ->where('s10wa_sendid', $id)
                        ->update([
                            's10wa_status' => 1,
                            's10wa_statusdate' => Capsule::raw('NOW()')
                        ]);

                    if ($msgType == 2) { // If it's a media message
                        $mediaData = [
                            'api_key'    => $apiKey,
                            'sender'     => $sender,
                            'number'     => $number,
                            'media_type' => 'document',
                            'url'        => $media_url . $attachment,
                            'footer'   => '',
                        ];
                        $mediaResponse = sendApiRequest($apiUrl . '/send-media', $mediaData);
                        error_log("PDF Response: " . json_encode($mediaResponse));
                    }
                } else {
                    $errorMsg = $response['error'] ?: 'Failed to send message';
                    error_log("Failed to send message ID $id. Error: $errorMsg");

                    Capsule::table('s10wa_sendmsg')
                        ->where('s10wa_sendid', $id)
                        ->update([
                            's10wa_status' => 2,
                            's10wa_errormsg' => $errorMsg
                        ]);
                }
            }
        }
    } else {
        throw new Exception("Failed to fetch API configuration.");
    }
} catch (Exception $e) {
    error_log("Error: " . $e->getMessage());
}

// Utility function to send API requests
function sendApiRequest($url, $data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json; charset=UTF-8'
    ]);

    $responseBody = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    return [
        'httpCode' => $httpCode,
        'body'     => $responseBody,
        'error'    => $curlError
    ];
}

error_log("Script execution completed.");
