<?php
// purchase_sms.php - Send SMS after purchase

require_once 'includes/config.php';
require_once 'includes/sms_config.php';

function sendPurchaseConfirmationSMS($user_id, $enrollment_id) {
    global $pdo, $sms;
    
    // Get user details
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
    
    // Get enrollment details
    $stmt = $pdo->prepare("
        SELECT e.*, 
               CASE 
                   WHEN e.course_id IS NOT NULL THEN c.title_bn
                   WHEN e.package_id IS NOT NULL THEN p.name_bn
               END as item_name
        FROM enrollments e
        LEFT JOIN courses c ON e.course_id = c.id
        LEFT JOIN packages p ON e.package_id = p.id
        WHERE e.id = ?
    ");
    $stmt->execute([$enrollment_id]);
    $enrollment = $stmt->fetch();
    
    if($user && $enrollment && !empty($user['phone'])) {
        $details = [
            'name' => $enrollment['item_name'] ?? 'কোর্স/প্যাকেজ',
            'amount' => $enrollment['amount_paid']
        ];
        
        // Send SMS
        $result = $sms->sendPurchaseConfirmation($user['phone'], $details);
        
        // Log SMS
        $stmt = $pdo->prepare("INSERT INTO sms_logs (user_id, phone, message, type, status) VALUES (?, ?, ?, 'purchase', ?)");
        $stmt->execute([$user_id, $user['phone'], "Purchase confirmation for enrollment #$enrollment_id", 'sent']);
        
        // Record confirmation
        $stmt = $pdo->prepare("INSERT INTO purchase_confirmations (enrollment_id, sms_sent, sms_message_id) VALUES (?, 1, ?)");
        $stmt->execute([$enrollment_id, $result]);
        
        return true;
    }
    
    return false;
}

// Usage example (call this after successful payment):
// sendPurchaseConfirmationSMS($user_id, $enrollment_id);
?>