<?php
/**
 * License Activation Page
 * Users land here if license is not activated or to upgrade from trial
 * File: activate_license.php
 * 
 * FIXED: Added LICENSE_SERVER constant definition
 */

session_start();
require_once 'config.php';
requireLogin(); // Must be logged in to activate

// ==========================================
// DEFINE LICENSE SERVER URL
// ==========================================
if (!defined('LICENSE_SERVER')) {
    // Change this to your actual license server URL
    define('LICENSE_SERVER', 'https://manage.apasaja.my/license_server.php');
}

// Initialize
$message = '';
$error = '';

// Check if already has full license
$hasFullLicense = false;
if (file_exists('license.key')) {
    $licenseContent = file_get_contents('license.key');
    $key = hash('sha256', $_SERVER['HTTP_HOST'] . $_SERVER['DOCUMENT_ROOT'], true);
    $decoded = base64_decode($licenseContent);
    if (strlen($decoded) > 16) {
        $iv = substr($decoded, 0, 16);
        $encrypted = substr($decoded, 16);
        $decrypted = @openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
        if ($decrypted) {
            $licenseData = json_decode($decrypted, true);
            if ($licenseData && $licenseData['status'] !== 'trial') {
                $hasFullLicense = true;
            }
        }
    }
}

// Handle activation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'activate') {
        $licenseKey = trim($_POST['license_key'] ?? '');
        $email = trim($_POST['email'] ?? '');
        
        if (empty($licenseKey) || empty($email)) {
            $error = 'Please enter both license key and email';
        } else {
            // Call activation
            $domain = $_SERVER['HTTP_HOST'];
            $fingerprint = hash('sha256', ($_SERVER['SERVER_SOFTWARE'] ?? 'unknown') . $domain);
            
            $data = [
                'action' => 'activate',
                'license_key' => $licenseKey,
                'email' => $email,
                'domain' => $domain,
                'fingerprint' => $fingerprint,
                'ip' => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
                'software_version' => '1.0'
            ];
            
            $options = [
                'http' => [
                    'header' => "Content-Type: application/json\r\n",
                    'method' => 'POST',
                    'content' => json_encode($data),
                    'timeout' => 10
                ],
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false
                ]
            ];
            
            $context = stream_context_create($options);
            $result = @file_get_contents(LICENSE_SERVER, false, $context);
            
            if ($result === false) {
                $error = 'Cannot connect to license server. Please try again later.';
                
                // Add debug info for testing (remove in production)
                if (isset($_GET['debug'])) {
                    $error .= '<br><small>Server URL: ' . LICENSE_SERVER . '</small>';
                    $error .= '<br><small>Data sent: ' . htmlspecialchars(json_encode($data)) . '</small>';
                }
            } else {
                $response = json_decode($result, true);
                
                if ($response && $response['success']) {
                    // Save license file
                    $licenseData = [
                        'license_key' => $licenseKey,
                        'email' => $email,
                        'domain' => $domain,
                        'status' => 'active',
                        'expires_at' => $response['expires_at'] ?? null,
                        'activated_at' => date('Y-m-d H:i:s'),
                        'last_check' => date('Y-m-d H:i:s'),
                        'fingerprint' => $fingerprint,
                        'installation_id' => hash('sha256', $domain . microtime(true))
                    ];
                    
                    $json = json_encode($licenseData);
                    $key = hash('sha256', $_SERVER['HTTP_HOST'] . $_SERVER['DOCUMENT_ROOT'], true);
                    $iv = openssl_random_pseudo_bytes(16);
                    $encrypted = openssl_encrypt($json, 'AES-256-CBC', $key, 0, $iv);
                    $encoded = base64_encode($iv . $encrypted);
                    
                    file_put_contents('license.key', $encoded);
                    @chmod('license.key', 0600);
                    
                    $message = 'License activated successfully! Redirecting...';
                    header('Refresh: 2; url=dashboard.php');
                } else {
                    $error = $response['message'] ?? 'License activation failed. Please check your license key and email.';
                }
            }
        }
    }
}

// Get current domain
$currentDomain = $_SERVER['HTTP_HOST'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Activate License - SAS System</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            padding: 50px;
            max-width: 500px;
            width: 100%;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #4f46e5 0%, #8b5cf6 100%);
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
            font-size: 2.5rem;
            color: white;
        }

        h1 {
            font-size: 2rem;
            color: #1e293b;
            margin-bottom: 10px;
            font-weight: 800;
        }

        .subtitle {
            color: #64748b;
            font-size: 1rem;
        }

        .alert {
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
        }

        .alert-info {
            background: #dbeafe;
            color: #1e40af;
        }

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

        label {
            display: block;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 8px;
            font-size: 0.9rem;
        }

        input {
            width: 100%;
            padding: 14px 16px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 0.95rem;
            transition: all 0.3s;
        }

        input:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        .btn {
            width: 100%;
            padding: 16px 20px;
            border: none;
            border-radius: 10px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #4f46e5 0%, #8b5cf6 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 20px -10px rgba(79, 70, 229, 0.5);
        }

        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .info-box {
            background: #f8fafc;
            border-left: 4px solid #4f46e5;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 25px;
            font-size: 0.9rem;
        }

        .info-box strong {
            color: #1e293b;
            display: block;
            margin-bottom: 5px;
        }

        .domain-info {
            background: #f1f5f9;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
            font-size: 0.9rem;
        }

        .domain-info strong {
            color: #475569;
            display: block;
            margin-bottom: 5px;
        }

        .domain-value {
            color: #4f46e5;
            font-weight: 700;
            font-family: monospace;
            font-size: 1.1rem;
        }

        .help-link {
            text-align: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #e2e8f0;
        }

        .help-link a {
            color: #4f46e5;
            text-decoration: none;
            font-weight: 600;
            font-size: 0.9rem;
        }

        .help-link a:hover {
            text-decoration: underline;
        }

        .spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255,255,255,0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.6s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        @media (max-width: 480px) {
            .container {
                padding: 30px;
            }
            
            h1 {
                font-size: 1.5rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="icon">
                <i class="bi bi-key-fill"></i>
            </div>
            <h1>Activate License</h1>
            <p class="subtitle">Enter your license key to activate SAS System</p>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-success">
                <i class="bi bi-check-circle-fill" style="font-size: 1.5rem;"></i>
                <div>
                    <strong>Success!</strong><br>
                    <?= htmlspecialchars($message) ?>
                    <br><small>Redirecting to dashboard...</small>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-error">
                <i class="bi bi-exclamation-triangle-fill" style="font-size: 1.5rem;"></i>
                <div>
                    <strong>Activation Failed</strong><br>
                    <?= $error ?>
                </div>
            </div>
        <?php endif; ?>

        <div class="info-box">
            <strong>ߒ Before You Start:</strong>
            Make sure you have your license key and purchase email ready.
            Your license will be bound to this domain.
        </div>

        <div class="domain-info">
            <strong>License will be activated for:</strong>
            <div class="domain-value"><?= htmlspecialchars($currentDomain) ?></div>
        </div>

        <form method="POST" id="activationForm">
            <input type="hidden" name="action" value="activate">
            
            <div class="form-group">
                <label for="license_key">
                    <i class="bi bi-key"></i> License Key
                </label>
                <input 
                    type="text" 
                    id="license_key" 
                    name="license_key" 
                    placeholder="XXXX-XXXX-XXXX-XXXX" 
                    required
                    pattern="[A-Z0-9\-]+"
                    style="text-transform: uppercase;"
                >
                <small style="color: #64748b; font-size: 0.85rem; display: block; margin-top: 5px;">
                    Format: XXXX-XXXX-XXXX-XXXX
                </small>
            </div>

            <div class="form-group">
                <label for="email">
                    <i class="bi bi-envelope"></i> Purchase Email
                </label>
                <input 
                    type="email" 
                    id="email" 
                    name="email" 
                    placeholder="your@email.com" 
                    required
                >
                <small style="color: #64748b; font-size: 0.85rem; display: block; margin-top: 5px;">
                    The email address used during purchase
                </small>
            </div>

            <button type="submit" class="btn btn-primary">
                <i class="bi bi-unlock-fill"></i>
                Activate License
            </button>
        </form>

        <div class="help-link">
            <a href="mailto:support@apasaja.my">
                <i class="bi bi-question-circle"></i> Need help? Contact Support
            </a>
        </div>
    </div>

    <script>
        // Auto-format license key
        document.getElementById('license_key').addEventListener('input', function(e) {
            let value = e.target.value.replace(/[^A-Z0-9]/g, '');
            let formatted = '';
            
            for (let i = 0; i < value.length && i < 20; i++) {
                if (i > 0 && i % 4 === 0) {
                    formatted += '-';
                }
                formatted += value[i];
            }
            
            e.target.value = formatted;
        });

        // Form submission
        document.getElementById('activationForm').addEventListener('submit', function(e) {
            const btn = this.querySelector('button[type="submit"]');
            btn.innerHTML = '<span class="spinner"></span> Activating...';
            btn.disabled = true;
        });
    </script>
</body>
</html>
