<?php
/**
 * Special Access Links Management
 * XChange 2025 Registration System
 * 
 * This page allows administrators to create special URLs that display specific products
 * (including hidden ones) to targeted audiences like VIP sponsors, partners, etc.
 */

require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once 'auto_migrate.php';

// Auto-migrate special access links feature
if (!auto_migrate_feature('special_access_links')) {
    die('Failed to initialize special access links feature. Please check database permissions.');
}

// Get database connection
$pdo = getDBConnection();

// Check authentication and permissions
$auth = new AdminAuth($pdo);
$auth->requirePermission('registrations');

$currentPage = 'special-access-links';

// Get flash messages from session
$message = $_SESSION['flash_message'] ?? '';
$messageType = $_SESSION['flash_type'] ?? '';
unset($_SESSION['flash_message'], $_SESSION['flash_type']);

// Get all special access links
try {
    $stmt = $pdo->query("
        SELECT 
            sal.*,
            au.full_name as creator_name,
            COUNT(DISTINCT r.id) as actual_conversions
        FROM special_access_links sal
        LEFT JOIN admin_users au ON sal.created_by = au.id
        LEFT JOIN registrations r ON r.referral_code = sal.link_code AND r.payment_status IN ('paid', 'pending', 'complimentary')
        GROUP BY sal.id
        ORDER BY sal.created_at DESC
    ");
    $links = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $links = [];
    $message = "Error loading links: " . $e->getMessage();
    $messageType = "error";
}

// Get all products for the create/edit form (including hidden ones)
try {
    $stmt = $pdo->query("
        SELECT 
            p.id, 
            p.product_code, 
            p.name, 
            p.base_price,
            p.is_active,
            p.show_in_frontend,
            pc.name as category_name
        FROM products p
        LEFT JOIN product_categories pc ON p.category_id = pc.id
        WHERE p.is_active = 1
        ORDER BY pc.name, p.name
    ");
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Group products by category
    $productsByCategory = [];
    foreach ($products as $product) {
        $category = $product['category_name'] ?? 'Uncategorized';
        if (!isset($productsByCategory[$category])) {
            $productsByCategory[$category] = [];
        }
        $productsByCategory[$category][] = $product;
    }
} catch (Exception $e) {
    $products = [];
    $productsByCategory = [];
}

// Get base URL for generating full links
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$baseUrl = $protocol . '://' . $host . dirname(dirname($_SERVER['PHP_SELF'])) . '/index.html';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Special Access Links - 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">
    <link rel="stylesheet" href="special-access-links.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>
    
    <div class="admin-content">
        <div class="page-header">
            <div>
                <h1 class="page-title">Special Access Links</h1>
                <p style="color: var(--slate-600); margin: 0.5rem 0 0 0;">Create special URLs to display hidden products for VIP access, sponsors, partners, and exclusive offers</p>
            </div>
            <button class="btn btn-primary" onclick="openCreateModal()">
                <i class="fas fa-plus"></i> Create New Link
            </button>
        </div>

        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?> mb-4">
            <i class="fas fa-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?>"></i>
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>

        <!-- Statistics Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-link"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo count($links); ?></div>
                    <div class="stat-label">Total Links</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo count(array_filter($links, fn($l) => $l['is_active'])); ?></div>
                    <div class="stat-label">Active Links</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-eye"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo array_sum(array_column($links, 'access_count')); ?></div>
                    <div class="stat-label">Total Accesses</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-value"><?php echo array_sum(array_column($links, 'actual_conversions')); ?></div>
                    <div class="stat-label">Conversions</div>
                </div>
            </div>
        </div>

        <!-- Links Table -->
        <div style="background: white; border-radius: 12px; box-shadow: var(--shadow); overflow: hidden;">
            <div style="padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e9ecef; display: flex; justify-content: space-between; align-items: center;">
                <h2 style="margin: 0; color: #2c3e50; font-size: 1.25rem; font-weight: 600;">Access Links</h2>
                <div class="search-container">
                    <i class="fas fa-search"></i>
                    <input type="text" id="searchLinks" class="search-input" placeholder="Search by name, code, or status...">
                </div>
            </div>
            <div style="overflow-x: auto;">
                <?php if (empty($links)): ?>
                <div style="text-align: center; padding: 4rem 2rem; color: #6c757d;">
                    <i class="fas fa-link" style="font-size: 4rem; color: #dee2e6; margin-bottom: 1rem;"></i>
                    <h3 style="color: #495057; margin: 1rem 0 0.5rem;">No Special Access Links Yet</h3>
                    <p style="margin-bottom: 1.5rem;">Create your first special access link to provide exclusive product access</p>
                    <button class="btn btn-primary" onclick="openCreateModal()">
                        <i class="fas fa-plus"></i> Create First Link
                    </button>
                </div>
                <?php else: ?>
                <table style="width: 100%; border-collapse: collapse; font-size: 0.875rem;">
                    <thead style="background: #f8f9fa; border-bottom: 2px solid #e9ecef;">
                        <tr>
                            <th style="padding: 0.75rem 1rem; text-align: left; font-weight: 600; color: #495057; white-space: nowrap;">Link Name</th>
                            <th style="padding: 0.75rem 1rem; text-align: left; font-weight: 600; color: #495057; white-space: nowrap;">Code</th>
                            <th style="padding: 0.75rem 1rem; text-align: left; font-weight: 600; color: #495057; white-space: nowrap;">Products</th>
                            <th style="padding: 0.75rem 1rem; text-align: left; font-weight: 600; color: #495057; white-space: nowrap;">Status</th>
                            <th style="padding: 0.75rem 1rem; text-align: left; font-weight: 600; color: #495057; white-space: nowrap;">Expires</th>
                            <th style="padding: 0.75rem 1rem; text-align: left; font-weight: 600; color: #495057; white-space: nowrap;">Access Count</th>
                            <th style="padding: 0.75rem 1rem; text-align: left; font-weight: 600; color: #495057; white-space: nowrap;">Conversions</th>
                            <th style="padding: 0.75rem 1rem; text-align: left; font-weight: 600; color: #495057; white-space: nowrap;">Created</th>
                            <th style="padding: 0.75rem 1rem; text-align: left; font-weight: 600; color: #495057; white-space: nowrap;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($links as $link): 
                            $productIds = json_decode($link['product_ids'], true) ?? [];
                            $isExpired = $link['expires_at'] && strtotime($link['expires_at']) < time();
                            $statusClass = $link['is_active'] && !$isExpired ? 'active' : 'inactive';
                        ?>
                        <tr data-link-id="<?php echo $link['id']; ?>" style="border-bottom: 1px solid #f3f4f6; transition: background-color 0.15s;" onmouseover="this.style.backgroundColor='#f9fafb'" onmouseout="this.style.backgroundColor=''">
                            <td style="padding: 1rem;">
                                <div style="display: flex; flex-direction: column; gap: 0.25rem;">
                                    <strong style="color: #1f2937;"><?php echo htmlspecialchars($link['link_name']); ?></strong>
                                    <?php if ($link['description']): ?>
                                    <small style="color: #6b7280; font-size: 0.8rem;"><?php echo htmlspecialchars(substr($link['description'], 0, 60)); ?><?php echo strlen($link['description']) > 60 ? '...' : ''; ?></small>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td style="padding: 1rem;">
                                <code style="background: #f3f4f6; padding: 0.25rem 0.5rem; border-radius: 4px; font-family: 'Courier New', monospace; font-size: 0.85rem; color: #374151; border: 1px solid #e5e7eb;"><?php echo htmlspecialchars($link['link_code']); ?></code>
                            </td>
                            <td style="padding: 1rem;">
                                <span style="display: inline-flex; align-items: center; padding: 0.25rem 0.6rem; border-radius: 4px; font-size: 0.75rem; font-weight: 600; background: #dbeafe; color: #1e40af;">
                                    <?php echo count($productIds); ?> product<?php echo count($productIds) !== 1 ? 's' : ''; ?>
                                </span>
                                <?php if ($link['include_visible_products']): ?>
                                <span style="display: inline-flex; align-items: center; padding: 0.25rem 0.6rem; border-radius: 4px; font-size: 0.7rem; font-weight: 600; background: #f3f4f6; color: #4b5563; margin-left: 0.25rem;" title="Also shows normally visible products">
                                    + Visible
                                </span>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 1rem;">
                                <span style="display: inline-flex; align-items: center; padding: 0.35rem 0.75rem; border-radius: 6px; font-size: 0.8rem; font-weight: 600; <?php echo $statusClass === 'active' ? 'background: #dcfce7; color: #15803d;' : 'background: #fee2e2; color: #dc2626;'; ?>">
                                    <?php if ($isExpired): ?>
                                        Expired
                                    <?php elseif ($link['is_active']): ?>
                                        Active
                                    <?php else: ?>
                                        Inactive
                                    <?php endif; ?>
                                </span>
                            </td>
                            <td style="padding: 1rem;">
                                <?php if ($link['expires_at']): ?>
                                    <span style="<?php echo $isExpired ? 'color: #dc2626;' : 'color: #6b7280;'; ?>">
                                        <?php echo date('M j, Y', strtotime($link['expires_at'])); ?>
                                    </span>
                                <?php else: ?>
                                    <span style="color: #6b7280;">Never</span>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 1rem;">
                                <span style="font-weight: 600;"><?php echo number_format($link['access_count']); ?></span>
                                <?php if ($link['last_accessed_at']): ?>
                                <small style="color: #6b7280; display: block; font-size: 0.8rem;"><?php echo date('M j, g:ia', strtotime($link['last_accessed_at'])); ?></small>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 1rem;">
                                <span style="font-weight: 600;"><?php echo number_format($link['actual_conversions']); ?></span>
                                <?php if ($link['access_count'] > 0): ?>
                                <small style="color: #6b7280; display: block; font-size: 0.8rem;">
                                    <?php echo number_format(($link['actual_conversions'] / $link['access_count']) * 100, 1); ?>%
                                </small>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 1rem;">
                                <span><?php echo date('M j, Y', strtotime($link['created_at'])); ?></span>
                                <?php if ($link['creator_name']): ?>
                                <small style="color: #6b7280; display: block; font-size: 0.8rem;"><?php echo htmlspecialchars($link['creator_name']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 1rem;">
                                <div style="display: flex; gap: 0.25rem; flex-wrap: wrap;">
                                    <button style="padding: 0.4rem 0.6rem; border: 1px solid #d1d5db; background: white; border-radius: 4px; cursor: pointer; color: #6b7280; transition: all 0.2s; font-size: 0.875rem;" onclick="copyLinkUrl('<?php echo htmlspecialchars($link['link_code']); ?>')" title="Copy URL">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                    <button style="padding: 0.4rem 0.6rem; border: 1px solid #d1d5db; background: white; border-radius: 4px; cursor: pointer; color: #6b7280; transition: all 0.2s; font-size: 0.875rem;" onclick="viewLink(<?php echo $link['id']; ?>)" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button style="padding: 0.4rem 0.6rem; border: 1px solid #d1d5db; background: white; border-radius: 4px; cursor: pointer; color: #6b7280; transition: all 0.2s; font-size: 0.875rem;" onclick="editLink(<?php echo $link['id']; ?>)" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button style="padding: 0.4rem 0.6rem; border: 1px solid #d1d5db; background: white; border-radius: 4px; cursor: pointer; color: #6b7280; transition: all 0.2s; font-size: 0.875rem;" onclick="toggleLinkStatus(<?php echo $link['id']; ?>, <?php echo $link['is_active'] ? 0 : 1; ?>)" title="<?php echo $link['is_active'] ? 'Deactivate' : 'Activate'; ?>">
                                        <i class="fas fa-<?php echo $link['is_active'] ? 'toggle-on' : 'toggle-off'; ?>"></i>
                                    </button>
                                    <button style="padding: 0.4rem 0.6rem; border: 1px solid #d1d5db; background: white; border-radius: 4px; cursor: pointer; color: #dc2626; transition: all 0.2s; font-size: 0.875rem;" onclick="deleteLink(<?php echo $link['id']; ?>)" title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Create/Edit Link Modal -->
    <div id="linkModal" class="modal">
        <div class="modal-dialog modal-lg" style="max-width: 1400px !important; width: 90% !important; min-width: 1200px !important; margin: 2% auto !important;">
            <div class="modal-content" style="max-width: none !important; width: 100% !important; margin: 0 !important; padding: 0 !important;">
                <div class="modal-header">
                    <h2 id="modalTitle">Create Special Access Link</h2>
                    <button class="modal-close" onclick="closeModal()">&times;</button>
                </div>
                <form id="linkForm">
                    <input type="hidden" id="linkId" name="link_id">
                    <div class="modal-body">
                        <!-- Two Column Layout -->
                        <div class="modal-two-column">
                            <!-- Left Column: Basic Information -->
                            <div class="form-section">
                                <h3>Basic Information</h3>
                                
                                <div class="form-group">
                                    <label for="linkName" class="form-label required">Link Name</label>
                                    <input type="text" id="linkName" name="link_name" class="form-input" required placeholder="e.g., VIP Sponsors Package 2025">
                                    <small class="form-help">Internal name for identifying this link</small>
                                </div>

                                <div class="form-group">
                                    <label for="linkCode" class="form-label required">Link Code</label>
                                    <div class="input-group">
                                        <input type="text" id="linkCode" name="link_code" class="form-input" required placeholder="e.g., VIP2025" pattern="[A-Za-z0-9_-]+" maxlength="50">
                                        <button type="button" class="btn btn-secondary" onclick="generateLinkCode()">
                                            <i class="fas fa-random"></i> Generate
                                        </button>
                                    </div>
                                    <small class="form-help">Used in URL: ?access=<strong id="previewCode">CODE</strong></small>
                                </div>

                                <div class="form-group">
                                    <label for="description" class="form-label">Description</label>
                                    <textarea id="description" name="description" class="form-input" rows="3" placeholder="Optional notes about the purpose or target audience"></textarea>
                                </div>

                                <div class="form-group">
                                    <label for="customMessage" class="form-label">Custom Access Message</label>
                                    <textarea id="customMessage" name="custom_message" class="form-input" rows="2" placeholder="You have exclusive access to additional registration options"></textarea>
                                    <small class="form-help">This message will be shown to users when they access the registration via this special link</small>
                                </div>
                            </div>

                            <!-- Right Column: Access Control -->
                            <div class="form-section">
                                <h3>Access Control</h3>
                                
                                <div class="form-group">
                                    <div class="checkbox-group">
                                        <input type="checkbox" id="isActive" name="is_active" value="1" checked>
                                        <label for="isActive">Link is active</label>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="expiresAt" class="form-label">Expiration Date</label>
                                    <input type="datetime-local" id="expiresAt" name="expires_at" class="form-input">
                                    <small class="form-help">Leave empty for no expiration</small>
                                </div>

                                <div class="form-group">
                                    <div class="checkbox-group">
                                        <input type="checkbox" id="includeVisible" name="include_visible_products" value="1" checked>
                                        <label for="includeVisible">
                                            Also show normally visible products
                                            <small class="d-block">Users will see selected products PLUS all products visible in normal registration</small>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Full Width: Product Selection -->
                        <div class="form-section modal-full-width">
                            <h3>Product Configuration</h3>
                            
                            <div class="form-group">
                                <label class="form-label required">Select Products</label>
                                <div class="product-selection-grid">
                                    <?php foreach ($productsByCategory as $category => $categoryProducts): ?>
                                    <div class="product-category-group">
                                        <div class="category-header">
                                            <strong><?php echo htmlspecialchars($category); ?></strong>
                                            <button type="button" class="btn-link" onclick="toggleCategoryProducts('<?php echo htmlspecialchars($category); ?>', true)">Select All</button>
                                            <button type="button" class="btn-link" onclick="toggleCategoryProducts('<?php echo htmlspecialchars($category); ?>', false)">Clear</button>
                                        </div>
                                        <?php foreach ($categoryProducts as $product): ?>
                                        <div class="product-checkbox">
                                            <input type="checkbox" 
                                                   id="product_<?php echo $product['id']; ?>" 
                                                   name="product_ids[]" 
                                                   value="<?php echo $product['id']; ?>"
                                                   data-category="<?php echo htmlspecialchars($category); ?>">
                                            <label for="product_<?php echo $product['id']; ?>">
                                                <div class="product-info">
                                                    <!-- First Line: Product Name and Status -->
                                                    <div class="product-line-1">
                                                        <span class="product-name"><?php echo htmlspecialchars($product['name']); ?></span>
                                                        <div class="product-status-section">
                                                            <span class="badge badge-success">Available</span>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Second Line: Code, Price, and Badges -->
                                                    <div class="product-line-2">
                                                        <div class="product-details">
                                                            <span class="product-code"><?php echo htmlspecialchars($product['product_code']); ?></span>
                                                            <span class="product-price">$<?php echo number_format($product['base_price'], 2); ?></span>
                                                        </div>
                                                        <div class="product-badges">
                                                            <?php if (!$product['show_in_frontend']): ?>
                                                            <span class="badge badge-warning">Hidden</span>
                                                            <?php endif; ?>
                                                            <span class="badge badge-info">Active</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <small class="form-help">Select which products should be accessible via this special link</small>
                            </div>
                        </div>

                    </div>
                    <div class="modal-footer">
                        <div class="footer-url-section">
                            <div class="url-section-content">
                                <label class="url-section-title">Generated URL</label>
                                <div class="url-preview-minimal">
                                    <code id="fullUrlPreview"><?php echo htmlspecialchars($baseUrl); ?>?access=<span id="urlCode">CODE</span></code>
                                    <button type="button" class="btn btn-sm btn-secondary" onclick="copyPreviewUrl()">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="footer-buttons">
                            <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> <span id="submitBtnText">Create Link</span>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Link Details Modal -->
    <div id="viewModal" class="modal">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Link Details</h2>
                    <button class="modal-close" onclick="closeViewModal()">&times;</button>
                </div>
                <div class="modal-body" id="viewModalContent">
                    <!-- Content loaded dynamically -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeViewModal()">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="special-access-links.js"></script>
    <script>
        // Pass PHP data to JavaScript
        const BASE_URL = <?php echo json_encode($baseUrl); ?>;
        const ALL_PRODUCTS = <?php echo json_encode($products); ?>;
    </script>
</body>
</html>


