<?php 
// Include session handling
try {
    include_once 'services/session.php';
} catch (Exception $e) {
    die("Error including session.php: " . $e->getMessage());
}

// Check if user is logged in
if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

// Include database connection
try {
    require_once 'layouts/dbconn.php';
} catch (Exception $e) {
    die("Error including database connection: " . $e->getMessage());
}

// Test database connection
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed: " . ($conn->connect_error ?? 'Connection object not found'));
}

// Function to safely execute queries
function safeQuery($conn, $query, $params = []) {
    try {
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        if (!empty($params)) {
            $types = str_repeat('s', count($params));
            $stmt->bind_param($types, ...$params);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        return $data;
    } catch (Exception $e) {
        error_log("Query error: " . $e->getMessage());
        return [];
    }
}

// Get pagination parameters
$page = $_GET['page'] ?? 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// Get filter parameters
$status_filter = $_GET['status'] ?? 'all';
$product_filter = $_GET['product'] ?? 'all';
$search = $_GET['search'] ?? '';

// Build WHERE clause
$where_conditions = ["l.user_id = ?"];
$params = [$user_id];

if ($status_filter !== 'all') {
    $where_conditions[] = "l.status = ?";
    $params[] = $status_filter;
}

if ($product_filter !== 'all') {
    $where_conditions[] = "l.product_id = ?";
    $params[] = $product_filter;
}

if (!empty($search)) {
    $where_conditions[] = "(p.name LIKE ? OR l.license_key LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
}

$where_clause = implode(" AND ", $where_conditions);

// Get user's licenses with product details
$licenses = safeQuery($conn, "
    SELECT 
        l.license_id,
        l.license_key,
        l.status,
        l.sites_allowed,
        l.sites_used,
        l.issued_at,
        l.expires_at,
        l.last_checked,
        l.check_count,
        l.violation_count,
        p.name as product_name,
        p.short_description,
        pp.tier_name,
        pp.price_usd,
        pc.name as category_name,
        (SELECT COUNT(*) FROM license_activations la WHERE la.license_id = l.license_id AND la.status = 'ACTIVE') as active_sites
    FROM licenses l
    JOIN products p ON l.product_id = p.product_id
    JOIN product_pricing pp ON l.pricing_tier_id = pp.pricing_id
    JOIN product_categories pc ON p.category_id = pc.category_id
    WHERE $where_clause
    ORDER BY l.issued_at DESC
    LIMIT ? OFFSET ?
", array_merge($params, [$per_page, $offset]));

// Get total count for pagination
$total_result = safeQuery($conn, "
    SELECT COUNT(*) as total
    FROM licenses l
    JOIN products p ON l.product_id = p.product_id
    WHERE $where_clause
", $params);
$total_licenses = $total_result[0]['total'] ?? 0;
$total_pages = ceil($total_licenses / $per_page);

// Get available products for filter
$products = safeQuery($conn, "
    SELECT DISTINCT p.product_id, p.name
    FROM products p
    JOIN licenses l ON p.product_id = l.product_id
    WHERE l.user_id = ?
    ORDER BY p.name
", [$user_id]);

// Get license statistics
$stats = safeQuery($conn, "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'ACTIVE' THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN status = 'EXPIRED' THEN 1 ELSE 0 END) as expired,
        SUM(CASE WHEN status = 'SUSPENDED' THEN 1 ELSE 0 END) as suspended,
        SUM(CASE WHEN status = 'REVOKED' THEN 1 ELSE 0 END) as revoked
    FROM licenses 
    WHERE user_id = ?
", [$user_id]);

$license_stats = $stats[0] ?? ['total' => 0, 'active' => 0, 'expired' => 0, 'suspended' => 0, 'revoked' => 0];
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php 
    $title = "My Licenses";
    if (file_exists('partials/title-meta.php')) {
        try {
            include_once 'partials/title-meta.php';
        } catch (Exception $e) {
            echo "<title>My Licenses - ConnectPay</title>\n";
        }
    } else {
        echo "<title>My Licenses - ConnectPay</title>\n";
    }
    ?>
    
    <?php 
    if (file_exists('partials/head-css.php')) {
        try {
            include_once 'partials/head-css.php';
        } catch (Exception $e) {
            echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
            echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
        }
    } else {
        echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
        echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
    }
    ?>
    
    <style>
        body {
            background-color: #f8f9fa;
        }
        
        .license-card {
            border: 1px solid #e9ecef;
            border-radius: 12px;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
            background: white;
        }
        
        .license-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .license-active { border-left: 4px solid #28a745; }
        .license-expired { border-left: 4px solid #dc3545; }
        .license-suspended { border-left: 4px solid #ffc107; }
        .license-revoked { border-left: 4px solid #6c757d; }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-item {
            text-align: center;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .filter-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .license-actions .btn {
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
        }
        
        .usage-progress {
            height: 8px;
            border-radius: 4px;
        }
    </style>
</head>

<body>

<div id="wrapper">
    <?php 
    $pagetitle = "My Licenses"; 
    if (file_exists('partials/menu.php')) {
        try {
            include_once 'partials/menu.php';
        } catch (Exception $e) {
            echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                    <div class="container">
                        <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                        <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                    </div>
                  </nav>';
        }
    } else {
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                    <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                </div>
              </nav>';
    }
    ?>

    <div class="content-page">
        <div class="content">
            <div class="container-fluid">
                
                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box mb-4">
                            <h4 class="page-title">
                                <i class="fas fa-key me-2"></i>
                                My Licenses
                            </h4>
                            <nav aria-label="breadcrumb">
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="customer-dashboard.php">Dashboard</a></li>
                                    <li class="breadcrumb-item active">My Licenses</li>
                                </ol>
                            </nav>
                        </div>
                    </div>
                </div>

                <!-- License Statistics -->
                <div class="row">
                    <div class="col-12">
                        <div class="stats-card">
                            <div class="row">
                                <div class="col-6 col-md-3">
                                    <div class="stat-item">
                                        <div class="stat-number"><?php echo $license_stats['total']; ?></div>
                                        <div>Total Licenses</div>
                                    </div>
                                </div>
                                <div class="col-6 col-md-3">
                                    <div class="stat-item">
                                        <div class="stat-number text-success"><?php echo $license_stats['active']; ?></div>
                                        <div>Active</div>
                                    </div>
                                </div>
                                <div class="col-6 col-md-3">
                                    <div class="stat-item">
                                        <div class="stat-number text-warning"><?php echo $license_stats['expired']; ?></div>
                                        <div>Expired</div>
                                    </div>
                                </div>
                                <div class="col-6 col-md-3">
                                    <div class="stat-item">
                                        <div class="stat-number text-danger"><?php echo $license_stats['suspended'] + $license_stats['revoked']; ?></div>
                                        <div>Suspended/Revoked</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filters -->
                <div class="row">
                    <div class="col-12">
                        <div class="filter-card">
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">Search</label>
                                    <input type="text" class="form-control" name="search" 
                                           value="<?php echo htmlspecialchars($search); ?>" 
                                           placeholder="Search licenses or products...">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Status</label>
                                    <select class="form-select" name="status">
                                        <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>>All Statuses</option>
                                        <option value="ACTIVE" <?php echo $status_filter === 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                        <option value="EXPIRED" <?php echo $status_filter === 'EXPIRED' ? 'selected' : ''; ?>>Expired</option>
                                        <option value="SUSPENDED" <?php echo $status_filter === 'SUSPENDED' ? 'selected' : ''; ?>>Suspended</option>
                                        <option value="REVOKED" <?php echo $status_filter === 'REVOKED' ? 'selected' : ''; ?>>Revoked</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Product</label>
                                    <select class="form-select" name="product">
                                        <option value="all" <?php echo $product_filter === 'all' ? 'selected' : ''; ?>>All Products</option>
                                        <?php foreach ($products as $product): ?>
                                        <option value="<?php echo $product['product_id']; ?>" 
                                                <?php echo $product_filter == $product['product_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($product['name']); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">&nbsp;</label>
                                    <div class="d-grid gap-2 d-md-flex">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-search me-1"></i>
                                            Filter
                                        </button>
                                        <a href="my-licenses.php" class="btn btn-outline-secondary">
                                            <i class="fas fa-times me-1"></i>
                                            Clear
                                        </a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Licenses List -->
                <div class="row">
                    <div class="col-12">
                        <?php if (empty($licenses)): ?>
                        <div class="card">
                            <div class="card-body text-center py-5">
                                <i class="fas fa-key fa-4x mb-3 text-muted"></i>
                                <h4>No licenses found</h4>
                                <p class="text-muted mb-4">
                                    <?php if (!empty($search) || $status_filter !== 'all' || $product_filter !== 'all'): ?>
                                    Try adjusting your filters to see more results.
                                    <?php else: ?>
                                    You haven't purchased any plugins yet. Browse our marketplace to get started.
                                    <?php endif; ?>
                                </p>
                                <a href="browse-plugins.php" class="btn btn-primary">
                                    <i class="fas fa-shopping-cart me-2"></i>
                                    Browse Plugins
                                </a>
                            </div>
                        </div>
                        <?php else: ?>
                            <?php foreach ($licenses as $license): ?>
                            <div class="license-card license-<?php echo strtolower($license['status']); ?>">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-8">
                                            <div class="d-flex align-items-start">
                                                <div class="flex-grow-1">
                                                    <h5 class="mb-2">
                                                        <?php echo htmlspecialchars($license['product_name']); ?>
                                                        <span class="badge bg-<?php echo $license['status'] === 'ACTIVE' ? 'success' : ($license['status'] === 'EXPIRED' ? 'danger' : 'warning'); ?> ms-2">
                                                            <?php echo ucfirst(strtolower($license['status'])); ?>
                                                        </span>
                                                    </h5>
                                                    <p class="text-muted mb-2">
                                                        <?php echo htmlspecialchars($license['short_description']); ?>
                                                    </p>
                                                    <div class="row g-2 mb-3">
                                                        <div class="col-auto">
                                                            <small class="text-muted">
                                                                <i class="fas fa-tag me-1"></i>
                                                                <?php echo $license['tier_name']; ?> - $<?php echo number_format($license['price_usd'], 2); ?>
                                                            </small>
                                                        </div>
                                                        <div class="col-auto">
                                                            <small class="text-muted">
                                                                <i class="fas fa-layer-group me-1"></i>
                                                                <?php echo $license['category_name']; ?>
                                                            </small>
                                                        </div>
                                                        <div class="col-auto">
                                                            <small class="text-muted">
                                                                <i class="fas fa-calendar me-1"></i>
                                                                Purchased: <?php echo date('M j, Y', strtotime($license['issued_at'])); ?>
                                                            </small>
                                                        </div>
                                                        <?php if ($license['expires_at']): ?>
                                                        <div class="col-auto">
                                                            <small class="text-muted">
                                                                <i class="fas fa-clock me-1"></i>
                                                                Expires: <?php echo date('M j, Y', strtotime($license['expires_at'])); ?>
                                                            </small>
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    
                                                    <!-- Site Usage -->
                                                    <div class="mb-3">
                                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                                            <small class="text-muted">Site Usage</small>
                                                            <small class="text-muted">
                                                                <?php echo $license['sites_used']; ?>/<?php echo $license['sites_allowed']; ?> sites
                                                            </small>
                                                        </div>
                                                        <div class="progress usage-progress">
                                                            <div class="progress-bar <?php echo $license['sites_used'] >= $license['sites_allowed'] ? 'bg-danger' : 'bg-success'; ?>" 
                                                                 style="width: <?php echo $license['sites_allowed'] > 0 ? ($license['sites_used'] / $license['sites_allowed'] * 100) : 0; ?>%">
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <!-- License Key -->
                                                    <div class="mb-2">
                                                        <small class="text-muted d-block">License Key:</small>
                                                        <div class="input-group input-group-sm">
                                                            <input type="text" class="form-control font-monospace" 
                                                                   value="<?php echo $license['license_key']; ?>" 
                                                                   id="license_<?php echo $license['license_id']; ?>" readonly>
                                                            <button class="btn btn-outline-secondary" type="button" 
                                                                    onclick="copyLicenseKey('license_<?php echo $license['license_id']; ?>')">
                                                                <i class="fas fa-copy"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <div class="text-md-end">
                                                <!-- License Stats -->
                                                <div class="mb-3">
                                                    <div class="row g-2 text-center">
                                                        <div class="col-4">
                                                            <div class="bg-light rounded p-2">
                                                                <div class="fw-bold text-primary"><?php echo $license['active_sites']; ?></div>
                                                                <small class="text-muted">Active Sites</small>
                                                            </div>
                                                        </div>
                                                        <div class="col-4">
                                                            <div class="bg-light rounded p-2">
                                                                <div class="fw-bold text-info"><?php echo $license['check_count']; ?></div>
                                                                <small class="text-muted">Checks</small>
                                                            </div>
                                                        </div>
                                                        <div class="col-4">
                                                            <div class="bg-light rounded p-2">
                                                                <div class="fw-bold text-warning"><?php echo $license['violation_count']; ?></div>
                                                                <small class="text-muted">Violations</small>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- Actions -->
                                                <div class="license-actions">
                                                    <?php if ($license['status'] === 'ACTIVE'): ?>
                                                    <a href="download-plugins.php?license=<?php echo $license['license_key']; ?>" 
                                                       class="btn btn-sm btn-success">
                                                        <i class="fas fa-download me-1"></i>
                                                        Download
                                                    </a>
                                                    <?php endif; ?>
                                                    
                                                    <a href="license-details.php?key=<?php echo $license['license_key']; ?>" 
                                                       class="btn btn-sm btn-outline-primary">
                                                        <i class="fas fa-info-circle me-1"></i>
                                                        Details
                                                    </a>
                                                    
                                                    <a href="manage-activations.php?license=<?php echo $license['license_key']; ?>" 
                                                       class="btn btn-sm btn-outline-info">
                                                        <i class="fas fa-cogs me-1"></i>
                                                        Manage
                                                    </a>
                                                    
                                                    <?php if ($license['status'] === 'EXPIRED'): ?>
                                                    <a href="renew-license.php?license=<?php echo $license['license_key']; ?>" 
                                                       class="btn btn-sm btn-warning">
                                                        <i class="fas fa-refresh me-1"></i>
                                                        Renew
                                                    </a>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>

                            <!-- Pagination -->
                            <?php if ($total_pages > 1): ?>
                            <div class="row">
                                <div class="col-12">
                                    <nav aria-label="Licenses pagination">
                                        <ul class="pagination justify-content-center">
                                            <?php if ($page > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page - 1; ?>&status=<?php echo $status_filter; ?>&product=<?php echo $product_filter; ?>&search=<?php echo urlencode($search); ?>">
                                                    <i class="fas fa-chevron-left"></i>
                                                </a>
                                            </li>
                                            <?php endif; ?>
                                            
                                            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                            <li class="page-item <?php echo $i === (int)$page ? 'active' : ''; ?>">
                                                <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status_filter; ?>&product=<?php echo $product_filter; ?>&search=<?php echo urlencode($search); ?>">
                                                    <?php echo $i; ?>
                                                </a>
                                            </li>
                                            <?php endfor; ?>
                                            
                                            <?php if ($page < $total_pages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page + 1; ?>&status=<?php echo $status_filter; ?>&product=<?php echo $product_filter; ?>&search=<?php echo urlencode($search); ?>">
                                                    <i class="fas fa-chevron-right"></i>
                                                </a>
                                            </li>
                                            <?php endif; ?>
                                        </ul>
                                    </nav>
                                    
                                    <div class="text-center text-muted">
                                        Showing <?php echo ($page - 1) * $per_page + 1; ?> to <?php echo min($page * $per_page, $total_licenses); ?> 
                                        of <?php echo $total_licenses; ?> licenses
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>

            </div>
        </div>

        <?php 
        if (file_exists('partials/footer.php')) {
            try {
                include_once 'partials/footer.php';
            } catch (Exception $e) {
                echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
            }
        } else {
            echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
        }
        ?>
    </div>
</div>

<?php 
if (file_exists('partials/footer-scripts.php')) {
    try {
        include_once 'partials/footer-scripts.php';
    } catch (Exception $e) {
        echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
    }
} else {
    echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
}
?>

<script>
function copyLicenseKey(inputId) {
    const input = document.getElementById(inputId);
    input.select();
    input.setSelectionRange(0, 99999); // For mobile devices
    
    try {
        document.execCommand('copy');
        
        // Show success feedback
        const button = input.nextElementSibling;
        const originalHTML = button.innerHTML;
        button.innerHTML = '<i class="fas fa-check text-success"></i>';
        button.classList.add('border-success');
        
        setTimeout(() => {
            button.innerHTML = originalHTML;
            button.classList.remove('border-success');
        }, 2000);
        
    } catch (err) {
        console.error('Failed to copy license key:', err);
    }
}

// Auto-submit form on filter change
document.addEventListener('DOMContentLoaded', function() {
    const filterSelects = document.querySelectorAll('select[name="status"], select[name="product"]');
    filterSelects.forEach(select => {
        select.addEventListener('change', function() {
            this.form.submit();
        });
    });
});
</script>

</body>
</html>