<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once '../email_notifications.php';

// Require admin login with edit permission
$auth = new AdminAuth();
$auth->requireLogin();
$auth->requirePermission('dashboard', 'edit');

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    switch ($action) {
        case 'resend':
            $email_id = $input['email_id'] ?? '';
            if (empty($email_id)) {
                throw new Exception('Email ID is required');
            }
            
            $result = resendFailedEmail($email_id);
            echo json_encode(['success' => true, 'message' => 'Email resent successfully']);
            break;
            
        case 'mark_sent':
            $email_id = $input['email_id'] ?? '';
            if (empty($email_id)) {
                throw new Exception('Email ID is required');
            }
            
            $result = markEmailAsSent($email_id);
            echo json_encode(['success' => true, 'message' => 'Email marked as sent']);
            break;
            
        default:
            throw new Exception('Invalid action');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}

/**
 * Resend a failed email
 */
function resendFailedEmail($email_id) {
    $pdo = getDBConnection();
    
    // Get the failed email details
    $stmt = $pdo->prepare("
        SELECT en.*, r.*
        FROM email_notifications en
        LEFT JOIN registrations r ON en.registration_id = r.id
        WHERE en.id = ? AND en.status = 'failed'
    ");
    $stmt->execute([$email_id]);
    $email = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$email) {
        throw new Exception('Failed email not found');
    }
    
    // Determine which email function to call based on type
    $success = false;
    
    switch ($email['email_type']) {
        case 'pending_registration':
            if ($email['registration_id']) {
                $success = sendPendingRegistrationEmail($email['registration_id']);
            }
            break;
            
        case 'registration_confirmation':
            if ($email['registration_id']) {
                $success = sendRegistrationConfirmationEmail($email['registration_id']);
            }
            break;
            
        case 'payment_failure':
            if ($email['registration_id']) {
                $success = sendPaymentFailureEmail($email['registration_id']);
            }
            break;
            
        case 'payment_reminder_24h':
        case 'payment_reminder_48h':
        case 'payment_reminder_7d':
            // For reminders, we'll create a new entry rather than resend
            if ($email['registration_id']) {
                $reminderType = str_replace('payment_reminder_', '', $email['email_type']);
                $emailService = new BrevoEmailService();
                $success = $emailService->sendPaymentReminderEmail($email, $reminderType);
            }
            break;
            
        default:
            throw new Exception('Cannot resend this email type');
    }
    
    if (!$success) {
        throw new Exception('Failed to resend email');
    }
    
    // Mark the original email as resent (optional - you might want to keep the failed status)
    $stmt = $pdo->prepare("
        UPDATE email_notifications 
        SET error_message = CONCAT(IFNULL(error_message, ''), '\n[RESENT: ', NOW(), ']')
        WHERE id = ?
    ");
    $stmt->execute([$email_id]);
    
    return true;
}

/**
 * Manually mark an email as sent (for admin override)
 */
function markEmailAsSent($email_id) {
    $pdo = getDBConnection();
    
    $stmt = $pdo->prepare("
        UPDATE email_notifications 
        SET status = 'sent', error_message = CONCAT(IFNULL(error_message, ''), '\n[MANUALLY MARKED AS SENT: ', NOW(), ']')
        WHERE id = ?
    ");
    $stmt->execute([$email_id]);
    
    if ($stmt->rowCount() === 0) {
        throw new Exception('Email not found or already updated');
    }
    
    return true;
}
?>
