<?php
/**
 * sms_product.php — Digital Store SMS Notifications
 * Place at: /includes/sms_product.php
 *
 * Functions:
 *   sendProductPurchaseSms()    — sent to BUYER after successful M-Pesa payment
 *   sendProductCommissionSms()  — sent to each UPLINE who earned a commission
 *
 * Requires: sms.php (sendSms already loaded)
 */

if (!function_exists('sendProductPurchaseSms')):

/**
 * Send download confirmation SMS to buyer
 */
function sendProductPurchaseSms($buyerId, $productTitle, $downloadToken, $amountPaid = 0, $currencySymbol = 'KSh') {
    try {
        $conn = getConnection();
        $stmt = $conn->prepare("SELECT username, phone FROM users WHERE id=? LIMIT 1");
        $stmt->bind_param("i", $buyerId);
        $stmt->execute();
        $buyer = $stmt->get_result()->fetch_assoc();
        if (!$buyer || empty($buyer['phone'])) return false;

        $siteName = getSetting('site_name', 'QuickTasks');
        $siteUrl  = rtrim(defined('SITE_URL') ? SITE_URL : 'https://' . ($_SERVER['HTTP_HOST'] ?? 'localhost'), '/');
        $dlUrl    = $siteUrl . '/user/download.php?token=' . urlencode($downloadToken);
        $amtF     = $currencySymbol . ' ' . number_format(floatval($amountPaid), 2);

        $message = "{$siteName}: Hi {$buyer['username']}! Purchase confirmed. "
                 . "You paid {$amtF} for \"{$productTitle}\". "
                 . "Download here: {$dlUrl}";

        // Trim to 306 chars (2 SMS parts) if too long — shorten URL note
        if (strlen($message) > 306) {
            $message = "{$siteName}: Purchase confirmed! \"{$productTitle}\" — {$amtF}. "
                     . "Download: {$dlUrl}";
        }

        $result = sendSms($buyer['phone'], $message);
        return $result['success'];

    } catch (Exception $e) {
        error_log("sendProductPurchaseSms error: " . $e->getMessage());
        return false;
    }
}

endif;


if (!function_exists('sendProductCommissionSms')):

/**
 * Send commission credit SMS to upline member
 */
function sendProductCommissionSms($recipientId, $buyerUsername, $productTitle, $commissionAmount, $level = 1, $currencySymbol = 'KSh') {
    try {
        $conn = getConnection();
        $stmt = $conn->prepare("SELECT username, phone FROM users WHERE id=? LIMIT 1");
        $stmt->bind_param("i", $recipientId);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        if (!$user || empty($user['phone'])) return false;

        $siteName = getSetting('site_name', 'QuickTasks');
        $amtF     = $currencySymbol . ' ' . number_format(floatval($commissionAmount), 2);

        $message = "{$siteName}: Level {$level} store commission! "
                 . "{$buyerUsername} bought \"{$productTitle}\". "
                 . "{$amtF} credited to your Main Wallet.";

        $result = sendSms($user['phone'], $message);
        return $result['success'];

    } catch (Exception $e) {
        error_log("sendProductCommissionSms error: " . $e->getMessage());
        return false;
    }
}

endif;


// ── Compatibility aliases — existing code calling email versions will use SMS ─

if (!function_exists('sendProductPurchaseEmail')):
function sendProductPurchaseEmail($buyerId, $productTitle, $downloadToken, $amountPaid = 0, $currencySymbol = 'KSh') {
    return sendProductPurchaseSms($buyerId, $productTitle, $downloadToken, $amountPaid, $currencySymbol);
}
endif;

if (!function_exists('sendProductCommissionEmail')):
function sendProductCommissionEmail($recipientId, $buyerUsername, $productTitle, $commissionAmount, $level = 1, $currencySymbol = 'KSh') {
    return sendProductCommissionSms($recipientId, $buyerUsername, $productTitle, $commissionAmount, $level, $currencySymbol);
}
endif;