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

// Require admin login with view permission
requirePermission('registrations', 'view');

/**
 * Format email type for display
 */
function formatEmailType($emailType) {
    $types = [
        'pending_registration' => 'Pending Registration',
        'registration_confirmation' => 'Registration Confirmation',
        'payment_failure' => 'Payment Failed',
        'payment_reminder_24h' => 'Payment Reminder (24h)',
        'payment_reminder_48h' => 'Payment Reminder (48h)',
        'payment_reminder_7d' => 'Payment Reminder (7 days)',
        'admin_notification' => 'Admin Notification'
    ];
    
    return $types[$emailType] ?? ucwords(str_replace('_', ' ', $emailType));
}

$currentPage = 'registrations';

$registration_id = $_GET['id'] ?? '';
$message = '';
$error = '';

if (empty($registration_id)) {
    header('Location: registrations.php');
    exit;
}

// Handle payment status update (only for users with edit permission)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_payment_status']) && hasPermission('payments', 'edit')) {
    try {
        $pdo = getDBConnection();
        $logger = new RegistrationLogger($pdo, $_SESSION['admin_user'] ?? null);
        $new_status = $_POST['payment_status'] ?? '';
        $admin_notes = $_POST['override_notes'] ?? '';
        $force_override = isset($_POST['force_override']) && $_POST['force_override'] === '1';
        
        // SECURITY: Only super_admin can use force override
        if ($force_override && getCurrentUserRole() !== 'super_admin') {
            throw new Exception('Force override is only available to Super Administrators. Please contact a super admin if you need to bypass validation rules.');
        }
        
        if (empty($new_status)) {
            throw new Exception('Payment status is required');
        }
        
        // Get full registration data for validation
        $stmt = $pdo->prepare("SELECT id, payment_status, payment_method, registration_number, total_amount FROM registrations WHERE " . 
            (is_numeric($registration_id) ? "id = ?" : "registration_number = ?"));
        $stmt->execute([$registration_id]);
        $oldRegistrationData = $stmt->fetch(PDO::FETCH_ASSOC);
        $old_status = $oldRegistrationData['payment_status'] ?? 'unknown';
        $payment_method = $oldRegistrationData['payment_method'] ?? '';
        $reg_number = $oldRegistrationData['registration_number'] ?? $registration_id;
        $total_amount = $oldRegistrationData['total_amount'] ?? 0;
        $numeric_reg_id = $oldRegistrationData['id'] ?? null;
        
        // VALIDATION: Prevent invalid status changes to 'complimentary'
        if ($new_status === 'complimentary' && !$force_override) {
            $validation_errors = [];
            
            // Scenario 1: Block if already paid via online gateway
            if ($payment_method === 'gateway' && $old_status === 'paid') {
                $validation_errors[] = "Cannot change to complimentary - payment already processed through online gateway (Stripe). Money has been collected. If you need to make this registration complimentary, please issue a refund through Stripe first, or use the 'Force Override' option with justification.";
            }
            
            // Scenario 2: Block if registration has paid products (total > 0)
            if ($total_amount > 0) {
                $validation_errors[] = "Cannot change to complimentary - registration includes paid products (Total: $" . number_format($total_amount, 2) . "). To make this complimentary, you need to adjust product prices to $0 first, or use the 'Force Override' option with justification.";
            }
            
            if (!empty($validation_errors)) {
                throw new Exception(implode(' ', $validation_errors));
            }
        }
        
        // If force override is used, require admin notes
        if ($force_override && empty($admin_notes)) {
            throw new Exception('Override notes are required when forcing a status change. Please explain why you are overriding the validation rules.');
        }
        
        // Log override if used
        if ($force_override) {
            error_log("Admin Override: User {$_SESSION['admin_user']['username']} forced payment status change from $old_status to $new_status for registration $reg_number. Notes: $admin_notes");
        }
        
        // Update payment status
        $stmt = $pdo->prepare("
            UPDATE registrations 
            SET payment_status = ?, updated_at = CURRENT_TIMESTAMP 
            WHERE " . (is_numeric($registration_id) ? "id = ?" : "registration_number = ?") . "
        ");
        $stmt->execute([$new_status, $registration_id]);
        
        // Log payment status update - use numeric ID for logging
        $logger->logPaymentStatusUpdate($numeric_reg_id, $reg_number, $old_status, $new_status, $total_amount);
        
        // Send webhook notification for payment status change
        try {
            require_once '../webhook_service.php';
            $webhookService = new WebhookService($pdo);
            
            // Get full registration data
            $fullRegistrationData = $webhookService->getFullRegistrationData($numeric_reg_id);
            
            $webhookData = [
                'event_type' => 'payment_status_changed',
                'trigger' => 'admin_update',
                'payment_status' => $new_status,
                'previous_payment_status' => $old_status,
                'admin_info' => [
                    'updated_by' => $_SESSION['admin_user']['username'] ?? 'admin',
                    'admin_id' => $_SESSION['admin_user']['id'] ?? null,
                    'admin_full_name' => $_SESSION['admin_user']['full_name'] ?? 'Unknown Admin'
                ],
                'updated_at' => date('c')
            ];
            
            // Merge with full registration data
            if ($fullRegistrationData) {
                $webhookData = array_merge($webhookData, $fullRegistrationData);
            }
            
            $webhookService->sendWebhook('payment_status_changed', $webhookData, $numeric_reg_id);
            error_log("Admin payment status webhook: Sent comprehensive webhook for registration $reg_number: $old_status -> $new_status");
        } catch (Exception $e) {
            error_log('Webhook notification failed for payment status change: ' . $e->getMessage());
            // Don't fail the payment update if webhook fails
        }
        
        // Log the status change in payment_transactions table
        $stmt = $pdo->prepare("
            SELECT id, total_amount FROM registrations WHERE " . 
            (is_numeric($registration_id) ? "id = ?" : "registration_number = ?")
        );
        $stmt->execute([$registration_id]);
        
        $reg_id = null; // Initialize variable outside the if block
        if ($registration_data = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $reg_id = $registration_data['id'];
            $total_amount = $registration_data['total_amount'];
            
            // Map registration payment status to transaction status
            $transaction_status_map = [
                'paid' => 'completed',
                'complimentary' => 'completed',  // Complimentary also treated as completed (no payment needed)
                'pending' => 'pending', 
                'failed' => 'failed',
                'expired' => 'cancelled',
                'cancelled' => 'cancelled'
            ];
            $transaction_status = $transaction_status_map[$new_status] ?? 'pending';
            
            $stmt = $pdo->prepare("
                INSERT INTO payment_transactions (
                    registration_id, transaction_type, transaction_status, 
                    amount, transaction_reference, bank_confirmation
                ) VALUES (?, 'admin_update', ?, ?, ?, ?)
            ");
            $stmt->execute([
                $reg_id, 
                $transaction_status, 
                $total_amount,
                $registration_id, 
                $admin_notes
            ]);
        }
        
        // Auto-confirm stock status and send email if status changed to 'paid'
        if ($new_status === 'paid' && $reg_id) {
            // Auto-confirm stock status for all products in this registration
            $stockStmt = $pdo->prepare("
                UPDATE registration_products 
                SET stock_status = 'confirmed', 
                    confirmed_at = NOW(),
                    updated_at = NOW()
                WHERE registration_id = ? AND stock_status = 'reserved'
            ");
            $stockResult = $stockStmt->execute([$reg_id]);
            $stockRowsUpdated = $stockStmt->rowCount();
            error_log("Admin Payment Update: Auto-confirmed $stockRowsUpdated product stock items for registration $registration_id");
            
            // Log stock confirmation
            if ($stockRowsUpdated > 0) {
                $logger->logStockConfirmation($reg_id, $reg_number, $stockRowsUpdated);
            }
            
            // Update product stock counts
            if ($stockRowsUpdated > 0) {
                $productStmt = $pdo->prepare("
                    SELECT DISTINCT product_id FROM registration_products WHERE registration_id = ?
                ");
                $productStmt->execute([$reg_id]);
                $productIds = $productStmt->fetchAll(PDO::FETCH_COLUMN);
                
                foreach ($productIds as $productId) {
                    $updateStockStmt = $pdo->prepare("
                        UPDATE products SET 
                            sold_stock = (
                                SELECT COALESCE(SUM(quantity), 0) 
                                FROM registration_products 
                                WHERE product_id = ? AND stock_status = 'confirmed'
                            ),
                            reserved_stock = (
                                SELECT COALESCE(SUM(quantity), 0) 
                                FROM registration_products 
                                WHERE product_id = ? AND stock_status = 'reserved'
                            )
                        WHERE id = ?
                    ");
                    $updateStockStmt->execute([$productId, $productId, $productId]);
                }
                error_log("Admin Payment Update: Updated stock counts for " . count($productIds) . " products");
            }
            
            try {
                error_log("Admin Payment Update: Attempting to send confirmation email for registration ID: $reg_id");
                require_once '../email_notifications.php';
                $emailSent = sendRegistrationConfirmationEmail($reg_id);
                error_log("Admin Payment Update: Email send result: " . ($emailSent ? 'SUCCESS' : 'FAILED'));
                
                // Log email sending attempt
                if ($emailSent) {
                    $logger->logEmailSent($reg_id, $reg_number, 'registration_confirmation', $oldRegistrationData['contact_email'] ?? 'unknown', 'Registration Confirmation');
                } else {
                    $logger->logEmailFailure($reg_id, $reg_number, 'registration_confirmation', $oldRegistrationData['contact_email'] ?? 'unknown', 'Failed to send confirmation email after payment update');
                }
                
                if ($emailSent) {
                    // Send admin notification for payment received
                    sendAdminNotification('payment_received', $reg_id, 'Payment manually confirmed by admin');
                    $message = "Payment status updated to 'Paid', stock confirmed, and confirmation email sent successfully!";
                } else {
                    $message = "Payment status updated to 'Paid' and stock confirmed, but failed to send confirmation email.";
                }
            } catch (Exception $e) {
                error_log('Failed to send confirmation email after admin payment update: ' . $e->getMessage());
                // Redirect even if email fails
                header("Location: registration-details.php?id=" . $registration_id . "&success=payment_updated_email_failed&status=" . urlencode($new_status));
                exit();
            }
            // Redirect after successful payment update with email
            header("Location: registration-details.php?id=" . $registration_id . "&success=payment_updated_with_email&status=" . urlencode($new_status));
            exit();
        } else {
            // Redirect to prevent form resubmission
            header("Location: registration-details.php?id=" . $registration_id . "&success=payment_updated&status=" . urlencode($new_status));
            exit();
        }
        
    } catch (Exception $e) {
        $error = "Error updating payment status: " . $e->getMessage();
    }
}

try {
    $pdo = getDBConnection();
    $logger = new RegistrationLogger($pdo, $_SESSION['admin_user'] ?? null);
    
    // Get registration details - try by ID first, then by registration_number
    $stmt = $pdo->prepare("
        SELECT * FROM registrations 
        WHERE " . (is_numeric($registration_id) ? "id = ?" : "registration_number = ?")
    );
    $stmt->execute([$registration_id]);
    $registration = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$registration) {
        throw new Exception("Registration not found");
    }
    
    
    // Get delegates for this registration
    $stmt = $pdo->prepare("
        SELECT * FROM delegates 
        WHERE registration_id = ?
        ORDER BY id
    ");
    $stmt->execute([$registration['id']]);
    $delegates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get payment transactions
    $stmt = $pdo->prepare("
        SELECT * FROM payment_transactions 
        WHERE registration_id = ?
        ORDER BY created_at DESC
    ");
    $stmt->execute([$registration['id']]);
    $payments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get purchased products
    $stmt = $pdo->prepare("
        SELECT rp.*, p.name as product_name, p.product_code, pc.name as category, pc.id as category_id
        FROM registration_products rp 
        JOIN products p ON rp.product_id = p.id 
        LEFT JOIN product_categories pc ON p.category_id = pc.id
        WHERE rp.registration_id = ?
        ORDER BY pc.name, p.name
    ");
    $stmt->execute([$registration['id']]);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = "Error: " . $e->getMessage();
}

// Handle error messages from redirect
if (isset($_GET['error'])) {
    $error = urldecode($_GET['error']);
}

// Handle success messages from redirect
if (isset($_GET['success'])) {
    switch ($_GET['success']) {
        case 'contact_updated':
            $success = "Contact information updated successfully!";
            break;
        case 'admin_notes_updated':
            $success = "Admin notes updated successfully!";
            break;
        case 'payment_updated':
            $status = $_GET['status'] ?? 'unknown';
            $success = "Payment status updated successfully to: " . ucfirst($status);
            break;
        case 'payment_updated_with_email':
            $status = $_GET['status'] ?? 'unknown';
            $success = "Payment status updated to '" . ucfirst($status) . "', stock confirmed, and confirmation email sent successfully!";
            break;
        case 'payment_updated_email_failed':
            $status = $_GET['status'] ?? 'unknown';
            $success = "Payment status updated to '" . ucfirst($status) . "' and stock confirmed, but email notification failed.";
            break;
        case 'product_changed':
            $oldProduct = $_GET['old_product'] ?? 'Unknown';
            $newProduct = $_GET['new_product'] ?? 'Unknown';
            $priceDiff = floatval($_GET['price_diff'] ?? 0);
            $delegateUpdate = $_GET['delegate_update'] ?? '';
            $success = "Product successfully changed from '{$oldProduct}' to '{$newProduct}'";
            if ($priceDiff != 0) {
                $diffText = $priceDiff > 0 ? "+$" . number_format($priceDiff, 2) : "-$" . number_format(abs($priceDiff), 2);
                $success .= " (Price difference: {$diffText})";
            }
            $success .= ". Registration total amount has been updated accordingly.";
            if ($delegateUpdate === 'true') {
                $success .= " Delegate count has also been recalculated based on delegate products.";
            }
            break;
    }
}

// Handle registration deletion (only for users with delete permission)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_registration']) && hasPermission('registrations', 'delete')) {
    try {
        $pdo = getDBConnection();
        $logger = new RegistrationLogger($pdo, $_SESSION['admin_user'] ?? null);
        
        // Get registration details for logging before deletion
        $stmt = $pdo->prepare("SELECT * FROM registrations WHERE " . 
            (is_numeric($registration_id) ? "id = ?" : "registration_number = ?"));
        $stmt->execute([$registration_id]);
        $regData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$regData) {
            throw new Exception('Registration not found');
        }
        
        // Check if payment status is 'cancelled' - only allow deletion for cancelled registrations
        if ($regData['payment_status'] !== 'cancelled') {
            throw new Exception('Registration can only be deleted when payment status is \'Cancelled\'. Current status: ' . ucfirst($regData['payment_status']));
        }
        
        $regId = $regData['id'];
        $regNumber = $regData['registration_number'];
        
        // Start transaction for safe deletion
        $pdo->beginTransaction();
        
        try {
            // 1. Delete from registration_products (and update product stock)
            $stmt = $pdo->prepare("SELECT product_id, quantity FROM registration_products WHERE registration_id = ?");
            $stmt->execute([$regId]);
            $registrationProducts = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Update product stock counts before deleting registration_products
            foreach ($registrationProducts as $regProduct) {
                $productId = $regProduct['product_id'];
                
                // Recalculate stock after removing this registration's products
                // Note: available_stock is a generated column, so we only update base columns
                $updateStockStmt = $pdo->prepare("
                    UPDATE products SET 
                        sold_stock = (
                            SELECT COALESCE(SUM(quantity), 0) 
                            FROM registration_products 
                            WHERE product_id = ? AND stock_status = 'confirmed' AND registration_id != ?
                        ),
                        reserved_stock = (
                            SELECT COALESCE(SUM(quantity), 0) 
                            FROM registration_products 
                            WHERE product_id = ? AND stock_status = 'reserved' AND registration_id != ?
                        )
                    WHERE id = ?
                ");
                $updateStockStmt->execute([$productId, $regId, $productId, $regId, $productId]);
            }
            
            // Delete registration_products
            $stmt = $pdo->prepare("DELETE FROM registration_products WHERE registration_id = ?");
            $stmt->execute([$regId]);
            
            // 2. Delete from payment_transactions
            $stmt = $pdo->prepare("DELETE FROM payment_transactions WHERE registration_id = ?");
            $stmt->execute([$regId]);
            
            // 3. Delete from registration_activity_log
            $stmt = $pdo->prepare("DELETE FROM registration_activity_log WHERE registration_id = ?");
            $stmt->execute([$regId]);
            
            // 4. Delete from product_stock_movements
            $stmt = $pdo->prepare("DELETE FROM product_stock_movements WHERE registration_id = ?");
            $stmt->execute([$regId]);
            
            // 5. Delete from product_activity_log
            $stmt = $pdo->prepare("DELETE FROM product_activity_log WHERE registration_id = ?");
            $stmt->execute([$regId]);
            
            // 6. Delete the main registration record (delegates and email_notifications will cascade)
            $stmt = $pdo->prepare("DELETE FROM registrations WHERE id = ?");
            $stmt->execute([$regId]);
            
            // Log the deletion
            $logger->logRegistrationDeletion($regId, $regNumber, $regData['contact_email'], $regData['total_amount']);
            
            // Commit transaction
            $pdo->commit();
            
            // Redirect to registrations list with success message
            header("Location: registrations.php?success=registration_deleted&reg_number=" . urlencode($regNumber));
            exit();
            
        } catch (Exception $e) {
            $pdo->rollback();
            throw $e;
        }
        
    } catch (Exception $e) {
        $error = "Error deleting registration: " . $e->getMessage();
    }
}

// Handle admin notes update
if (isset($_POST['action']) && $_POST['action'] === 'update_admin_notes' && isset($_POST['registration_id'])) {
    try {
        // Get old admin notes for logging
        $stmt = $pdo->prepare("SELECT admin_notes, registration_number FROM registrations WHERE id = ?");
        $stmt->execute([$_POST['registration_id']]);
        $oldData = $stmt->fetch(PDO::FETCH_ASSOC);
        $oldNotes = $oldData['admin_notes'] ?? '';
        $regNumber = $oldData['registration_number'] ?? $_POST['registration_id'];
        
        $stmt = $pdo->prepare("
            UPDATE registrations 
            SET admin_notes = ?, updated_at = NOW()
            WHERE id = ?
        ");
        
        $stmt->execute([
            $_POST['admin_notes'],
            $_POST['registration_id']
        ]);
        
        if ($stmt->rowCount() > 0) {
            // Log admin notes update
            $logger->logAdminNotesUpdate($_POST['registration_id'], $regNumber, $oldNotes, $_POST['admin_notes']);
            
            // Redirect to prevent form resubmission
            header("Location: registration-details.php?id=" . $_POST['registration_id'] . "&success=admin_notes_updated");
            exit();
        } else {
            $error = "No changes were made to the admin notes.";
        }
    } catch (Exception $e) {
        $error = "Error updating admin notes: " . $e->getMessage();
    }
}

// Handle contact information update
if (isset($_POST['action']) && $_POST['action'] === 'update_contact' && isset($_POST['registration_id'])) {
    try {
        // Get old contact data for logging
        $stmt = $pdo->prepare("
            SELECT contact_full_name, contact_designation, contact_department, contact_email, 
                   contact_mobile, university_name, country, registration_number 
            FROM registrations WHERE id = ?
        ");
        $stmt->execute([$_POST['registration_id']]);
        $oldContactData = $stmt->fetch(PDO::FETCH_ASSOC);
        $regNumber = $oldContactData['registration_number'] ?? $_POST['registration_id'];
        
        // Prepare new contact data
        $newContactData = [
            'contact_full_name' => $_POST['contact_full_name'],
            'contact_designation' => $_POST['contact_designation'],
            'contact_department' => $_POST['contact_department'],
            'contact_email' => $_POST['contact_email'],
            'contact_mobile' => $_POST['contact_mobile'],
            'university_name' => $_POST['university_name'],
            'country' => $_POST['country']
        ];
        
        $stmt = $pdo->prepare("
            UPDATE registrations 
            SET contact_full_name = ?, contact_designation = ?, contact_department = ?, 
                contact_email = ?, contact_mobile = ?, university_name = ?, country = ?,
                updated_at = NOW()
            WHERE id = ?
        ");
        
        $stmt->execute([
            $_POST['contact_full_name'],
            $_POST['contact_designation'],
            $_POST['contact_department'],
            $_POST['contact_email'],
            $_POST['contact_mobile'],
            $_POST['university_name'],
            $_POST['country'],
            $_POST['registration_id']
        ]);
        
        if ($stmt->rowCount() > 0) {
            // Log contact information update
            $logger->logContactUpdate($_POST['registration_id'], $regNumber, $oldContactData, $newContactData);
            
            // Redirect to prevent form resubmission
            header("Location: registration-details.php?id=" . $_POST['registration_id'] . "&success=contact_updated");
            exit();
        } else {
            $error = "No changes were made to the contact information.";
        }
    } catch (Exception $e) {
        $error = "Error updating contact information: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo isset($registration['registration_number']) ? 'Registration ' . htmlspecialchars($registration['registration_number']) . ' - Details' : 'Registration Details'; ?> - Xchange Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <!--
        .admin-header {
            background: white;
            padding: 20px 0;
            border-bottom: 1px solid var(--slate-200);
            margin-bottom: 32px;
        }
        
        .admin-nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .admin-nav h1 {
            margin: 0;
            color: var(--slate-800);
        }
        
        .admin-nav .nav-links {
            display: flex;
            gap: 20px;
            align-items: center;
        }
        
        .admin-nav .nav-links a {
            color: var(--slate-600);
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 6px;
            transition: all 0.2s;
        }
        
        .admin-nav .nav-links a:hover {
            background: var(--slate-100);
            color: var(--slate-800);
        }
        
        .admin-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px 60px 20px;
            min-height: calc(100vh - 120px);
        }
        
        .breadcrumb {
            margin-bottom: 24px;
            font-size: 14px;
            color: var(--slate-500);
        }
        
        .breadcrumb a {
            color: var(--indigo-600);
            text-decoration: none;
        }
        
        .details-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
            margin-bottom: 32px;
        }
        
        .details-card {
            background: white;
            padding: 24px;
            border-radius: 12px;
            box-shadow: var(--shadow);
        }
        
        .details-card h3 {
            margin: 0 0 16px 0;
            color: var(--slate-800);
            border-bottom: 2px solid var(--indigo-500);
            padding-bottom: 8px;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid var(--slate-100);
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            font-weight: 600;
            color: var(--slate-600);
        }
        
        .detail-value {
            color: var(--slate-800);
        }
        
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-pending {
            background: var(--yellow-100);
            color: var(--yellow-700);
        }
        
        .status-paid {
            background: var(--green-100);
            color: var(--green-700);
        }
        
        .status-failed {
            background: var(--red-100);
            color: var(--red-700);
        }
        
        .status-expired {
            background: var(--slate-100);
            color: var(--slate-700);
        }
        
        .delegates-table {
            background: white;
            border-radius: 12px;
            box-shadow: var(--shadow);
            overflow: hidden;
            margin-bottom: 24px;
        }
        
        .delegates-table h3 {
            padding: 24px;
            margin: 0;
            border-bottom: 1px solid var(--slate-200);
            background: var(--slate-50);
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .table th,
        .table td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid var(--slate-200);
        }
        
        .table th {
            background: var(--slate-50);
            font-weight: 600;
            color: var(--slate-700);
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .table td {
            color: var(--slate-600);
            font-size: 14px;
        }
        
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <div class="breadcrumb">
            <a href="dashboard.php">Dashboard</a> / 
            <a href="registrations.php">Registrations</a> / 
            <?php echo htmlspecialchars($registration_id); ?>
        </div>
        
        <!-- Page Header with Actions -->
        <div class="page-header">
            <h1 class="page-title">Registration Details</h1>
            <div class="page-actions">
                <a href="registration-activity-log.php?registration_id=<?php echo urlencode($registration_id); ?>" 
                   target="_blank" 
                   class="btn btn-outline-secondary action-btn"
                   title="View Activity Log for this Registration">
                    <i class="fas fa-history"></i> Activity Log
                </a>
                <a href="generate_invoice.php?id=<?php echo urlencode($registration_id); ?>" 
                   target="_blank" 
                   class="btn btn-primary action-btn">
                    <i class="fas fa-file-invoice"></i> Generate Invoice
                </a>
                <?php
                // Generate security hash for public invoice
                $securityHash = md5($registration['registration_number'] . $registration['contact_email'] . $registration['created_at']);
                $publicInvoiceUrl = '../public_invoice.php?id=' . urlencode($registration['registration_number']) . '&hash=' . urlencode($securityHash);
                ?>
                <a href="<?php echo $publicInvoiceUrl; ?>" 
                   target="_blank" 
                   class="btn btn-secondary action-btn ml-2" 
                   data-toggle="tooltip" 
                   title="Share this link with the customer">
                    <i class="fas fa-link"></i> Public Invoice Link
                </a>
                <button class="btn btn-outline-secondary action-btn ml-2" 
                        onclick="copyToClipboard('<?php echo $publicInvoiceUrl; ?>')" 
                        data-toggle="tooltip" 
                        title="Copy public invoice URL to clipboard">
                    <i class="fas fa-copy"></i> Copy URL
                </button>
                <button onclick="window.print(); logPrintAction();" 
                        class="btn btn-outline-secondary action-btn ml-2"
                        title="Print registration details">
                    <i class="fas fa-print"></i> Print Details
                </button>
                <script>
                function copyToClipboard(text) {
                    const input = document.createElement('input');
                    input.style.position = 'fixed';
                    input.style.opacity = 0;
                    input.value = text;
                    document.body.appendChild(input);
                    input.select();
                    document.execCommand('copy');
                    document.body.removeChild(input);
                    
                    // Show feedback
                    alert('Public invoice URL copied to clipboard!');
                }
                
                function confirmDeleteRegistration() {
                    const regNumber = '<?php echo htmlspecialchars($registration['registration_number']); ?>';
                    const regId = '<?php echo htmlspecialchars($registration_id); ?>';
                    
                    if (confirm(`Are you sure you want to delete registration ${regNumber}?\n\nThis action will permanently delete:\n• Registration record\n• All delegate information\n• Payment transactions\n• Email history\n• Product purchases\n• Activity logs\n\nNote: Only registrations with 'Cancelled' payment status can be deleted.\n\nThis action CANNOT be undone!`)) {
                        if (confirm('This is your final warning. Are you absolutely sure you want to delete this registration?')) {
                            // Create and submit delete form
                            const form = document.createElement('form');
                            form.method = 'POST';
                            form.style.display = 'none';
                            
                            const deleteInput = document.createElement('input');
                            deleteInput.type = 'hidden';
                            deleteInput.name = 'delete_registration';
                            deleteInput.value = '1';
                            
                            form.appendChild(deleteInput);
                            document.body.appendChild(form);
                            form.submit();
                        }
                    }
                }
                </script>
            </div>
        </div>
        
        <?php if (!empty($error)): ?>
            <div class="alert alert-error mb-4"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <?php if (!empty($message)): ?>
            <div class="alert alert-success mb-4"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        
        <?php if (!empty($success)): ?>
            <div class="alert alert-success mb-4"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        
        <?php if (!isset($error) || empty($error)): ?>
        
        <!-- Tab Navigation -->
        <div class="tab-navigation">
            <div class="tab-container">
                <a href="#registration-info" class="tab-item active">Registration & Contact</a>
                <a href="#payment-info" class="tab-item">Payment Info</a>
                <a href="#products" class="tab-item">Products</a>
                <a href="#delegates" class="tab-item">Delegates</a>
                <a href="#payment-history" class="tab-item">Payment History</a>
                <a href="#email-history" class="tab-item">Email History</a>
                <a href="#technical-info" class="tab-item">Technical Info</a>
            </div>
        </div>
        
        <div class="details-grid" id="registration-info">
            <!-- Registration & Payment Overview -->
            <div class="details-card" id="payment-info">
                <h3><i class="fas fa-file-invoice-dollar"></i> Registration & Payment Overview</h3>
                <div class="detail-row">
                    <span class="detail-label">Registration Number:</span>
                    <span class="detail-value"><?php echo htmlspecialchars($registration['registration_number']); ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Registration Date:</span>
                    <span class="detail-value"><?php echo date('M j, Y H:i', strtotime($registration['created_at'])); ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Payment Method:</span>
                    <span class="detail-value">
                        <?php echo $registration['payment_method'] === 'gateway' ? 'Online Payment' : 'Bank Transfer (TT)'; ?>
                    </span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Payment Status:</span>
                    <span class="detail-value">
                        <span class="status-badge status-<?php echo $registration['payment_status']; ?>">
                            <?php echo ucfirst($registration['payment_status']); ?>
                        </span>
                        <?php if ($registration['payment_status'] === 'complimentary'): ?>
                            <small class="text-muted" style="margin-left: 8px; font-size: 0.85em;">
                                (Free registration - No payment required)
                            </small>
                        <?php endif; ?>
                    </span>
                </div>
                <div class="detail-row print-hide-amount">
                    <span class="detail-label">Total Amount:</span>
                    <span class="detail-value">$<?php echo number_format($registration['total_amount']); ?></span>
                </div>
                <?php if ($registration['payment_reference']): ?>
                <div class="detail-row">
                    <span class="detail-label">Payment Reference:</span>
                    <span class="detail-value"><?php echo htmlspecialchars($registration['payment_reference']); ?></span>
                </div>
                <?php endif; ?>
                
                <?php 
                // Find the most recent gateway transaction ID for Stripe payments
                $gatewayTransactionId = null;
                foreach ($payments as $payment) {
                    if ($payment['transaction_type'] === 'gateway' && !empty($payment['gateway_transaction_id'])) {
                        $gatewayTransactionId = $payment['gateway_transaction_id'];
                        break; // Get the most recent one
                    }
                }
                ?>
                <?php if ($gatewayTransactionId && $registration['payment_method'] === 'gateway'): ?>
                <div class="detail-row print-hide-stripe">
                    <span class="detail-label">Stripe Transaction ID:</span>
                    <span class="detail-value">
                        <code style="background: #f1f5f9; padding: 2px 6px; border-radius: 4px; font-size: 0.9em;">
                            <?php echo htmlspecialchars($gatewayTransactionId); ?>
                        </code>
                        <a href="https://dashboard.stripe.com/payments/<?php echo urlencode($gatewayTransactionId); ?>" 
                           target="_blank" 
                           style="margin-left: 8px; color: #635bff; text-decoration: none; font-size: 0.9em;"
                           title="View in Stripe Dashboard">
                            <i class="fas fa-external-link-alt"></i> View in Stripe
                        </a>
                    </span>
                </div>
                <?php endif; ?>
                <?php if ($registration['payment_deadline']): ?>
                <div class="detail-row print-hide-deadline">
                    <span class="detail-label">Payment Deadline:</span>
                    <span class="detail-value"><?php echo date('M j, Y', strtotime($registration['payment_deadline'])); ?></span>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Contact Information -->
            <div class="details-card">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h3><i class="fas fa-address-card"></i> Contact Information</h3>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="openContactEditModal()">
                        <i class="fas fa-edit"></i> Edit Contact Info
                    </button>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Full Name:</span>
                    <span class="detail-value"><?php echo htmlspecialchars($registration['contact_full_name']); ?></span>
                </div>

                <div class="detail-row">
                    <span class="detail-label">Designation:</span>
                    <span class="detail-value"><?php echo htmlspecialchars($registration['contact_designation']); ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Department:</span>
                    <span class="detail-value"><?php echo htmlspecialchars($registration['contact_department']); ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Email:</span>
                    <span class="detail-value">
                        <a href="mailto:<?php echo htmlspecialchars($registration['contact_email']); ?>" 
                           class="link">
                            <?php echo htmlspecialchars($registration['contact_email']); ?>
                        </a>
                    </span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Mobile:</span>
                    <span class="detail-value"><?php echo htmlspecialchars($registration['contact_mobile']); ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">University:</span>
                    <span class="detail-value"><?php echo htmlspecialchars($registration['university_name']); ?></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Country:</span>
                    <span class="detail-value"><?php echo htmlspecialchars($registration['country']); ?></span>
                </div>
            </div>
            

            
            <!-- Payment Status Update (Only for users with edit permission) -->
            <?php if (hasPermission('payments', 'edit')): ?>
            <div class="details-card print-hide-section">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h3><i class="fas fa-sync-alt"></i> Update Payment Status</h3>
                    <span class="badge badge-status badge-<?php echo $registration['payment_status']; ?>">
                        Current: <?php echo ucfirst($registration['payment_status']); ?>
                    </span>
                </div>
                <form method="POST" class="mt-16" id="payment-status-form">
                    <div class="form-group">
                        <label for="payment_status" class="form-label">Payment Status</label>
                        <select id="payment_status" name="payment_status" class="form-control" required>
                            <option value="">Select Status...</option>
                            <option value="paid" <?php echo $registration['payment_status'] === 'paid' ? 'selected' : ''; ?>>Paid</option>
                            <option value="complimentary" <?php echo $registration['payment_status'] === 'complimentary' ? 'selected' : ''; ?>>Complimentary (Free)</option>
                            <option value="pending" <?php echo $registration['payment_status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="failed" <?php echo $registration['payment_status'] === 'failed' ? 'selected' : ''; ?>>Failed</option>
                            <option value="expired" <?php echo $registration['payment_status'] === 'expired' ? 'selected' : ''; ?>>Expired</option>
                            <option value="cancelled" <?php echo $registration['payment_status'] === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    
                    <!-- Validation Warning Alert -->
                    <div id="complimentary-warning" class="alert alert-warning" style="display: none; margin-top: 15px;">
                        <i class="fas fa-exclamation-triangle"></i>
                        <strong>Cannot Change to Complimentary:</strong>
                        <ul id="validation-errors" style="margin: 10px 0 10px 20px; padding: 0;"></ul>
                        <?php if (getCurrentUserRole() === 'super_admin'): ?>
                        <div style="margin-top: 10px;">
                            <label style="display: flex; align-items: start; cursor: pointer;">
                                <input type="checkbox" id="force-override-checkbox" style="margin-top: 4px; margin-right: 8px;">
                                <span><strong>Force Override</strong> (Super Admin only - requires justification)</span>
                            </label>
                        </div>
                        <?php else: ?>
                        <div style="margin-top: 10px; padding: 10px; background: #fef3c7; border-left: 3px solid #f59e0b; color: #92400e;">
                            <i class="fas fa-info-circle"></i> <strong>Note:</strong> Only Super Administrators can override these validation rules. Please contact a super admin if this change is necessary.
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Override Notes (shown when force override is checked) -->
                    <div id="override-notes-section" style="display: none; margin-top: 15px;">
                        <div class="form-group">
                            <label for="override_notes" class="form-label">
                                <i class="fas fa-sticky-note"></i> Override Justification <span style="color: #dc2626;">*</span>
                            </label>
                            <textarea id="override_notes" name="override_notes" class="form-control" rows="4" 
                                      placeholder="Required: Explain why you are overriding the validation rules (e.g., sponsor provided free seats, refund processed separately, etc.)"></textarea>
                        </div>
                    </div>
                    
                    <input type="hidden" id="force_override" name="force_override" value="0">
                    
                    <div class="form-group">
                        <button type="submit" name="update_payment_status" class="btn btn-primary action-btn" id="update-status-btn">
                            <i class="fas fa-save"></i> Update Payment Status
                        </button>
                    </div>
                </form>
            </div>
            <?php endif; ?>
            
            <!-- Admin Notes -->
            <div class="details-card print-hide-section">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h3><i class="fas fa-sticky-note"></i> Admin Notes</h3>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="openAdminNotesModal()">
                        <i class="fas fa-edit"></i> Edit Notes
                    </button>
                </div>
                <div class="admin-notes-display">
                    <?php if (!empty($registration['admin_notes'])): ?>
                        <div class="notes-content">
                            <?php echo $registration['admin_notes']; ?>
                        </div>
                        <div class="notes-meta text-sm text-muted mt-2">
                            Last updated: <?php echo date('M j, Y H:i', strtotime($registration['updated_at'])); ?>
                        </div>
                    <?php else: ?>
                        <div class="no-notes text-muted">
                            <em>No admin notes added yet.</em>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Products Purchased -->
        <?php if (!empty($products)): ?>
        <div class="delegates-table" id="products">
            <h3><i class="fas fa-shopping-cart"></i> Products Purchased</h3>
            <div class="table-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Category</th>
                            <th>Quantity</th>
                            <th>Unit Price</th>
                            <th>Total Price</th>
                            <th>Pricing Tier</th>
                            <th>Stock Status</th>
                            <?php if ($registration['payment_method'] === 'tt' && hasPermission('registrations', 'edit')): ?>
                            <th>Actions</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $totalProductAmount = 0;
                        foreach ($products as $product): 
                            $totalProductAmount += $product['total_price'];
                        ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($product['product_name']); ?></strong>
                                <?php if ($product['product_code']): ?>
                                <br><small class="text-muted"><?php echo htmlspecialchars($product['product_code']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge badge-secondary">
                                    <?php echo ucfirst(htmlspecialchars($product['category'])); ?>
                                </span>
                            </td>
                            <td><?php echo number_format($product['quantity']); ?></td>
                            <td>$<?php echo number_format($product['unit_price'], 2); ?></td>
                            <td><strong>$<?php echo number_format($product['total_price'], 2); ?></strong></td>
                            <td>
                                <?php if ($product['pricing_tier']): ?>
                                    <span class="badge badge-info"><?php echo htmlspecialchars($product['pricing_tier']); ?></span>
                                <?php else: ?>
                                    <span class="text-muted">Standard</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php 
                                $stockStatus = $product['stock_status'];
                                $statusClass = '';
                                switch($stockStatus) {
                                    case 'confirmed':
                                        $statusClass = 'status-paid';
                                        break;
                                    case 'reserved':
                                        $statusClass = 'status-pending';
                                        break;
                                    case 'cancelled':
                                        $statusClass = 'status-failed';
                                        break;
                                    default:
                                        $statusClass = 'status-pending';
                                }
                                ?>
                                <span class="status-badge <?php echo $statusClass; ?>">
                                    <?php echo ucfirst($stockStatus); ?>
                                </span>
                            </td>
                            <?php if ($registration['payment_method'] === 'tt' && hasPermission('registrations', 'edit')): ?>
                            <td>
                                <button type="button" 
                                        class="btn btn-sm btn-outline-primary" 
                                        onclick="openProductChangeModal(<?php echo $product['id']; ?>, <?php echo $product['product_id']; ?>, <?php echo $product['category_id'] ?? 'null'; ?>, '<?php echo htmlspecialchars($product['category']); ?>', '<?php echo htmlspecialchars($product['product_name']); ?>', <?php echo $product['quantity']; ?>, <?php echo $product['unit_price']; ?>)"
                                        title="Change this product to another in the same category">
                                    <i class="fas fa-exchange-alt"></i> Change Product
                                </button>
                            </td>
                            <?php endif; ?>
                        </tr>
                        <?php endforeach; ?>
                        <tr style="border-top: 2px solid var(--slate-300); background: var(--slate-50);">
                            <td colspan="4"><strong>Total Products Amount:</strong></td>
                            <td><strong>$<?php echo number_format($totalProductAmount, 2); ?></strong></td>
                            <td colspan="<?php echo ($registration['payment_method'] === 'tt' && hasPermission('registrations', 'edit')) ? '3' : '2'; ?>"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <?php else: ?>
        <div class="details-card">
            <h3><i class="fas fa-shopping-cart"></i> Products Purchased</h3>
            <p class="text-muted">No detailed product information available. This registration may have been created before the product system was implemented.</p>
            
            <?php
            // Create dynamic product summary from registration data
            $legacyProducts = [];
            
            // Add delegate passes
            if ($registration['delegate_count'] > 0) {
                $delegateTypeName = $registration['delegate_type'] === 'earlyBird' ? 'Early Bird' : 'Standard';
                $legacyProducts[] = [
                    'name' => $delegateTypeName . ' Delegate Pass',
                    'category' => 'Delegate Pass',
                    'quantity' => $registration['delegate_count'],
                    'type' => 'delegate'
                ];
            }
            

            ?>
            
            <?php if (!empty($legacyProducts)): ?>
            <div class="mt-4">
                <h4 class="text-sm font-semibold text-slate-700 mb-3">Estimated Products (Legacy Registration)</h4>
                <div class="legacy-products-list">
                    <?php foreach ($legacyProducts as $product): ?>
                    <div class="legacy-product-item">
                        <div class="product-info">
                            <div class="product-name">
                                <strong><?php echo htmlspecialchars($product['name']); ?></strong>
                                <span class="badge badge-secondary ml-2">
                                    <?php echo htmlspecialchars($product['category']); ?>
                                </span>
                            </div>
                            <div class="product-quantity text-sm text-slate-600">
                                Quantity: <?php echo number_format($product['quantity']); ?>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="mt-3 p-3 bg-yellow-50 border border-yellow-200 rounded">
                    <p class="text-sm text-yellow-800">
                        <strong>Note:</strong> This is an estimated product breakdown based on legacy registration data. 
                        Detailed pricing and product information is not available for registrations created before the product system implementation.
                    </p>
                </div>
            </div>
            <?php else: ?>
            <div class="mt-3 p-3 bg-slate-50 border border-slate-200 rounded">
                <p class="text-sm text-slate-600">No product information could be determined from this registration.</p>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <style>
        .legacy-products-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .legacy-product-item {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 16px;
        }
        
        .product-info {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .product-name {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .badge.badge-secondary {
            background: #64748b;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .bg-yellow-50 {
            background-color: #fefce8;
        }
        
        .border-yellow-200 {
            border-color: #fde047;
        }
        
        .text-yellow-800 {
            color: #854d0e;
        }
        
        .bg-slate-50 {
            background-color: #f8fafc;
        }
        
        .border-slate-200 {
            border-color: #e2e8f0;
        }
        
        .text-slate-600 {
            color: #475569;
        }
        
        .text-slate-700 {
            color: #334155;
        }
        
                 /* Print Styles - Optimized for clean, professional printing */
         @media print {
             /* Override browser default page margins */
             @page {
                 margin: 0.5cm;
                 size: A4;
             }
            /* Hide all non-essential elements - aggressive removal */
            .admin-nav,
            .admin-top-bar,
            .admin-top-nav,
            .admin-nav-bar,
            .admin-nav-container,
            .main-nav,
            .nav-link,
            .nav-dropdown,
            .breadcrumb,
            .page-actions,
            .tab-navigation,
            .tab-container,
            .tab-item,
            .nav-links,
            .page-header,
            .btn,
            button,
            .modal,
            .alert,
            #payment-history,
            #email-history,
            #technical-info,
            .fas,
            .fa,
            [onclick],
            .action-btn,
            .ml-3,
            .mt-32,
            .text-center,
            .d-flex:has(button),
            .email-actions,
            .page-header .page-actions {
                display: none !important;
                visibility: hidden !important;
                height: 0 !important;
                width: 0 !important;
                margin: 0 !important;
                padding: 0 !important;
                border: none !important;
                position: absolute !important;
                top: -9999px !important;
                left: -9999px !important;
            }
            
            /* Add print header at very top of body */
            body::before {
                content: "Registration Details - <?php echo htmlspecialchars($registration['registration_number']); ?>";
                display: block;
                text-align: center;
                font-size: 18px;
                font-weight: bold;
                margin: 0 0 8px 0;
                padding: 8px 20px 4px 20px;
                border-bottom: 1px solid #000;
                color: #000;
                background: white;
                position: relative;
                z-index: 9999;
            }
            
            /* Reset page margins and layout */
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                font-size: 16px;
                line-height: 1.5;
                color: #000;
                background: white;
                margin: 0 !important;
                padding: 0 !important;
            }
            
            /* Force body to start at absolute top */
            html, body {
                margin: 0 !important;
                padding: 0 !important;
                border: 0 !important;
            }
            
            /* Main content container */
            .admin-content {
                max-width: 100%;
                margin: 0 !important;
                padding: 0 20px !important;
                box-shadow: none;
                position: relative;
            }
            
            /* Page title */
            .page-title {
                font-size: 28px;
                font-weight: bold;
                text-align: center;
                margin-bottom: 20px;
                color: #000;
                border-bottom: 2px solid #000;
                padding-bottom: 10px;
            }
            
            /* Details grid layout */
            .details-grid {
                display: block !important;
                margin: 0;
            }
            
            /* Cards styling for print */
            .details-card {
                break-inside: avoid;
                margin-bottom: 20px;
                padding: 15px;
                border: 1px solid #ddd;
                border-radius: 0;
                box-shadow: none;
                background: white;
            }
            
            /* Remove top margin from first card */
            .details-card:first-child {
                margin-top: 0;
            }
            
            /* Ensure admin content starts at very top */
            .admin-content {
                margin-top: 0 !important;
                padding-top: 0 !important;
            }
            
            .details-card h3 {
                font-size: 20px;
                font-weight: bold;
                margin: 0 0 15px 0;
                padding: 0 0 8px 0;
                border-bottom: 1px solid #ccc;
                color: #000;
            }
            
            /* Detail rows */
            .detail-row {
                display: flex;
                justify-content: space-between;
                padding: 6px 0;
                border-bottom: 1px dotted #ccc;
                break-inside: avoid;
            }
            
            .detail-row:last-child {
                border-bottom: none;
            }
            
            .detail-label {
                font-weight: bold;
                color: #000;
                flex: 0 0 40%;
                font-size: 16px;
            }
            
            .detail-value {
                color: #000;
                flex: 1;
                text-align: right;
                font-size: 16px;
            }
            
            /* Tables for products and delegates */
            .delegates-table {
                break-inside: avoid;
                margin-bottom: 20px;
                border: 1px solid #ddd;
                border-radius: 0;
                box-shadow: none;
                background: white;
            }
            
            .delegates-table h3 {
                font-size: 20px;
                font-weight: bold;
                padding: 15px;
                margin: 0;
                background: #f5f5f5;
                border-bottom: 1px solid #ddd;
                color: #000;
            }
            
            .table {
                width: 100%;
                border-collapse: collapse;
                font-size: 14px;
            }
            
            .table th,
            .table td {
                padding: 8px 6px;
                text-align: left;
                border: 1px solid #ddd;
                color: #000;
            }
            
            .table th {
                background: #f5f5f5;
                font-weight: bold;
                font-size: 12px;
                text-transform: uppercase;
            }
            
            /* Status badges */
            .status-badge,
            .badge {
                background: #f0f0f0 !important;
                color: #000 !important;
                padding: 2px 6px;
                border: 1px solid #ccc;
                border-radius: 3px;
                font-size: 10px;
                font-weight: bold;
            }
            
            /* Links */
            a {
                color: #000 !important;
                text-decoration: none !important;
            }
            
            /* Hide specific sections that aren't needed for printing */
            .print-hide-section,
            #payment-history,
            #email-history,
            #technical-info {
                display: none !important;
            }
            
            /* Hide specific payment fields from print */
            .print-hide-amount,
            .print-hide-stripe,
            .print-hide-deadline {
                display: none !important;
            }
            
            /* Ensure important sections are visible */
            #registration-info,
            #payment-info,
            #products,
            #delegates {
                display: block !important;
            }
            
            /* Page breaks */
            .page-break {
                page-break-before: always;
            }
            
            /* Prevent orphans and widows */
            p, .detail-row {
                orphans: 3;
                widows: 3;
            }
            
            /* Legacy products styling */
            .legacy-products-list {
                display: block;
            }
            
            .legacy-product-item {
                border: 1px solid #ddd;
                padding: 10px;
                margin-bottom: 10px;
                background: white;
                break-inside: avoid;
            }
            
            /* Remove background colors and shadows */
            .details-card,
            .delegates-table {
                background: white !important;
                box-shadow: none !important;
            }
            
            /* Special handling for payment status */
            .status-paid {
                background: #e8f5e8 !important;
                color: #000 !important;
            }
            
            .status-pending {
                background: #fff3cd !important;
                color: #000 !important;
            }
            
            .status-failed {
                background: #f8d7da !important;
                color: #000 !important;
            }
        }
        </style>

        <!-- Delegates Information -->
        <div class="delegates-table" id="delegates">
            <h3><i class="fas fa-users"></i> Delegate Details (<?php echo count($delegates); ?> delegates)</h3>
            <div class="table-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Full Name</th>
                            <th>Badge Name</th>
                            <th>Email</th>
                            <th>Designation</th>
                            <th>Department</th>
                            <th>Dietary Requirements</th>
                            <th>Special Assistance</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($delegates)): ?>
                        <tr>
                            <td colspan="8" class="empty-state muted">
                                No delegate details found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($delegates as $index => $delegate): ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><?php echo htmlspecialchars($delegate['full_name']); ?></td>
                            <td><?php echo htmlspecialchars($delegate['badge_name']); ?></td>
                            <td><?php echo htmlspecialchars($delegate['email'] ?: '—'); ?></td>
                            <td><?php echo htmlspecialchars($delegate['designation']); ?></td>
                            <td><?php echo htmlspecialchars($delegate['department'] ?: '—'); ?></td>
                            <td><?php echo htmlspecialchars($delegate['dietary_requirements'] ?: '—'); ?></td>
                            <td><?php echo htmlspecialchars($delegate['special_assistance'] ?: '—'); ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Payment History -->
        <?php if (!empty($payments)): ?>
        <div class="delegates-table print-hide-section" id="payment-history">
            <h3><i class="fas fa-history"></i> Payment History</h3>
            <div class="table-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Transaction ID</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Reference</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($payments as $payment): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($payment['gateway_transaction_id'] ?: $payment['id']); ?></td>
                            <td>$<?php echo number_format($payment['amount'], 2); ?></td>
                            <td>
                                <?php 
                                $status = $payment['transaction_status'];
                                $cssClass = "status-badge status-{$status}";
                                
                                // Display user-friendly status labels
                                $display_status_map = [
                                    'completed' => 'Paid',
                                    'pending' => 'Pending',
                                    'failed' => 'Failed',
                                    'cancelled' => 'Cancelled',
                                    'processing' => 'Processing'
                                ];
                                $display_status = $display_status_map[$status] ?? ucfirst($status);
                                ?>
                                <span class="<?php echo $cssClass; ?>">
                                    <?php echo $display_status; ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($payment['transaction_reference'] ?: '—'); ?></td>
                            <td><?php echo date('M j, Y H:i', strtotime($payment['created_at'])); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Email History -->
        <div class="details-card print-hide-section" id="email-history" style="margin-top: 32px;">
            <h3><i class="fas fa-envelope"></i> Email History</h3>
            <?php
            try {
                require_once '../email_notifications.php';
                $emailHistory = getEmailHistory($registration['id']);
                
                if (empty($emailHistory)) {
                    echo '<p class="text-slate-600">No emails sent for this registration yet.</p>';
                } else {
                    echo '<div class="email-history-list">';
                    foreach ($emailHistory as $email) {
                        $statusClass = $email['status'] === 'sent' ? 'status-paid' : ($email['status'] === 'failed' ? 'status-failed' : 'status-pending');
                        $emailType = formatEmailType($email['email_type']);
                        
                        echo '<div class="email-history-item">';
                        echo '<div class="email-history-header">';
                        echo '<span class="email-type-badge">' . htmlspecialchars($emailType) . '</span>';
                        echo '<span class="status-badge ' . $statusClass . '">' . ucfirst($email['status']) . '</span>';
                        echo '<span class="email-date">' . date('M j, Y H:i', strtotime($email['sent_at'])) . '</span>';
                        echo '<div class="email-actions">';
                        echo '<button class="btn btn-sm btn-secondary action-btn" onclick="viewEmailDetails(' . $email['id'] . ')" title="View email details"><i class="fas fa-eye"></i> View</button>';
                        echo '<button class="btn btn-sm btn-primary action-btn" onclick="resendEmail(' . $email['id'] . ', \'' . $email['email_type'] . '\')" title="Resend this email"><i class="fas fa-sync"></i> Resend</button>';
                        echo '</div>';
                        echo '</div>';
                        echo '<div class="email-subject">' . htmlspecialchars($email['subject']) . '</div>';
                        echo '<div class="email-recipient">To: ' . htmlspecialchars($email['recipient_email']) . '</div>';
                        if ($email['status'] === 'failed' && $email['error_message']) {
                            echo '<div class="email-error">Error: ' . htmlspecialchars($email['error_message']) . '</div>';
                        }
                        echo '</div>';
                    }
                    echo '</div>';
                }
            } catch (Exception $e) {
                echo '<p class="text-red-600">Error loading email history: ' . htmlspecialchars($e->getMessage()) . '</p>';
            }
            ?>
        </div>
        
        <!-- Action Buttons -->
        <!-- Technical Information -->
        <div class="details-card print-hide-section" id="technical-info" style="margin-top: 32px;">
            <h3><i class="fas fa-cogs"></i> Technical Information</h3>
            <div class="detail-row">
                <span class="detail-label">IP Address:</span>
                <span class="detail-value"><?php echo htmlspecialchars($registration['ip_address'] ?? 'N/A'); ?></span>
            </div>
            <div class="detail-row">
                <span class="detail-label">User Agent:</span>
                <span class="detail-value text-xs break-all">
                    <?php echo htmlspecialchars($registration['user_agent'] ?? 'N/A'); ?>
                </span>
            </div>
            <div class="detail-row">
                <span class="detail-label">Last Updated:</span>
                <span class="detail-value"><?php echo date('M j, Y H:i', strtotime($registration['updated_at'])); ?></span>
            </div>
        </div>

        <div class="mt-32 text-center">
            <a href="registrations.php" class="btn btn-secondary">← Back to Registrations</a>
            
            <?php if (hasPermission('registrations', 'delete') && $registration['payment_status'] === 'cancelled'): ?>
            <button onclick="confirmDeleteRegistration()" class="btn btn-danger ml-3">
                <i class="fas fa-trash"></i> Delete Registration
            </button>
            <?php elseif (hasPermission('registrations', 'delete') && $registration['payment_status'] !== 'cancelled'): ?>
            <button class="btn btn-danger ml-3" disabled title="Registration can only be deleted when payment status is 'Cancelled'">
                <i class="fas fa-trash"></i> Delete Registration
            </button>
            <?php endif; ?>
        </div>
        
        <?php endif; ?>
    </div>

<!-- Contact Edit Modal -->
<div id="contactEditModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h4>Edit Contact Information</h4>
            <span class="close" onclick="closeContactEditModal()">&times;</span>
        </div>
        <form id="contactEditForm" method="POST">
            <input type="hidden" name="action" value="update_contact">
            <input type="hidden" name="registration_id" value="<?php echo $registration['id']; ?>">
            
            <div class="form-group">
                <label for="contact_full_name">Full Name *</label>
                <input type="text" id="contact_full_name" name="contact_full_name" 
                       value="<?php echo htmlspecialchars($registration['contact_full_name']); ?>" required>
            </div>
            
            <div class="form-group">
                <label for="contact_designation">Designation</label>
                <input type="text" id="contact_designation" name="contact_designation" 
                       value="<?php echo htmlspecialchars($registration['contact_designation']); ?>">
            </div>
            
            <div class="form-group">
                <label for="contact_department">Department</label>
                <input type="text" id="contact_department" name="contact_department" 
                       value="<?php echo htmlspecialchars($registration['contact_department']); ?>">
            </div>
            
            <div class="form-group">
                <label for="contact_email">Email *</label>
                <input type="email" id="contact_email" name="contact_email" 
                       value="<?php echo htmlspecialchars($registration['contact_email']); ?>" required>
            </div>
            
            <div class="form-group">
                <label for="contact_mobile">Mobile</label>
                <input type="text" id="contact_mobile" name="contact_mobile" 
                       value="<?php echo htmlspecialchars($registration['contact_mobile']); ?>">
            </div>
            
            <div class="form-group">
                <label for="university_name">University</label>
                <input type="text" id="university_name" name="university_name" 
                       value="<?php echo htmlspecialchars($registration['university_name']); ?>">
            </div>
            
            <div class="form-group">
                <label for="country">Country</label>
                <input type="text" id="country" name="country" 
                       value="<?php echo htmlspecialchars($registration['country']); ?>">
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeContactEditModal()">Cancel</button>
                <button type="submit" class="btn btn-primary action-btn"><i class="fas fa-save"></i> Save Changes</button>
            </div>
        </form>
    </div>
</div>

<!-- Admin Notes Edit Modal -->
<div id="adminNotesModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h4>Edit Admin Notes</h4>
            <span class="close" onclick="closeAdminNotesModal()">&times;</span>
        </div>
        <form id="adminNotesForm" method="POST">
            <input type="hidden" name="action" value="update_admin_notes">
            <input type="hidden" name="registration_id" value="<?php echo $registration['id']; ?>">
            
            <div class="form-group">
                <label for="admin_notes">Admin Notes</label>
                <div class="editor-toolbar">
                    <button type="button" class="editor-btn" onclick="formatText('bold')" title="Bold">
                        <strong>B</strong>
                    </button>
                    <button type="button" class="editor-btn" onclick="formatText('italic')" title="Italic">
                        <em>I</em>
                    </button>
                    <button type="button" class="editor-btn" onclick="formatText('underline')" title="Underline">
                        <u>U</u>
                    </button>
                    <span class="editor-separator">|</span>
                    <button type="button" class="editor-btn" onclick="insertList('ul')" title="Bullet List">
                        • List
                    </button>
                    <button type="button" class="editor-btn" onclick="insertList('ol')" title="Numbered List">
                        1. List
                    </button>
                    <span class="editor-separator">|</span>
                    <button type="button" class="editor-btn" onclick="clearFormatting()" title="Clear Formatting">
                        Clear
                    </button>
                    <span class="editor-separator">|</span>
                    <button type="button" class="editor-btn" id="htmlViewBtn" onclick="toggleHtmlView()" title="Toggle HTML View">
                        &lt;/&gt; HTML
                    </button>
                </div>
                <div id="editor-content" class="editor-content" contenteditable="true" 
                     placeholder="Add your admin notes here..."><?php echo $registration['admin_notes'] ?? ''; ?></div>
                <textarea id="html-view" class="html-view" style="display: none;" 
                          placeholder="HTML source code will appear here..."></textarea>
                <textarea id="admin_notes" name="admin_notes" style="display: none;"><?php echo htmlspecialchars($registration['admin_notes'] ?? ''); ?></textarea>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeAdminNotesModal()">Cancel</button>
                <button type="submit" class="btn btn-primary action-btn"><i class="fas fa-save"></i> Save Notes</button>
            </div>
        </form>
    </div>
</div>

<!-- Product Change Modal -->
<div id="productChangeModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h4>Change Product</h4>
            <span class="close" onclick="closeProductChangeModal()">&times;</span>
        </div>
        <form id="productChangeForm" method="POST" action="change_product.php">
            <input type="hidden" name="registration_id" value="<?php echo $registration['id']; ?>">
            <input type="hidden" name="registration_product_id" id="change_registration_product_id">
            <input type="hidden" name="old_product_id" id="change_old_product_id">
            <input type="hidden" name="category_id" id="change_category_id">
            
            <div class="form-group">
                <label>Current Product:</label>
                <div id="current_product_display" class="current-product-display"></div>
            </div>
            
            <div class="form-group">
                <label for="new_product_id">New Product (Same Category) *</label>
                <select id="new_product_id" name="new_product_id" class="form-control" required>
                    <option value="">Loading products...</option>
                </select>
                <small class="form-text text-muted">Only products from the same category are shown.</small>
            </div>
            
            <div class="form-group">
                <label for="change_quantity">Quantity *</label>
                <input type="number" id="change_quantity" name="quantity" class="form-control" min="1" required>
            </div>
            
            <div class="form-group">
                <label>Price Information:</label>
                <div id="price_information" class="price-info-display">
                    <div class="price-row">
                        <span class="price-label">Current Unit Price:</span>
                        <span id="current_unit_price" class="price-value">$0.00</span>
                    </div>
                    <div class="price-row">
                        <span class="price-label">New Unit Price:</span>
                        <span id="new_unit_price" class="price-value">$0.00</span>
                    </div>
                    <div class="price-row total-price">
                        <span class="price-label">New Total Price:</span>
                        <span id="new_total_price" class="price-value">$0.00</span>
                    </div>
                </div>
            </div>
            
            <div class="form-group">
                <label for="change_reason">Reason for Change *</label>
                <textarea id="change_reason" name="reason" class="form-control" rows="3" required 
                          placeholder="Please provide a reason for changing this product..."></textarea>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeProductChangeModal()">Cancel</button>
                <button type="submit" class="btn btn-primary action-btn">
                    <i class="fas fa-exchange-alt"></i> Change Product
                </button>
            </div>
        </form>
    </div>
</div>

<style>
/* Custom styles for registration details page */
/* Action Buttons */
.action-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 16px;
    transition: all 0.2s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    border-radius: 6px;
    font-weight: 600;
}

.action-btn i {
    font-size: 0.9rem;
}

.action-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.btn-primary.action-btn {
    background: white;
    border-color: #001b42;
    color: #001b42;
}

.btn-primary.action-btn:hover {
    background: #f8fafc;
    border-color: #001b42;
    color: #001b42;
}

.btn-secondary.action-btn {
    background: white;
    border-color: #2563eb;
    color: #2563eb;
}

.btn-secondary.action-btn:hover {
    background: #f8fafc;
    border-color: #2563eb;
    color: #2563eb;
}

.btn-outline-secondary.action-btn {
    background: white;
    border-color: #64748b;
    color: #64748b;
}

.btn-outline-secondary.action-btn:hover {
    background: #f8fafc;
    color: #334155;
    border-color: #334155;
}

/* Tab Navigation */
.tab-navigation {
    margin-bottom: 24px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow-x: auto;
}

.tab-container {
    display: flex;
    padding: 0 16px;
    border-bottom: 1px solid #e2e8f0;
}

.tab-item {
    padding: 16px 20px;
    color: #64748b;
    text-decoration: none;
    font-weight: 600;
    font-size: 0.95rem;
    border-bottom: 3px solid transparent;
    white-space: nowrap;
    transition: all 0.2s;
}

.tab-item:hover {
    color: #334155;
    background: #f8fafc;
}

.tab-item.active {
    color: #3b82f6;
    border-bottom-color: #3b82f6;
    background: #eff6ff;
}

@media (max-width: 768px) {
    .tab-container {
        padding: 0;
    }
    
    .tab-item {
        padding: 12px 16px;
        font-size: 0.85rem;
    }
}

.admin-notes-content {
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    padding: 15px;
    margin-top: 10px;
    background-color: #f9fafb;
}

/* Email History Styling */
.email-history-list {
    margin-top: 15px;
}

.email-history-item {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
    transition: box-shadow 0.2s ease;
}

.email-history-item:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.email-history-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;
    flex-wrap: wrap;
}

.email-type-badge {
    background: #3b82f6;
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
}

.status-badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
}

.status-badge.status-paid {
    background: #10b981;
    color: white;
}

.status-badge.status-failed {
    background: #ef4444;
    color: white;
}

.status-badge.status-pending {
    background: #f59e0b;
    color: white;
}

.status-badge.status-completed {
    background: #10b981;
    color: white;
}

.status-badge.status-processing {
    background: #3b82f6;
    color: white;
}

.status-badge.status-cancelled {
    background: #6b7280;
    color: white;
}

.status-badge.status-expired {
    background: #dc2626;
    color: white;
}

.email-date {
    color: #64748b;
    font-size: 14px;
}

.email-actions {
    margin-left: auto;
    display: flex;
    gap: 8px;
}

.email-actions .btn {
    padding: 4px 8px;
    font-size: 12px;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
}

.email-actions .btn-secondary {
    background: #6b7280;
    color: white;
}

.email-actions .btn-secondary:hover {
    background: #4b5563;
}

.email-actions .btn-primary {
    background: #3b82f6;
    color: white;
}

.email-actions .btn-primary:hover {
    background: #2563eb;
}

.email-subject {
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 4px;
    font-size: 14px;
}

.email-recipient {
    color: #64748b;
    font-size: 13px;
    margin-bottom: 4px;
}

.email-error {
    background: #fef2f2;
    color: #dc2626;
    padding: 8px;
    border-radius: 4px;
    font-size: 13px;
    margin-top: 8px;
    border-left: 3px solid #dc2626;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .email-history-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }
    
    .email-date {
        margin-left: 0;
        order: -1;
    }
}

/* Modal Styling */
.modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    overflow: auto;
}

.modal-content {
    background-color: #fefefe;
    margin: 5% auto;
    padding: 0;
    border: none;
    border-radius: 12px;
    width: 90%;
    max-width: 600px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: translateY(-50px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid #e2e8f0;
    display: flex;
    justify-content: between;
    align-items: center;
    background: #f8fafc;
    border-radius: 12px 12px 0 0;
}

.modal-header h4 {
    margin: 0;
    color: #1e293b;
    font-weight: 600;
}

.close {
    color: #64748b;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
    line-height: 1;
    margin-left: auto;
}

.close:hover,
.close:focus {
    color: #ef4444;
    text-decoration: none;
}

.form-group {
    margin-bottom: 20px;
    padding: 0 24px;
}

.form-group:first-of-type {
    margin-top: 24px;
}

.form-group label {
    display: block;
    margin-bottom: 6px;
    font-weight: 600;
    color: #374151;
    font-size: 14px;
}

.form-group input {
    width: 100%;
    padding: 12px 16px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    font-size: 14px;
    transition: border-color 0.2s, box-shadow 0.2s;
    box-sizing: border-box;
}

.form-group input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.modal-footer {
    padding: 20px 24px;
    border-top: 1px solid #e2e8f0;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    background: #f8fafc;
    border-radius: 0 0 12px 12px;
}

.btn-sm {
    padding: 6px 12px;
    font-size: 13px;
}

.btn-outline-primary {
    background: transparent;
    border: 1px solid #3b82f6;
    color: #3b82f6;
}

.btn-outline-primary:hover {
    background: #3b82f6;
    color: white;
}

.d-flex {
    display: flex;
}

.justify-content-between {
    justify-content: space-between;
}

.align-items-center {
    align-items: center;
}

.mb-3 {
    margin-bottom: 1rem;
}

/* Payment Status Badge Styling */
.badge-status {
    padding: 6px 12px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.badge-pending {
    background-color: #fef3c7;
    color: #92400e;
    border: 1px solid #fbbf24;
}

.badge-paid {
    background-color: #d1fae5;
    color: #065f46;
    border: 1px solid #10b981;
}

.badge-failed {
    background-color: #fee2e2;
    color: #991b1b;
    border: 1px solid #ef4444;
}

.badge-expired {
    background-color: #f3f4f6;
    color: #374151;
    border: 1px solid #9ca3af;
}

/* Admin Notes Styling */
.admin-notes-display {
    min-height: 60px;
    padding: 16px;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
}

.notes-content {
    color: #374151;
    line-height: 1.6;
    white-space: pre-wrap;
}

.no-notes {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60px;
    color: #9ca3af;
}

.notes-meta {
    border-top: 1px solid #e2e8f0;
    padding-top: 8px;
    margin-top: 12px;
}

/* Simple Editor Styling */
.editor-toolbar {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 8px 12px;
    background: #f8fafc;
    border: 1px solid #d1d5db;
    border-bottom: none;
    border-radius: 8px 8px 0 0;
    margin-bottom: 0;
}

.editor-btn {
    background: none;
    border: 1px solid #d1d5db;
    border-radius: 4px;
    padding: 4px 8px;
    cursor: pointer;
    font-size: 12px;
    color: #374151;
    transition: all 0.2s;
}

.editor-btn:hover {
    background: #e5e7eb;
    border-color: #9ca3af;
}

.editor-btn:active {
    background: #d1d5db;
}

.editor-separator {
    color: #d1d5db;
    margin: 0 4px;
}

.editor-content {
    min-height: 120px;
    padding: 12px 16px;
    border: 1px solid #d1d5db;
    border-radius: 0 0 8px 8px;
    background: white;
    font-size: 14px;
    line-height: 1.6;
    color: #374151;
    outline: none;
    overflow-y: auto;
    max-height: 300px;
}

.editor-content:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.editor-content:empty:before {
    content: attr(placeholder);
    color: #9ca3af;
    pointer-events: none;
}

.editor-content ul, .editor-content ol {
    margin: 8px 0;
    padding-left: 24px;
}

.editor-content li {
    margin: 4px 0;
}

.editor-content strong {
    font-weight: 600;
}

.editor-content em {
    font-style: italic;
}

.editor-content u {
    text-decoration: underline;
}

.html-view {
    min-height: 120px;
    padding: 12px 16px;
    border: 1px solid #d1d5db;
    border-radius: 0 0 8px 8px;
    background: #f8fafc;
    font-family: 'Courier New', monospace;
    font-size: 13px;
    line-height: 1.4;
    color: #374151;
    outline: none;
    overflow-y: auto;
    max-height: 300px;
    resize: none;
}

.html-view:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.editor-btn.active {
    background: #3b82f6;
    color: white;
    border-color: #2563eb;
}

/* Product Change Modal Styles */
.current-product-display {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 8px;
}

.current-product-name {
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 4px;
}

.current-product-category {
    color: #64748b;
    font-size: 14px;
    margin-bottom: 4px;
}

.current-product-price {
    color: #059669;
    font-weight: 600;
    font-size: 14px;
}

.price-info-display {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 16px;
}

.price-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #e2e8f0;
}

.price-row:last-child {
    border-bottom: none;
}

.price-row.total-price {
    border-top: 2px solid #e2e8f0;
    margin-top: 8px;
    padding-top: 12px;
    font-weight: 600;
    background: #eff6ff;
    margin: 8px -16px -16px -16px;
    padding: 12px 16px;
    border-radius: 0 0 8px 8px;
}

.price-label {
    font-weight: 600;
    color: #374151;
}

.price-value {
    color: #059669;
    font-weight: 600;
}

.form-text {
    font-size: 12px;
    color: #6b7280;
    margin-top: 4px;
}

.form-control select {
    appearance: none;
    background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3E%3C/svg%3E");
    background-position: right 8px center;
    background-repeat: no-repeat;
    background-size: 16px;
    padding-right: 32px;
}

.form-control textarea {
    resize: vertical;
    min-height: 80px;
}
</style>

<script>
// Tab Navigation - Smooth Scrolling and Active Tab Highlighting
document.addEventListener('DOMContentLoaded', function() {
    // Smooth scrolling for tab navigation
    const tabLinks = document.querySelectorAll('.tab-item');
    const sections = document.querySelectorAll('.details-card, .delegates-table');
    
    // Smooth scrolling for tab links
    tabLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                // Smooth scroll to target
                window.scrollTo({
                    top: targetElement.offsetTop - 100, // Offset to account for fixed header
                    behavior: 'smooth'
                });
                
                // Update active tab
                tabLinks.forEach(tab => tab.classList.remove('active'));
                this.classList.add('active');
            }
        });
    });
    
    // Update active tab on scroll
    window.addEventListener('scroll', function() {
        let current = '';
        
        sections.forEach(section => {
            const sectionTop = section.offsetTop - 150;
            const sectionHeight = section.offsetHeight;
            const id = section.getAttribute('id');
            
            if (id && window.pageYOffset >= sectionTop && window.pageYOffset < sectionTop + sectionHeight) {
                current = id;
            }
        });
        
        tabLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href') === '#' + current) {
                link.classList.add('active');
            }
        });
    });
});

function openContactEditModal() {
    document.getElementById('contactEditModal').style.display = 'block';
    document.body.style.overflow = 'hidden';
}

function closeContactEditModal() {
    document.getElementById('contactEditModal').style.display = 'none';
    document.body.style.overflow = 'auto';
}

// Prevent closing modal when clicking outside - removed for data safety

function openAdminNotesModal() {
    document.getElementById('adminNotesModal').style.display = 'block';
    document.body.style.overflow = 'hidden';
}

function closeAdminNotesModal() {
    document.getElementById('adminNotesModal').style.display = 'none';
    document.body.style.overflow = 'auto';
}

// Simple Editor Functions
function formatText(command) {
    document.execCommand(command, false, null);
    document.getElementById('editor-content').focus();
}

function insertList(type) {
    if (type === 'ul') {
        document.execCommand('insertUnorderedList', false, null);
    } else if (type === 'ol') {
        document.execCommand('insertOrderedList', false, null);
    }
    document.getElementById('editor-content').focus();
}

function clearFormatting() {
    document.execCommand('removeFormat', false, null);
    document.getElementById('editor-content').focus();
}

let isHtmlView = false;

function toggleHtmlView() {
    const editorContent = document.getElementById('editor-content');
    const htmlView = document.getElementById('html-view');
    const htmlBtn = document.getElementById('htmlViewBtn');
    
    if (!isHtmlView) {
        // Switch to HTML view
        htmlView.value = editorContent.innerHTML;
        editorContent.style.display = 'none';
        htmlView.style.display = 'block';
        htmlBtn.classList.add('active');
        htmlBtn.innerHTML = '<i class="fas fa-eye"></i> Visual';
        htmlBtn.title = 'Switch to Visual Editor';
        isHtmlView = true;
    } else {
        // Switch back to visual view
        editorContent.innerHTML = htmlView.value;
        htmlView.style.display = 'none';
        editorContent.style.display = 'block';
        htmlBtn.classList.remove('active');
        htmlBtn.innerHTML = '&lt;/&gt; HTML';
        htmlBtn.title = 'Toggle HTML View';
        isHtmlView = false;
    }
}

// Sync editor content with hidden textarea before form submission
document.getElementById('adminNotesForm').addEventListener('submit', function() {
    if (isHtmlView) {
        // If in HTML view, use the HTML textarea content
        document.getElementById('admin_notes').value = document.getElementById('html-view').value;
    } else {
        // If in visual view, use the editor content
        document.getElementById('admin_notes').value = document.getElementById('editor-content').innerHTML;
    }
});

// Initialize editor content when modal opens
function openAdminNotesModal() {
    document.getElementById('adminNotesModal').style.display = 'block';
    document.body.style.overflow = 'hidden';
    
    // Reset HTML view state
    isHtmlView = false;
    const htmlBtn = document.getElementById('htmlViewBtn');
    const htmlView = document.getElementById('html-view');
    htmlBtn.classList.remove('active');
    htmlBtn.innerHTML = '&lt;/&gt; HTML';
    htmlBtn.title = 'Toggle HTML View';
    htmlView.style.display = 'none';
    
    // Load existing content into editor
    const hiddenTextarea = document.getElementById('admin_notes');
    const editorContent = document.getElementById('editor-content');
    editorContent.style.display = 'block';
    if (hiddenTextarea.value) {
        editorContent.innerHTML = hiddenTextarea.value;
    }
}

// Escape key disabled for data safety - only close button can close modal

// Email History Functions
function viewEmailDetails(emailId) {
    // Open modal or new page with email details
    window.open('email_details.php?id=' + emailId, '_blank', 'width=800,height=600');
}

function logPrintAction() {
    // Set print date for header
    const printDate = new Date().toLocaleDateString();
    document.body.setAttribute('data-print-date', printDate);
    
    // Log print action via AJAX
    fetch('log_action.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            action: 'print_details',
            registration_id: '<?php echo $registration['id']; ?>',
            registration_number: '<?php echo $registration['registration_number']; ?>'
        })
    }).catch(error => console.log('Logging error:', error));
}

function resendEmail(emailId, emailType) {
    const emailTypeNames = {
        'pending_registration': 'Pending Registration Email',
        'registration_confirmation': 'Registration Confirmation Email',
        'payment_reminder_24h': '24-Hour Payment Reminder',
        'payment_reminder_48h': '48-Hour Payment Reminder',
        'payment_reminder_7d': '7-Day Payment Reminder',
        'admin_notification': 'Admin Notification'
    };
    
    const emailTypeName = emailTypeNames[emailType] || emailType;
    
    if (confirm(`Are you sure you want to resend this ${emailTypeName}?\n\nThis will generate a fresh email using current data and send it to the same recipient.`)) {
        const button = event.target;
        const originalText = button.innerHTML;
        button.innerHTML = '⏳ Sending...';
        button.disabled = true;
        
        fetch('resend_email.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                email_id: emailId
            })
        })
        .then(response => response.json())
        .then(data => {
            button.innerHTML = originalText;
            button.disabled = false;
            
            if (data.success) {
                alert('✅ Email resent successfully!');
                // Refresh the page to show the new email log entry
                location.reload();
            } else {
                alert('❌ Failed to resend email: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            button.innerHTML = originalText;
            button.disabled = false;
            alert('❌ Network error: ' + error.message);
        });
    }
}

// Product Change Modal Functions
function openProductChangeModal(registrationProductId, productId, categoryId, categoryName, productName, quantity, unitPrice) {
    console.log('Opening product change modal with:', {
        registrationProductId, productId, categoryId, categoryName, productName, quantity, unitPrice
    });
    // Set hidden form fields
    document.getElementById('change_registration_product_id').value = registrationProductId;
    document.getElementById('change_old_product_id').value = productId;
    document.getElementById('change_category_id').value = categoryId;
    document.getElementById('change_quantity').value = quantity;
    
    // Display current product information
    let productInfoHtml = `
        <div class="current-product-name">${productName}</div>
        <div class="current-product-category">Category: ${categoryName}</div>
        <div class="current-product-price">Current Unit Price: $${parseFloat(unitPrice).toFixed(2)} × ${quantity} = $${(parseFloat(unitPrice) * parseInt(quantity)).toFixed(2)}</div>
    `;
    
    // Add warning for delegate products and disable quantity field
    if (categoryName === 'Delegate Pass') {
        productInfoHtml += `
            <div class="delegate-warning" style="background: #fef3cd; border: 1px solid #fecf4e; padding: 12px; margin-top: 8px; border-radius: 6px;">
                <div style="color: #8b5a00; font-weight: 600; margin-bottom: 4px;">
                    <i class="fas fa-exclamation-triangle"></i> Delegate Product Notice
                </div>
                <div style="color: #8b5a00; font-size: 13px;">
                    Delegate products have fixed quantity of 1 per person. Quantity cannot be changed.
                    Please review the Delegates section after making changes to ensure consistency.
                </div>
            </div>
        `;
        // Disable quantity field for delegate products
        const quantityField = document.getElementById('change_quantity');
        quantityField.disabled = true;
        quantityField.value = 1;
        quantityField.style.backgroundColor = '#f5f5f5';
        quantityField.style.cursor = 'not-allowed';
        
        // Add hidden field to ensure quantity is submitted for delegate products
        let hiddenQuantityField = document.getElementById('delegate_quantity_hidden');
        if (!hiddenQuantityField) {
            hiddenQuantityField = document.createElement('input');
            hiddenQuantityField.type = 'hidden';
            hiddenQuantityField.id = 'delegate_quantity_hidden';
            hiddenQuantityField.name = 'quantity';
            document.getElementById('productChangeForm').appendChild(hiddenQuantityField);
        }
        hiddenQuantityField.value = 1;
        quantityField.removeAttribute('name'); // Remove name from disabled field
    } else {
        // Enable quantity field for non-delegate products
        const quantityField = document.getElementById('change_quantity');
        quantityField.disabled = false;
        quantityField.style.backgroundColor = '';
        quantityField.style.cursor = '';
        quantityField.name = 'quantity'; // Restore name attribute
        
        // Remove hidden field if it exists
        const hiddenQuantityField = document.getElementById('delegate_quantity_hidden');
        if (hiddenQuantityField) {
            hiddenQuantityField.remove();
        }
    }
    
    document.getElementById('current_product_display').innerHTML = productInfoHtml;
    
    // Set current unit price
    document.getElementById('current_unit_price').textContent = `$${parseFloat(unitPrice).toFixed(2)}`;
    
    // Clear form fields
    document.getElementById('new_product_id').innerHTML = '<option value="">Loading products...</option>';
    document.getElementById('change_reason').value = '';
    
    // Load products for this category
    loadProductsForCategory(categoryId, productId);
    
    // Show modal
    document.getElementById('productChangeModal').style.display = 'block';
    document.body.style.overflow = 'hidden';
}

function closeProductChangeModal() {
    document.getElementById('productChangeModal').style.display = 'none';
    document.body.style.overflow = 'auto';
    
    // Reset form
    document.getElementById('productChangeForm').reset();
    document.getElementById('new_product_id').innerHTML = '<option value="">Select a product...</option>';
    document.getElementById('new_unit_price').textContent = '$0.00';
    document.getElementById('new_total_price').textContent = '$0.00';
    
    // Reset quantity field state
    const quantityField = document.getElementById('change_quantity');
    quantityField.disabled = false;
    quantityField.style.backgroundColor = '';
    quantityField.style.cursor = '';
    quantityField.name = 'quantity'; // Restore name attribute
    
    // Remove hidden quantity field if it exists
    const hiddenQuantityField = document.getElementById('delegate_quantity_hidden');
    if (hiddenQuantityField) {
        hiddenQuantityField.remove();
    }
}

function loadProductsForCategory(categoryId, excludeProductId) {
    const selectElement = document.getElementById('new_product_id');
    
    fetch('get_category_products.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            category_id: categoryId,
            exclude_product_id: excludeProductId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            selectElement.innerHTML = '<option value="">Select a new product...</option>';
            data.products.forEach(product => {
                const option = document.createElement('option');
                option.value = product.id;
                option.textContent = `${product.name} - $${parseFloat(product.base_price).toFixed(2)}`;
                option.dataset.price = product.base_price;
                option.dataset.name = product.name;
                selectElement.appendChild(option);
            });
            
            if (data.products.length === 0) {
                selectElement.innerHTML = '<option value="">No other products available in this category</option>';
            }
        } else {
            selectElement.innerHTML = '<option value="">Error loading products</option>';
            console.error('Failed to load products:', data.error);
        }
    })
    .catch(error => {
        selectElement.innerHTML = '<option value="">Error loading products</option>';
        console.error('Network error loading products:', error);
    });
}

// Update price information when product or quantity changes
document.addEventListener('DOMContentLoaded', function() {
    const newProductSelect = document.getElementById('new_product_id');
    const quantityInput = document.getElementById('change_quantity');
    
    function updatePriceDisplay() {
        const selectedOption = newProductSelect.options[newProductSelect.selectedIndex];
        const quantity = parseInt(quantityInput.value) || 0;
        
        if (selectedOption && selectedOption.dataset.price) {
            const unitPrice = parseFloat(selectedOption.dataset.price);
            const totalPrice = unitPrice * quantity;
            
            document.getElementById('new_unit_price').textContent = `$${unitPrice.toFixed(2)}`;
            document.getElementById('new_total_price').textContent = `$${totalPrice.toFixed(2)}`;
        } else {
            document.getElementById('new_unit_price').textContent = '$0.00';
            document.getElementById('new_total_price').textContent = '$0.00';
        }
    }
    
    newProductSelect.addEventListener('change', updatePriceDisplay);
    quantityInput.addEventListener('input', updatePriceDisplay);
});

// Payment Status Validation for Complimentary Changes
document.addEventListener('DOMContentLoaded', function() {
    const paymentStatusSelect = document.getElementById('payment_status');
    const complimentaryWarning = document.getElementById('complimentary-warning');
    const validationErrorsList = document.getElementById('validation-errors');
    const forceOverrideCheckbox = document.getElementById('force-override-checkbox');
    const overrideNotesSection = document.getElementById('override-notes-section');
    const forceOverrideInput = document.getElementById('force_override');
    const paymentStatusForm = document.getElementById('payment-status-form');
    const updateStatusBtn = document.getElementById('update-status-btn');
    
    // Get current registration data from PHP
    const currentStatus = '<?php echo $registration['payment_status']; ?>';
    const paymentMethod = '<?php echo $registration['payment_method']; ?>';
    const totalAmount = <?php echo $registration['total_amount']; ?>;
    
    // Handle payment status change
    paymentStatusSelect.addEventListener('change', function() {
        const newStatus = this.value;
        
        // Reset warnings
        complimentaryWarning.style.display = 'none';
        validationErrorsList.innerHTML = '';
        forceOverrideCheckbox.checked = false;
        overrideNotesSection.style.display = 'none';
        forceOverrideInput.value = '0';
        
        // Check if trying to change to complimentary
        if (newStatus === 'complimentary') {
            const errors = [];
            
            // Scenario 1: Already paid via online gateway
            if (paymentMethod === 'gateway' && currentStatus === 'paid') {
                errors.push('Payment already processed through online gateway (Stripe). Money has been collected.');
            }
            
            // Scenario 2: Registration has paid products (total > 0)
            if (totalAmount > 0) {
                errors.push('Registration includes paid products (Total: $' + totalAmount.toFixed(2) + ').');
            }
            
            // Show warnings if there are validation errors
            if (errors.length > 0) {
                errors.forEach(error => {
                    const li = document.createElement('li');
                    li.textContent = error;
                    li.style.marginBottom = '5px';
                    validationErrorsList.appendChild(li);
                });
                
                complimentaryWarning.style.display = 'block';
                
                // Scroll to warning
                complimentaryWarning.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
        }
    });
    
    // Handle force override checkbox (only if it exists - super admin only)
    if (forceOverrideCheckbox) {
        forceOverrideCheckbox.addEventListener('change', function() {
            if (this.checked) {
                overrideNotesSection.style.display = 'block';
                forceOverrideInput.value = '1';
                updateStatusBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Force Override & Update';
                updateStatusBtn.style.backgroundColor = '#dc2626';
            } else {
                overrideNotesSection.style.display = 'none';
                forceOverrideInput.value = '0';
                updateStatusBtn.innerHTML = '<i class="fas fa-save"></i> Update Payment Status';
                updateStatusBtn.style.backgroundColor = '';
            }
        });
    }
    
    // Form validation before submit
    paymentStatusForm.addEventListener('submit', function(e) {
        const newStatus = paymentStatusSelect.value;
        const forceOverride = forceOverrideInput.value === '1';
        const overrideNotes = document.getElementById('override_notes').value.trim();
        
        // If changing to complimentary with validation errors and override is checked
        if (newStatus === 'complimentary' && forceOverride) {
            // Require override notes
            if (overrideNotes === '') {
                e.preventDefault();
                alert('Override justification is required when forcing a status change. Please explain why you are overriding the validation rules.');
                document.getElementById('override_notes').focus();
                return false;
            }
            
            // Confirm override action
            const confirmMessage = 'WARNING: You are about to force override the validation rules.\n\n' +
                                 'This will change the status to Complimentary despite:\n' +
                                 validationErrorsList.textContent + '\n\n' +
                                 'Your justification: ' + overrideNotes + '\n\n' +
                                 'Are you sure you want to proceed?';
            
            if (!confirm(confirmMessage)) {
                e.preventDefault();
                return false;
            }
        }
        
        // If changing to complimentary with validation errors but no override
        if (newStatus === 'complimentary' && complimentaryWarning.style.display === 'block' && !forceOverride) {
            e.preventDefault();
            alert('Cannot change status to Complimentary. Please review the warnings and either:\n\n' +
                  '1. Fix the issues mentioned, OR\n' +
                  '2. Use the "Force Override" option with proper justification (Super Admin only)');
            return false;
        }
    });
});
</script>

    </div>

</body>
</html>
