<?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'];

// Only allow customers
if ($user_role !== 'Customer') {
    header('Location: auth-login.php?error=access_denied');
    exit();
}

// 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
if (!function_exists('safeQuery')) {
    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 form submissions
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'activate_license') {
        $license_key = trim($_POST['license_key'] ?? '');
        $domain = trim($_POST['domain'] ?? '');
        
        if (empty($license_key) || empty($domain)) {
            $error_message = "Please provide both license key and domain.";
        } else {
            // Validate license key format
            if (!preg_match('/^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/', $license_key)) {
                $error_message = "Invalid license key format.";
            } else {
                // Check if license exists and belongs to user
                $license_check = safeQuery($conn, "
                    SELECT license_id, max_activations 
                    FROM licenses 
                    WHERE license_key = ? AND user_id = ? AND status = 'active'
                ", [$license_key, $user_id]);
                
                if (empty($license_check)) {
                    $error_message = "License not found or access denied.";
                } else {
                    $license = $license_check[0];
                    
                    // Check current activations count
                    $current_activations = safeQuery($conn, "
                        SELECT COUNT(*) as count 
                        FROM license_activations 
                        WHERE license_id = ? AND status = 'active'
                    ", [$license['license_id']]);
                    
                    $activation_count = $current_activations[0]['count'] ?? 0;
                    
                    if ($activation_count >= $license['max_activations']) {
                        $error_message = "Maximum activations reached for this license.";
                    } else {
                        // Check if domain already activated
                        $domain_check = safeQuery($conn, "
                            SELECT activation_id 
                            FROM license_activations 
                            WHERE license_id = ? AND domain = ? AND status = 'active'
                        ", [$license['license_id'], $domain]);
                        
                        if (!empty($domain_check)) {
                            $error_message = "This domain is already activated for this license.";
                        } else {
                            // Activate license
                            $activation_result = safeQuery($conn, "
                                INSERT INTO license_activations 
                                (license_id, domain, status, activated_at) 
                                VALUES (?, ?, 'active', NOW())
                            ", [$license['license_id'], $domain]);
                            
                            if ($activation_result !== false) {
                                $success_message = "License activated successfully for domain: " . htmlspecialchars($domain);
                            } else {
                                $error_message = "Failed to activate license.";
                            }
                        }
                    }
                }
            }
        }
    } elseif (isset($_POST['action']) && $_POST['action'] === 'deactivate_license') {
        $activation_id = $_POST['activation_id'] ?? '';
        
        // Verify activation belongs to user
        $activation_check = safeQuery($conn, "
            SELECT la.activation_id 
            FROM license_activations la
            JOIN licenses l ON la.license_id = l.license_id
            WHERE la.activation_id = ? AND l.user_id = ?
        ", [$activation_id, $user_id]);
        
        if (empty($activation_check)) {
            $error_message = "Activation not found or access denied.";
        } else {
            $deactivate_result = safeQuery($conn, "
                UPDATE license_activations 
                SET status = 'deactivated', deactivated_at = NOW() 
                WHERE activation_id = ?
            ", [$activation_id]);
            
            if ($deactivate_result !== false) {
                $success_message = "License deactivated successfully.";
            } else {
                $error_message = "Failed to deactivate license.";
            }
        }
    }
}

// Get customer's licenses
$licenses = safeQuery($conn, "
    SELECT 
        l.license_id,
        l.license_key,
        l.status,
        l.expires_at,
        l.max_activations,
        p.name as product_name,
        p.product_id,
        pp.tier_name as plan_name,
        (SELECT COUNT(*) FROM license_activations la WHERE la.license_id = l.license_id AND la.status = 'active') as active_activations
    FROM licenses l
    JOIN products p ON l.product_id = p.product_id
    LEFT JOIN product_pricing pp ON l.pricing_id = pp.pricing_id
    WHERE l.user_id = ?
    ORDER BY l.created_at DESC
", [$user_id]);

// Get activation history
$activationHistory = safeQuery($conn, "
    SELECT 
        la.activation_id,
        la.domain,
        la.status,
        la.activated_at,
        la.deactivated_at,
        p.name as product_name,
        l.license_key
    FROM license_activations la
    JOIN licenses l ON la.license_id = l.license_id
    JOIN products p ON l.product_id = p.product_id
    WHERE l.user_id = ?
    ORDER BY la.activated_at DESC
    LIMIT 10
", [$user_id]);

// Function to display time ago
function timeAgo($datetime) {
    $time = time() - strtotime($datetime);
    
    if ($time < 60) return 'just now';
    if ($time < 3600) return floor($time/60) . ' minutes ago';
    if ($time < 86400) return floor($time/3600) . ' hours ago';
    if ($time < 2592000) return floor($time/86400) . ' days ago';
    if ($time < 31536000) return floor($time/2592000) . ' months ago';
    return floor($time/31536000) . ' years ago';
}
?>

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

<head>
    <?php 
    $title = "License Activation";
    if (file_exists('partials/title-meta.php')) {
        try {
            include_once 'partials/title-meta.php';
        } catch (Exception $e) {
            echo "<title>$title - ConnectPay</title>\n";
        }
    } else {
        echo "<title>$title - 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";
        }
    } else {
        echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
    }
    ?>
    
    <style>
        body {
            background-color: #f8f9fa;
        }
        
        .license-card {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            background: white;
            transition: all 0.2s ease;
        }
        
        .license-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .status-active {
            background-color: #dcfce7;
            color: #166534;
        }
        
        .status-inactive {
            background-color: #fef3c7;
            color: #92400e;
        }
        
        .status-expired {
            background-color: #fef2f2;
            color: #dc2626;
        }
        
        .form-control {
            border: 1px solid #d1d5db;
            border-radius: 6px;
            padding: 0.75rem;
            transition: border-color 0.2s ease;
        }
        
        .form-control:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .btn-primary {
            background-color: #3b82f6;
            border-color: #3b82f6;
            border-radius: 6px;
            padding: 0.75rem 1.5rem;
            font-weight: 500;
        }
        
        .btn-primary:hover {
            background-color: #2563eb;
            border-color: #2563eb;
        }
        
        .btn-danger {
            background-color: #ef4444;
            border-color: #ef4444;
            border-radius: 6px;
        }
        
        .btn-danger:hover {
            background-color: #dc2626;
            border-color: #dc2626;
        }
        
        .btn-outline-secondary {
            border: 1px solid #d1d5db;
            color: #6b7280;
            border-radius: 6px;
        }
        
        .alert {
            border-radius: 6px;
            border: none;
            padding: 1rem 1.25rem;
        }
        
        .alert-success {
            background-color: #dcfce7;
            color: #166534;
            border-left: 4px solid #16a34a;
        }
        
        .alert-danger {
            background-color: #fef2f2;
            color: #dc2626;
            border-left: 4px solid #ef4444;
        }
        
        .activation-item {
            border-left: 3px solid #e2e8f0;
            padding-left: 1rem;
            margin-bottom: 1rem;
        }
        
        .activation-item.active {
            border-left-color: #16a34a;
        }
        
        .code-display {
            background-color: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            padding: 1rem;
            font-family: 'Monaco', 'Consolas', monospace;
            font-size: 0.875rem;
            cursor: pointer;
        }
        
        .page-title-box {
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e2e8f0;
        }
    </style>
</head>

<body>

<div id="wrapper">
    <?php 
    $pagetitle = "License Activation"; 
    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>';
        }
    }
    ?>

    <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"><a href="my-licenses.php">Licenses</a></li>
                                    <li class="breadcrumb-item active">License Activation</li>
                                </ol>
                            </div>
                            <h4 class="page-title">
                                <i class="fas fa-key me-2"></i>
                                License Activation
                            </h4>
                        </div>
                    </div>
                </div>
                
                <!-- Alert Messages -->
                <?php if (!empty($success_message)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i>
                    <?php echo htmlspecialchars($success_message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($error_message)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    <?php echo htmlspecialchars($error_message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <div class="row">
                    <!-- License Activation Form -->
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header border-bottom bg-light">
                                <h5 class="card-title mb-0">
                                    <i class="fas fa-plus-circle me-2"></i>
                                    Activate New License
                                </h5>
                            </div>
                            <div class="card-body">
                                <form method="POST" action="">
                                    <input type="hidden" name="action" value="activate_license">
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">License Key</label>
                                            <input type="text" 
                                                   class="form-control" 
                                                   name="license_key" 
                                                   id="license_key"
                                                   placeholder="XXXX-XXXX-XXXX-XXXX"
                                                   maxlength="19"
                                                   required>
                                            <small class="text-muted">Format: XXXX-XXXX-XXXX-XXXX</small>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Domain/Website URL</label>
                                            <input type="url" 
                                                   class="form-control" 
                                                   name="domain" 
                                                   placeholder="https://yourdomain.com"
                                                   required>
                                            <small class="text-muted">Where you'll use this plugin</small>
                                        </div>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-check me-2"></i>
                                        Activate License
                                    </button>
                                </form>
                            </div>
                        </div>
                        
                        <!-- My Licenses -->
                        <div class="card mt-4">
                            <div class="card-header border-bottom bg-light">
                                <h5 class="card-title mb-0">
                                    <i class="fas fa-license me-2"></i>
                                    My Licenses
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php if (empty($licenses)): ?>
                                <div class="text-center py-4">
                                    <div class="mb-3">
                                        <i class="fas fa-key fa-3x text-muted"></i>
                                    </div>
                                    <h6 class="text-muted">No Licenses Found</h6>
                                    <p class="text-muted mb-3">You don't have any licenses yet.</p>
                                    <a href="browse-plugins.php" class="btn btn-primary">
                                        <i class="fas fa-shopping-cart me-2"></i>
                                        Browse Plugins
                                    </a>
                                </div>
                                <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-borderless">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Product</th>
                                                <th>License Key</th>
                                                <th>Status</th>
                                                <th>Expires</th>
                                                <th>Activations</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($licenses as $license): ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <i class="fas fa-puzzle-piece me-2 text-primary"></i>
                                                        <div>
                                                            <h6 class="mb-0"><?php echo htmlspecialchars($license['product_name']); ?></h6>
                                                            <small class="text-muted"><?php echo htmlspecialchars($license['plan_name'] ?? 'Standard'); ?></small>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="code-display" onclick="copyToClipboard(this)" title="Click to copy">
                                                        <?php echo htmlspecialchars($license['license_key']); ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <?php
                                                    $status = $license['status'];
                                                    $badgeClass = $status === 'active' ? 'status-active' : 
                                                                 ($status === 'expired' ? 'status-expired' : 'status-inactive');
                                                    ?>
                                                    <span class="status-badge <?php echo $badgeClass; ?>">
                                                        <?php echo ucfirst($status); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <small class="text-muted">
                                                        <?php echo date('M j, Y', strtotime($license['expires_at'])); ?>
                                                    </small>
                                                </td>
                                                <td>
                                                    <span class="badge bg-info">
                                                        <?php echo $license['active_activations']; ?>/<?php echo $license['max_activations']; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="customization-settings.php?license=<?php echo $license['license_id']; ?>" 
                                                           class="btn btn-outline-secondary" 
                                                           title="Customize">
                                                            <i class="fas fa-palette"></i>
                                                        </a>
                                                        <a href="download-plugins.php?license=<?php echo $license['license_id']; ?>" 
                                                           class="btn btn-outline-primary" 
                                                           title="Download">
                                                            <i class="fas fa-download"></i>
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Activation History & Info -->
                    <div class="col-lg-4">
                        <!-- Quick Info -->
                        <div class="card">
                            <div class="card-header border-bottom bg-light">
                                <h5 class="card-title mb-0">
                                    <i class="fas fa-info-circle me-2"></i>
                                    License Info
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <h6 class="text-muted mb-1">Total Licenses</h6>
                                    <h4 class="mb-0"><?php echo count($licenses); ?></h4>
                                </div>
                                <div class="mb-3">
                                    <h6 class="text-muted mb-1">Active</h6>
                                    <h5 class="mb-0 text-success">
                                        <?php echo count(array_filter($licenses, function($l) { return $l['status'] === 'active'; })); ?>
                                    </h5>
                                </div>
                                <div class="mb-3">
                                    <h6 class="text-muted mb-1">Total Activations</h6>
                                    <h5 class="mb-0 text-info">
                                        <?php echo array_sum(array_column($licenses, 'active_activations')); ?>
                                    </h5>
                                </div>
                                <hr>
                                <small class="text-muted">
                                    <i class="fas fa-lightbulb me-1"></i>
                                    Each license can be activated on multiple domains based on your plan.
                                </small>
                            </div>
                        </div>
                        
                        <!-- Activation History -->
                        <div class="card mt-4">
                            <div class="card-header border-bottom bg-light">
                                <h5 class="card-title mb-0">
                                    <i class="fas fa-history me-2"></i>
                                    Recent Activations
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php if (empty($activationHistory)): ?>
                                <div class="text-center py-3">
                                    <i class="fas fa-history fa-2x text-muted"></i>
                                    <p class="text-muted mb-0 mt-2">No activation history</p>
                                </div>
                                <?php else: ?>
                                <div style="max-height: 400px; overflow-y: auto;">
                                    <?php foreach ($activationHistory as $activation): ?>
                                    <div class="activation-item <?php echo $activation['status'] === 'active' ? 'active' : ''; ?>">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="flex-grow-1">
                                                <h6 class="mb-1"><?php echo htmlspecialchars($activation['product_name']); ?></h6>
                                                <p class="mb-1 text-muted small">
                                                    <i class="fas fa-globe me-1"></i>
                                                    <?php echo htmlspecialchars($activation['domain']); ?>
                                                </p>
                                                <small class="text-muted">
                                                    <?php echo timeAgo($activation['activated_at']); ?>
                                                </small>
                                            </div>
                                            <div>
                                                <?php if ($activation['status'] === 'active'): ?>
                                                <form method="POST" action="" class="d-inline">
                                                    <input type="hidden" name="action" value="deactivate_license">
                                                    <input type="hidden" name="activation_id" value="<?php echo $activation['activation_id']; ?>">
                                                    <button type="submit" 
                                                            class="btn btn-sm btn-outline-danger" 
                                                            onclick="return confirm('Deactivate this license?')"
                                                            title="Deactivate">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </form>
                                                <?php else: ?>
                                                <span class="badge bg-secondary">Deactivated</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Help Section -->
                        <div class="card mt-4">
                            <div class="card-header border-bottom bg-light">
                                <h5 class="card-title mb-0">
                                    <i class="fas fa-question-circle me-2"></i>
                                    Need Help?
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <h6>License Activation Issues?</h6>
                                    <ul class="list-unstyled mb-0">
                                        <li class="mb-2">
                                            <i class="fas fa-check text-success me-2"></i>
                                            Verify your license key format
                                        </li>
                                        <li class="mb-2">
                                            <i class="fas fa-check text-success me-2"></i>
                                            Check domain URL spelling
                                        </li>
                                        <li class="mb-2">
                                            <i class="fas fa-check text-success me-2"></i>
                                            Ensure license isn't expired
                                        </li>
                                    </ul>
                                </div>
                                <div class="d-grid gap-2">
                                    <a href="create-ticket.php" class="btn btn-outline-primary btn-sm">
                                        <i class="fas fa-ticket-alt me-2"></i>
                                        Create Support Ticket
                                    </a>
                                    <a href="documentation.php" class="btn btn-outline-secondary btn-sm">
                                        <i class="fas fa-book me-2"></i>
                                        View Documentation
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
            </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>';
    }
}
?>

<?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";
    }
}
?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Auto-format license key input
    const licenseInput = document.getElementById('license_key');
    if (licenseInput) {
        licenseInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/[^A-Z0-9]/g, '');
            let formatted = value.match(/.{1,4}/g)?.join('-') || value;
            if (formatted.length > 19) formatted = formatted.substr(0, 19);
            e.target.value = formatted;
        });
        
        licenseInput.addEventListener('keyup', function(e) {
            e.target.value = e.target.value.toUpperCase();
        });
    }
    
    // Domain validation
    const domainInput = document.querySelector('input[name="domain"]');
    if (domainInput) {
        domainInput.addEventListener('blur', function(e) {
            let domain = e.target.value;
            if (domain && !domain.startsWith('http://') && !domain.startsWith('https://')) {
                e.target.value = 'https://' + domain;
            }
        });
    }
});

function copyToClipboard(element) {
    const text = element.textContent.trim();
    navigator.clipboard.writeText(text).then(() => {
        const original = element.innerHTML;
        element.innerHTML = '<i class="fas fa-check text-success"></i> Copied!';
        element.style.backgroundColor = '#dcfce7';
        
        setTimeout(() => {
            element.innerHTML = original;
            element.style.backgroundColor = '#f8fafc';
        }, 2000);
    }).catch(err => {
        console.error('Failed to copy text: ', err);
    });
}
</script>

</body>
</html>