<?php
/**
 * Email Notification Helper Functions
 * Wrapper functions for easy email sending throughout the application
 */

require_once 'email_service.php';
require_once 'db_config.php';

/**
 * Get registration data by ID or registration number
 */
function getRegistrationData($identifier, $byRegistrationNumber = false) {
    try {
        $pdo = getDBConnection();
        
        if ($byRegistrationNumber) {
            $stmt = $pdo->prepare("SELECT * FROM registrations WHERE registration_number = ?");
        } else {
            $stmt = $pdo->prepare("SELECT * FROM registrations WHERE id = ?");
        }
        
        $stmt->execute([$identifier]);
        $registrationData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$registrationData) {
            return false;
        }
        
        // Get associated products for this registration (if any exist)
        try {
            $stmt = $pdo->prepare("
                SELECT rp.*, p.product_code, p.name, p.description, c.name as category_name 
                FROM registration_products rp
                LEFT JOIN products p ON rp.product_id = p.id
                LEFT JOIN product_categories c ON p.category_id = c.id
                WHERE rp.registration_id = ?
                ORDER BY c.display_order, p.id
            ");
            $stmt->execute([$registrationData['id']]);
            $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Organize products into sponsorships and otherSponsorships arrays
            $sponsorships = [];
            $otherSponsorships = [];
            
            foreach ($products as $product) {
                // Debug each product found
                error_log('Email Data: Product found - Code: ' . $product['product_code'] . ', Category: ' . $product['category_name'] . ', Quantity: ' . $product['quantity']);
                
                if ($product['category_name'] === 'Sponsorship') {
                    $sponsorships[] = [
                        'type' => $product['product_code'],
                        'count' => intval($product['quantity'])
                    ];
                } elseif ($product['category_name'] === 'Other Sponsorship') {
                    $otherSponsorships[] = [
                        'type' => $product['product_code'],
                        'count' => intval($product['quantity'])
                    ];
                }
            }
            
            // Add product arrays to registration data
            $registrationData['sponsorships'] = $sponsorships;
            $registrationData['otherSponsorships'] = $otherSponsorships;
            
            // Debug logging
            error_log('Email Data: Registration ' . $registrationData['id'] . ' has ' . count($sponsorships) . ' sponsorships and ' . count($otherSponsorships) . ' other sponsorships');
            error_log('Email Data: Found ' . count($products) . ' total products for registration ' . $registrationData['id']);
            
        } catch (Exception $productException) {
            // If product query fails, continue without products but log the error
            error_log('Failed to get products for registration ' . $registrationData['id'] . ': ' . $productException->getMessage());
            $registrationData['sponsorships'] = [];
            $registrationData['otherSponsorships'] = [];
        }
        
        return $registrationData;
        
    } catch (Exception $e) {
        error_log('Failed to get registration data: ' . $e->getMessage());
        return false;
    }
}

/**
 * Send pending registration email for bank transfers
 */
function sendPendingRegistrationEmail($registrationId) {
    $registrationData = getRegistrationData($registrationId);
    if (!$registrationData) {
        error_log("Cannot send pending registration email: Registration not found (ID: $registrationId)");
        return false;
    }
    
    // Only send for bank transfer registrations
    if ($registrationData['payment_method'] !== 'tt') {
        error_log("Pending registration email only for bank transfers (ID: $registrationId)");
        return false;
    }
    
    $emailService = new BrevoEmailService();
    return $emailService->sendPendingRegistrationEmail($registrationData);
}

/**
 * Send registration confirmation email (payment success)
 */
function sendRegistrationConfirmationEmail($registrationId) {
    $registrationData = getRegistrationData($registrationId);
    if (!$registrationData) {
        error_log("Cannot send confirmation email: Registration not found (ID: $registrationId)");
        return false;
    }
    
    $emailService = new BrevoEmailService();
    return $emailService->sendRegistrationConfirmationEmail($registrationData);
}

/**
 * Send registration confirmation email by registration number (for webhooks)
 */
function sendRegistrationConfirmationEmailByNumber($registrationNumber) {
    $registrationData = getRegistrationData($registrationNumber, true);
    if (!$registrationData) {
        error_log("Cannot send confirmation email: Registration not found (Number: $registrationNumber)");
        return false;
    }
    
    $emailService = new BrevoEmailService();
    return $emailService->sendRegistrationConfirmationEmail($registrationData);
}

/**
 * Send payment failure email
 */
function sendPaymentFailureEmail($registrationId, $failureReason = '') {
    $registrationData = getRegistrationData($registrationId);
    if (!$registrationData) {
        error_log("Cannot send payment failure email: Registration not found (ID: $registrationId)");
        return false;
    }
    
    $emailService = new BrevoEmailService();
    return $emailService->sendPaymentFailureEmail($registrationData, $failureReason);
}

/**
 * Send payment failure email by registration number (for webhooks)
 */
function sendPaymentFailureEmailByNumber($registrationNumber, $failureReason = '') {
    $registrationData = getRegistrationData($registrationNumber, true);
    if (!$registrationData) {
        error_log("Cannot send payment failure email: Registration not found (Number: $registrationNumber)");
        return false;
    }
    
    $emailService = new BrevoEmailService();
    return $emailService->sendPaymentFailureEmail($registrationData, $failureReason);
}

/**
 * Send payment reminder emails for pending registrations
 */
function sendPaymentReminders($reminderType = '24h') {
    try {
        $pdo = getDBConnection();
        
        // Calculate the time threshold based on reminder type
        $timeThresholds = [
            '24h' => '24 HOUR',
            '48h' => '48 HOUR', 
            '7d' => '7 DAY'
        ];
        
        $threshold = $timeThresholds[$reminderType] ?? '24 HOUR';
        
        // Get registrations that need reminders
        $stmt = $pdo->prepare("
            SELECT r.* 
            FROM registrations r 
            LEFT JOIN email_notifications en ON r.id = en.registration_id 
                AND en.email_type = ?
            WHERE r.payment_status = 'pending' 
            AND r.created_at <= DATE_SUB(NOW(), INTERVAL $threshold)
            AND en.id IS NULL
        ");
        
        $stmt->execute(['payment_reminder_' . $reminderType]);
        $registrations = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $emailService = new BrevoEmailService();
        $sentCount = 0;
        
        foreach ($registrations as $registration) {
            if ($emailService->sendPaymentReminderEmail($registration, $reminderType)) {
                $sentCount++;
            }
        }
        
        error_log("Sent $sentCount payment reminder emails ($reminderType)");
        return $sentCount;
        
    } catch (Exception $e) {
        error_log('Failed to send payment reminders: ' . $e->getMessage());
        return 0;
    }
}

/**
 * Send admin notification
 */
function sendAdminNotification($type, $registrationId, $additionalInfo = '') {
    $registrationData = getRegistrationData($registrationId);
    if (!$registrationData) {
        error_log("Cannot send admin notification: Registration not found (ID: $registrationId)");
        return false;
    }
    
    $emailService = new BrevoEmailService();
    return $emailService->sendAdminNotification($type, $registrationData, $additionalInfo);
}

/**
 * Send admin notification by registration number
 */
function sendAdminNotificationByNumber($type, $registrationNumber, $additionalInfo = '') {
    $registrationData = getRegistrationData($registrationNumber, true);
    if (!$registrationData) {
        error_log("Cannot send admin notification: Registration not found (Number: $registrationNumber)");
        return false;
    }
    
    $emailService = new BrevoEmailService();
    return $emailService->sendAdminNotification($type, $registrationData, $additionalInfo);
}

/**
 * Check if email has already been sent
 */
function hasEmailBeenSent($registrationId, $emailType) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("
            SELECT COUNT(*) 
            FROM email_notifications 
            WHERE registration_id = ? AND email_type = ? AND status = 'sent'
        ");
        $stmt->execute([$registrationId, $emailType]);
        return $stmt->fetchColumn() > 0;
        
    } catch (Exception $e) {
        error_log('Failed to check email status: ' . $e->getMessage());
        return false;
    }
}

/**
 * Get email notification history for a registration
 */
function getEmailHistory($registrationId) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("
            SELECT * 
            FROM email_notifications 
            WHERE registration_id = ? 
            ORDER BY sent_at DESC
        ");
        $stmt->execute([$registrationId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        error_log('Failed to get email history: ' . $e->getMessage());
        return [];
    }
}
?>
