<?php 
// Include session handling
include 'services/session.php'; 

// Check if user is logged in
if (!$_SESSION['user'] || !isset($_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
require_once 'layouts/dbconn.php';

// 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 [];
    }
}

// Handle download request
$download_message = '';
$download_error = '';

if (isset($_GET['download']) && isset($_GET['license'])) {
    $license_key = $_GET['license'];
    
    // Verify license belongs to user and is active
    $license_check = safeQuery($conn, "
        SELECT l.license_id, l.license_key, l.status, p.name as product_name, p.version
        FROM licenses l
        JOIN products p ON l.product_id = p.product_id
        WHERE l.license_key = ? AND l.user_id = ? AND l.status = 'ACTIVE'
    ", [$license_key, $user_id]);
    
    if (empty($license_check)) {
        $download_error = 'Invalid license key or license not active.';
    } else {
        $license = $license_check[0];
        
        // Generate download link
        $download_token = bin2hex(random_bytes(32));
        $expires_at = date('Y-m-d H:i:s', strtotime('+24 hours'));
        
        try {
            // Insert download link record
            $stmt = $conn->prepare("
                INSERT INTO download_links 
                (license_id, download_token, file_path, file_type, expires_at, downloads_allowed, downloads_used) 
                VALUES (?, ?, ?, 'PLUGIN', ?, 5, 0)
            ");
            $file_path = "plugins/{$license['product_name']}_v{$license['version']}.zip";
            $stmt->bind_param("isss", $license['license_id'], $download_token, $file_path, $expires_at);
            $stmt->execute();
            
            // Redirect to actual download
            header("Location: process-download.php?token=" . $download_token);
            exit();
            
        } catch (Exception $e) {
            $download_error = 'Error generating download link. Please try again.';
        }
    }
}

// Get user's licenses with download information
$licenses = safeQuery($conn, "
    SELECT 
        l.license_id,
        l.license_key,
        l.status,
        l.sites_allowed,
        l.sites_used,
        l.issued_at,
        l.expires_at,
        p.name as product_name,
        p.version,
        p.short_description,
        pp.tier_name,
        pc.name as category_name,
        (SELECT COUNT(*) FROM download_links dl WHERE dl.license_id = l.license_id) as total_downloads,
        (SELECT MAX(dl.created_at) FROM download_links dl WHERE dl.license_id = l.license_id) as last_download
    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 l.user_id = ? AND l.status IN ('ACTIVE', 'EXPIRED')
    ORDER BY l.issued_at DESC
", [$user_id]);

// Get download statistics
$download_stats = safeQuery($conn, "
    SELECT 
        COUNT(DISTINCT l.license_id) as total_licenses,
        COUNT(dl.link_id) as total_downloads,
        SUM(dl.downloads_used) as files_downloaded
    FROM licenses l
    LEFT JOIN download_links dl ON l.license_id = dl.license_id
    WHERE l.user_id = ?
", [$user_id]);

$stats = $download_stats[0] ?? ['total_licenses' => 0, 'total_downloads' => 0, 'files_downloaded' => 0];
?>

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

<head>
    <?php $title = "Download Plugins";
    include 'partials/title-meta.php'; ?>
    
    <?php include 'partials/head-css.php'; ?>
    
    <style>
        .download-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .stats-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }
        
        .stat-item {
            text-align: center;
            padding: 1rem;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .license-download-card {
            border: 1px solid #e9ecef;
            border-radius: 15px;
            margin-bottom: 1.5rem;
            transition: all 0.3s ease;
            background: white;
            overflow: hidden;
        }
        
        .license-download-card:hover {
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .license-active {
            border-left: 4px solid #28a745;
        }
        
        .license-expired {
            border-left: 4px solid #dc3545;
        }
        
        .download-button {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .download-button:hover {
            background: linear-gradient(45deg, #20c997, #28a745);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(40,167,69,0.4);
            color: white;
        }
        
        .download-button:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .version-badge {
            background: #007bff;
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .download-info {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
        }
        
        .file-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(45deg, #007bff, #6f42c1);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
        }
        
        .help-card {
            background: #e7f3ff;
            border: 1px solid #b3d9ff;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
    </style>
</head>

<?php include 'partials/body.php'; ?>

<div id="wrapper">
    <?php $pagetitle = "Download Plugins"; include 'partials/menu.php'; ?>

    <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">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="customer-dashboard.php">Dashboard</a></li>
                                    <li class="breadcrumb-item active">Download Plugins</li>
                                </ol>
                            </div>
                            <h4 class="page-title">
                                <i class="fas fa-download me-2"></i>
                                Download Plugins
                            </h4>
                        </div>
                    </div>
                </div>

                <!-- Download Header -->
                <div class="row">
                    <div class="col-12">
                        <div class="download-header">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h3 class="mb-3">
                                        <i class="fas fa-cloud-download-alt me-2"></i>
                                        Your Plugin Downloads
                                    </h3>
                                    <p class="mb-0 opacity-75">
                                        Download the latest versions of your purchased plugins. 
                                        All downloads include documentation and support files.
                                    </p>
                                </div>
                                <div class="col-md-4 text-md-end">
                                    <div class="text-white">
                                        <h5 class="mb-1">
                                            <i class="fas fa-shield-alt me-2"></i>
                                            Secure Downloads
                                        </h5>
                                        <p class="mb-0">Licensed & authenticated</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Download Messages -->
                <?php if ($download_message): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i>
                    <?php echo $download_message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <?php if ($download_error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    <?php echo $download_error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <!-- Download Statistics -->
                <div class="row">
                    <div class="col-12">
                        <div class="stats-card">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="stat-item">
                                        <div class="stat-number text-primary"><?php echo $stats['total_licenses']; ?></div>
                                        <div class="text-muted">Licensed Products</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="stat-item">
                                        <div class="stat-number text-success"><?php echo $stats['total_downloads']; ?></div>
                                        <div class="text-muted">Download Links Generated</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="stat-item">
                                        <div class="stat-number text-info"><?php echo $stats['files_downloaded']; ?></div>
                                        <div class="text-muted">Files Downloaded</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Help Information -->
                <div class="row">
                    <div class="col-12">
                        <div class="help-card">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h6 class="mb-2">
                                        <i class="fas fa-info-circle me-2"></i>
                                        Download Instructions
                                    </h6>
                                    <p class="mb-0">
                                        Click the download button to generate a secure download link. 
                                        Links expire after 24 hours and can be used up to 5 times for security.
                                        Need help installing? Check our <a href="documentation.php">installation guide</a>.
                                    </p>
                                </div>
                                <div class="col-md-4 text-md-end">
                                    <a href="documentation.php" class="btn btn-primary">
                                        <i class="fas fa-book me-1"></i>
                                        View Documentation
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Licensed Products -->
                <div class="row">
                    <div class="col-12">
                        <?php if (empty($licenses)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-download fa-4x mb-3 text-muted"></i>
                            <h4>No Licensed Products</h4>
                            <p class="text-muted mb-4">
                                You don't have any active licenses yet. Purchase a plugin to start downloading.
                            </p>
                            <a href="browse-plugins.php" class="btn btn-primary">
                                <i class="fas fa-shopping-cart me-2"></i>
                                Browse Plugin Marketplace
                            </a>
                        </div>
                        <?php else: ?>
                            <?php foreach ($licenses as $license): ?>
                            <div class="license-download-card license-<?php echo strtolower($license['status']); ?>">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-2 text-center">
                                            <div class="file-icon">
                                                <i class="fas fa-puzzle-piece"></i>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="d-flex align-items-start">
                                                <div class="flex-grow-1">
                                                    <h5 class="mb-2">
                                                        <?php echo htmlspecialchars($license['product_name']); ?>
                                                        <span class="version-badge ms-2">v<?php echo $license['version']; ?></span>
                                                        <span class="badge bg-<?php echo $license['status'] === 'ACTIVE' ? 'success' : 'danger'; ?> ms-1">
                                                            <?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-2">
                                                        <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-tag me-1"></i>
                                                                <?php echo $license['tier_name']; ?>
                                                            </small>
                                                        </div>
                                                        <div class="col-auto">
                                                            <small class="text-muted">
                                                                <i class="fas fa-calendar me-1"></i>
                                                                Licensed: <?php echo date('M j, Y', strtotime($license['issued_at'])); ?>
                                                            </small>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="download-info">
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <small class="text-muted d-block">Sites Usage</small>
                                                                <strong><?php echo $license['sites_used']; ?>/<?php echo $license['sites_allowed']; ?> sites</strong>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <small class="text-muted d-block">Downloads</small>
                                                                <strong><?php echo $license['total_downloads']; ?> downloads</strong>
                                                                <?php if ($license['last_download']): ?>
                                                                <small class="d-block text-muted">
                                                                    Last: <?php echo date('M j, Y', strtotime($license['last_download'])); ?>
                                                                </small>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4 text-md-end">
                                            <?php if ($license['status'] === 'ACTIVE'): ?>
                                            <div class="d-grid gap-2">
                                                <a href="?download=1&license=<?php echo $license['license_key']; ?>" 
                                                   class="download-button">
                                                    <i class="fas fa-download me-2"></i>
                                                    Download Plugin
                                                </a>
                                                
                                                <div class="row g-1">
                                                    <div class="col">
                                                        <a href="license-details.php?key=<?php echo $license['license_key']; ?>" 
                                                           class="btn btn-sm btn-outline-primary w-100">
                                                            <i class="fas fa-info-circle me-1"></i>
                                                            Details
                                                        </a>
                                                    </div>
                                                    <div class="col">
                                                        <a href="manage-activations.php?license=<?php echo $license['license_key']; ?>" 
                                                           class="btn btn-sm btn-outline-info w-100">
                                                            <i class="fas fa-cogs me-1"></i>
                                                            Manage
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php else: ?>
                                            <div class="text-center">
                                                <button class="download-button" disabled>
                                                    <i class="fas fa-lock me-2"></i>
                                                    License <?php echo ucfirst(strtolower($license['status'])); ?>
                                                </button>
                                                <div class="mt-2">
                                                    <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 License
                                                    </a>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Additional Resources -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body text-center">
                                <i class="fas fa-book fa-3x mb-3 text-primary"></i>
                                <h5>Installation Guide</h5>
                                <p class="text-muted mb-3">
                                    Step-by-step instructions for installing and configuring your plugins.
                                </p>
                                <a href="installation-guide.php" class="btn btn-outline-primary">
                                    <i class="fas fa-external-link-alt me-1"></i>
                                    View Guide
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body text-center">
                                <i class="fas fa-headphones fa-3x mb-3 text-success"></i>
                                <h5>Need Help?</h5>
                                <p class="text-muted mb-3">
                                    Having trouble with downloads or installation? Our support team is here to help.
                                </p>
                                <a href="create-ticket.php" class="btn btn-outline-success">
                                    <i class="fas fa-ticket-alt me-1"></i>
                                    Get Support
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <?php include 'partials/footer.php'; ?>
    </div>
</div>

<?php include 'partials/footer-scripts.php'; ?>

<script>
// Download confirmation
document.addEventListener('DOMContentLoaded', function() {
    const downloadButtons = document.querySelectorAll('.download-button:not([disabled])');
    
    downloadButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            const productName = this.closest('.license-download-card').querySelector('h5').textContent.split('v')[0].trim();
            
            if (!confirm(`Download ${productName}?\n\nThis will generate a secure download link that expires in 24 hours.`)) {
                e.preventDefault();
                return false;
            }
            
            // Show loading state
            this.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Generating Link...';
            this.style.pointerEvents = 'none';
        });
    });
});

// Auto-refresh page if download was initiated
if (window.location.search.includes('download=1')) {
    // Check if download processing is complete
    setTimeout(function() {
        if (!window.location.search.includes('token=')) {
            // If no token in URL, download might have failed
            console.log('Download processing...');
        }
    }, 3000);
}
</script>

</body>
</html>