<?php
/**
 * HALAMAN AKTIVASI LISENSI
 * Clean version - no obfuscation
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

date_default_timezone_set('Asia/Jakarta');

$db_config = [
    'host' => 'localhost',
    'user' => 'root',
    'pass' => '',
    'name' => 'db_rental_ps'
];

try {
    $conn = new mysqli($db_config['host'], $db_config['user'], $db_config['pass'], $db_config['name']);
    $conn->set_charset("utf8mb4");
} catch (Exception $e) {
    die("Database Error: " . $e->getMessage());
}

// ✅ FIXED: domain .fun (bukan .site)
define('API_URL', 'https://escobargame.fun/license/api.php');

function get_setting_local($conn, $key) {
    $stmt = $conn->prepare("SELECT setting_value FROM system_settings WHERE setting_name = ? LIMIT 1");
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $res  = $stmt->get_result();
    $val  = ($row = $res->fetch_assoc()) ? $row['setting_value'] : '';
    $stmt->close();
    return $val;
}

// Jika sudah ada key di DB, validasi dulu ke server
$existing_key = trim(get_setting_local($conn, 'license_key'));

if (!empty($existing_key)) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => API_URL,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query([
            'action'      => 'validate',
            'license_key' => $existing_key,
            'domain'      => $_SERVER['HTTP_HOST'] ?? 'localhost'
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $response = curl_exec($ch);
    curl_close($ch);

    if ($response) {
        $result = json_decode($response, true);
        if (isset($result['status']) && in_array(strtolower($result['status']), ['success', 'active'])) {
            $_SESSION['lic_status']       = 'success';
            $_SESSION['lic_last_check']   = time();
            $_SESSION['lic_last_success'] = time();
            $_SESSION['lic_client_name']  = $result['data']['client_name']    ?? '';
            $_SESSION['lic_expired_at']   = $result['data']['expired_at']     ?? '';
            $_SESSION['lic_days_remaining'] = $result['data']['days_remaining'] ?? 0;
            header("Location: index.php");
            exit();
        }
    }
}

$error   = '';
$success = '';

// Handle POST aktivasi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['license_key'])) {
    $key = trim($_POST['license_key']);
    $key = strtoupper(preg_replace('/[^A-Za-z0-9\-]/', '', $key));

    if (empty($key)) {
        $error = 'License key tidak boleh kosong!';
    } else {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => API_URL,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => http_build_query([
                'action'      => 'activate',
                'license_key' => $key,
                'domain'      => $_SERVER['HTTP_HOST'] ?? 'localhost'
            ]),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);

        $response  = curl_exec($ch);
        $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($curlError) {
            $error = 'Gagal terhubung ke server: ' . $curlError;
        } elseif ($httpCode != 200) {
            $error = 'Server error (HTTP ' . $httpCode . ')';
        } elseif ($response) {
            $result = json_decode($response, true);

            if ($result && isset($result['status']) && in_array(strtolower($result['status']), ['success', 'active'])) {
                // Simpan ke DB
                $stmt = $conn->prepare("UPDATE system_settings SET setting_value = ? WHERE setting_name = 'license_key'");
                $stmt->bind_param("s", $key);
                $stmt->execute();
                $stmt->close();

                // Set session
                $_SESSION['lic_status']       = 'success';
                $_SESSION['lic_last_check']   = time();
                $_SESSION['lic_last_success'] = time();
                $_SESSION['lic_grace_mode']   = false;

                if (isset($result['data'])) {
                    $_SESSION['lic_client_name']    = $result['data']['client_name']    ?? 'Client';
                    $_SESSION['lic_expired_at']     = $result['data']['expired_at']     ?? date('Y-m-d', strtotime('+1 year'));
                    $_SESSION['lic_days_remaining'] = $result['data']['days_remaining'] ?? 365;
                    $_SESSION['lic_max_tv']         = $result['data']['max_tv']         ?? 0;
                }

                echo "<!DOCTYPE html><html><head>
                    <meta http-equiv='refresh' content='2;url=index.php'>
                    <title>Aktivasi Berhasil</title>
                    <style>
                        body { font-family: sans-serif; background: #111827; color: #10b981;
                               display: flex; align-items: center; justify-content: center;
                               min-height: 100vh; margin: 0; text-align: center; }
                        .icon { font-size: 4rem; margin-bottom: 20px; }
                    </style>
                </head><body>
                    <div>
                        <div class='icon'>✅</div>
                        <h1>Aktivasi Berhasil!</h1>
                        <p>Mengalihkan ke aplikasi...</p>
                    </div>
                </body></html>";
                exit();

            } else {
                $error = $result['message'] ?? 'License key tidak valid atau sudah digunakan.';
            }
        } else {
            $error = 'Tidak ada response dari server.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aktivasi Sistem</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
    <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
    <style>
        :root { --primary: #06b6d4; --bg-dark: #111827; --card-bg: #1f2937; }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg-dark);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            background: var(--card-bg);
            padding: 40px;
            border-radius: 24px;
            width: 100%;
            max-width: 420px;
            text-align: center;
            box-shadow: 0 20px 50px rgba(0,0,0,0.3);
            border: 1px solid rgba(255,255,255,0.05);
        }
        .logo-icon {
            width: 70px; height: 70px;
            background: linear-gradient(135deg, var(--primary), #0891b2);
            border-radius: 20px;
            display: flex; align-items: center; justify-content: center;
            margin: 0 auto 25px;
            font-size: 2rem; color: #fff;
        }
        h1 { font-size: 1.6rem; margin-bottom: 10px; }
        p  { color: #9ca3af; font-size: 0.9rem; margin-bottom: 30px; }

        .alert {
            padding: 15px 20px; border-radius: 12px; margin-bottom: 25px;
            font-size: 0.9rem; font-weight: 600;
            display: flex; align-items: center; gap: 10px; text-align: left;
        }
        .alert-error   { background: rgba(239,68,68,.15);  color: #f87171; border: 1px solid rgba(239,68,68,.3); }
        .alert-success { background: rgba(16,185,129,.15); color: #34d399; border: 1px solid rgba(16,185,129,.3); }

        .form-group { text-align: left; margin-bottom: 20px; }
        .form-group label {
            display: block; font-size: 0.75rem; color: #6b7280;
            font-weight: 700; text-transform: uppercase;
            margin-bottom: 10px; letter-spacing: 1px;
        }
        .license-input {
            width: 100%; padding: 16px 20px;
            background: #111827; border: 2px solid #374151;
            border-radius: 14px; color: #fff;
            font-size: 1.1rem; text-align: center;
            font-family: 'Courier New', monospace;
            letter-spacing: 3px; transition: all 0.3s;
        }
        .license-input:focus {
            outline: none; border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(6,182,212,0.1);
        }
        .license-input::placeholder { color: #4b5563; letter-spacing: 2px; }

        .btn-activate {
            width: 100%; padding: 16px;
            background: linear-gradient(135deg, var(--primary), #0891b2);
            color: #000; border: none; border-radius: 14px;
            font-weight: 800; cursor: pointer; transition: all 0.3s;
            font-size: 1rem; text-transform: uppercase; letter-spacing: 1px;
        }
        .btn-activate:hover { transform: translateY(-2px); box-shadow: 0 10px 30px rgba(6,182,212,0.3); }
        .btn-activate:disabled { opacity: 0.7; cursor: not-allowed; transform: none; }

        .help-text {
            margin-top: 30px; padding-top: 25px;
            border-top: 1px solid rgba(255,255,255,0.1);
            color: #6b7280; font-size: 0.8rem;
        }
        .help-text a { color: var(--primary); text-decoration: none; }
    </style>
</head>
<body>

<div class="container">
    <div class="logo-icon"><i class='bx bxs-key'></i></div>
    <h1>Aktivasi Sistem</h1>
    <p>Masukkan license key untuk memulai</p>

    <?php if ($error): ?>
        <div class="alert alert-error">
            <i class='bx bx-error-circle'></i>
            <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="alert alert-success">
            <i class='bx bx-check-circle'></i>
            <?= htmlspecialchars($success) ?>
        </div>
    <?php endif; ?>

    <form method="POST" id="formActivate">
        <div class="form-group">
            <label for="license_key">License Key</label>
            <input
                type="text"
                name="license_key"
                id="license_key"
                class="license-input"
                placeholder="XXXX-XXXX-XXXX-XXXX"
                maxlength="19"
                autocomplete="off"
                required
            >
        </div>
        <button type="submit" class="btn-activate" id="btnSubmit">
            <i class='bx bx-check-shield'></i> Aktifkan Sekarang
        </button>
    </form>

    <div class="help-text">
        <p>Belum punya license key?</p>
        <p>Hubungi: <a href="https://wa.me/6281811024">0818110242</a></p>
    </div>
</div>

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

// Disable button saat submit
document.getElementById('formActivate').addEventListener('submit', function() {
    const btn = document.getElementById('btnSubmit');
    btn.disabled = true;
    btn.innerHTML = '<i class="bx bx-loader-alt bx-spin"></i> Memproses...';
});
</script>

</body>
</html>