<?php
/**
 * ============================================================================
 * MixToko License Guard for CodeIgniter (CI4 & CI3)
 * Versi: 2.1 (Full Auto Domain-Lock & Protection Screen)
 * ============================================================================
 * 
 * CARA PEMASANGAN DI CODEIGNITER 4:
 * ----------------------------------------------------------------------------
 * OPSI A: SEBAGAI FILTER GLOBAL (Sangat Direkomendasikan):
 * 1. Simpan file ini di: app/Filters/MixTokoLicenseFilter.php
 * 2. Tambahkan namespace jika perlu: namespace App\Filters; use CodeIgniter\Filters\FilterInterface; ...
 * 3. Buka app/Config/Filters.php dan daftarkan:
 *    public array $aliases = [
 *        'license' => \App\Filters\MixTokoLicenseFilter::class,
 *    ];
 *    public array $globals = [
 *        'before' => ['license'],
 *    ];
 * 4. Tambahkan kunci lisensi di file .env Anda:
 *    MIXTOKO_LICENSE_KEY=MTK-REG-XXXX-XXXX-XXXX
 * 
 * OPSI B: SEBAGAI BOOTSTRAP / PRE-SYSTEM (CI3 & CI4):
 * 1. Simpan file ini di: app/Common.php (atau application/hooks/ di CI3).
 * 2. Panggil: MixTokoLicenseGuard::protect(env('MIXTOKO_LICENSE_KEY') ?? 'KUNCI_LISENSI');
 * ============================================================================
 */

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class MixTokoLicenseFilter implements FilterInterface {
    public static $verifyEndpoint = 'https://mixtoko.net/api/v1/license/verify';

    public function before(RequestInterface $request, $arguments = null) {
        $licenseKey = env('MIXTOKO_LICENSE_KEY') ?: (defined('MIXTOKO_LICENSE_KEY') ? MIXTOKO_LICENSE_KEY : '');
        
        // Jika tidak diset di .env, periksa di session atau config
        if (empty($licenseKey) && function_exists('config')) {
            $appConfig = config('App');
            $licenseKey = $appConfig->licenseKey ?? '';
        }

        return self::protect($licenseKey);
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {
        // Tidak ada aksi setelah request
    }

    public static function protect($licenseKey, $cacheHours = 6) {
        $licenseKey = trim((string)$licenseKey);
        $domain = self::getCurrentDomain();

        if (empty($licenseKey)) {
            self::renderLockScreen([
                'status' => 'missing_key',
                'message' => 'Kunci lisensi belum diatur di file .env (MIXTOKO_LICENSE_KEY=...).'
            ], '(Kosong)', $domain);
            exit;
        }

        $cacheFile = sys_get_temp_dir() . '/mtk_lic_' . md5($licenseKey . '_' . $domain) . '.json';

        $data = null;
        if ($cacheHours > 0 && file_exists($cacheFile) && (time() - filemtime($cacheFile) < ($cacheHours * 3600))) {
            $cached = @json_decode(@file_get_contents($cacheFile), true);
            if (!empty($cached) && isset($cached['valid'])) {
                $data = $cached;
            }
        }

        if (!$data) {
            $data = self::callApi($licenseKey, $domain);
            if (!empty($data) && isset($data['valid'])) {
                @file_put_contents($cacheFile, json_encode($data));
            }
        }

        // Jika lisensi tidak valid (beda domain pada Regular License, suspended, dll)
        if (empty($data['valid'])) {
            self::renderLockScreen($data, $licenseKey, $domain);
            exit;
        }

        return $data;
    }

    public static function getCurrentDomain() {
        $host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
        $host = strtolower(trim((string)$host));
        $host = preg_replace('#^www\.#i', '', $host);
        $parts = explode(':', $host);
        return trim($parts[0]);
    }

    protected static function callApi($licenseKey, $domain) {
        $payload = json_encode([
            'license_key' => $licenseKey,
            'domain' => $domain,
            'framework' => 'CodeIgniter'
        ]);

        if (function_exists('curl_init')) {
            $ch = curl_init(self::$verifyEndpoint);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $payload,
                CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Accept: application/json'],
                CURLOPT_TIMEOUT => 15,
                CURLOPT_SSL_VERIFYPEER => false
            ]);
            $resp = curl_exec($ch);
            curl_close($ch);
            $json = json_decode($resp, true);
            if (!empty($json)) return $json;
        }

        $ctx = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => "Content-Type: application/json\r\nAccept: application/json\r\n",
                'content' => $payload,
                'timeout' => 15
            ]
        ]);
        $resp = @file_get_contents(self::$verifyEndpoint, false, $ctx);
        return json_decode($resp, true) ?: [
            'valid' => false,
            'status' => 'connection_error',
            'message' => 'Gagal terhubung ke server verifikasi lisensi MixToko.'
        ];
    }

    public static function maskKey($key) {
        $key = trim((string)$key);
        if (empty($key)) return '••••••••••••••••';
        $parts = explode('-', $key);
        if (count($parts) >= 4) {
            // e.g. MTK-REG-F438-140B-8696 -> MTK-REG-••••-••••-8696
            return $parts[0] . '-' . $parts[1] . '-••••-••••-' . end($parts);
        } elseif (count($parts) === 3) {
            return $parts[0] . '-••••-' . end($parts);
        }
        $len = strlen($key);
        if ($len <= 8) return '••••••••';
        return substr($key, 0, 4) . '••••' . substr($key, -4);
    }

    public static function renderLockScreen($info, $licenseKey, $currentDomain) {
        while (ob_get_level()) {
            @ob_end_clean();
        }
        @http_response_code(403);

        $status = $info['status'] ?? 'invalid';
        $msg = $info['message'] ?? 'Lisensi tidak valid atau tidak diizinkan untuk domain ini.';
        $regDomain = $info['registered_domain'] ?? 'Tidak Diketahui';
        $maskedKey = self::maskKey($licenseKey);
        
        $isMismatch = ($status === 'domain_mismatch');
        $isSuspended = ($status === 'suspended');
        $isRevoked = ($status === 'revoked');

        // Styling and text by status
        if ($isSuspended) {
            $badgeText = 'Lisensi Ditangguhkan';
            $badgeColor = '#f59e0b';
            $badgeBg = 'rgba(245, 158, 11, 0.15)';
            $badgeBorder = 'rgba(245, 158, 11, 0.3)';
            $iconClass = 'fas fa-pause-circle';
            $iconColor = '#f59e0b';
            $iconBg = 'rgba(245, 158, 11, 0.12)';
            $iconBorder = 'rgba(245, 158, 11, 0.3)';
            $title = 'Akses Aplikasi Ditangguhkan Sementara';
            $desc = 'Lisensi untuk aplikasi ini sedang dalam status <b>Suspended (Ditangguhkan)</b> oleh pemilik produk atau administrator MixToko. Seluruh halaman menu, route, dan fitur dinonaktifkan sementara waktu.';
        } elseif ($isRevoked) {
            $badgeText = 'Lisensi Dicabut';
            $badgeColor = '#ef4444';
            $badgeBg = 'rgba(239, 68, 68, 0.15)';
            $badgeBorder = 'rgba(239, 68, 68, 0.3)';
            $iconClass = 'fas fa-ban';
            $iconColor = '#ef4444';
            $iconBg = 'rgba(239, 68, 68, 0.12)';
            $iconBorder = 'rgba(239, 68, 68, 0.3)';
            $title = 'Lisensi Telah Dicabut Permanen';
            $desc = 'Lisensi untuk aplikasi ini telah dicabut permanen (Revoked). Akses aplikasi dihentikan total.';
        } elseif ($isMismatch) {
            $badgeText = 'Domain Tidak Diizinkan';
            $badgeColor = '#f87171';
            $badgeBg = 'rgba(239, 68, 68, 0.15)';
            $badgeBorder = 'rgba(239, 68, 68, 0.3)';
            $iconClass = 'fas fa-shield-alt';
            $iconColor = '#ef4444';
            $iconBg = 'rgba(239, 68, 68, 0.12)';
            $iconBorder = 'rgba(239, 68, 68, 0.3)';
            $title = 'Lisensi Terkunci di Domain Lain';
            $desc = 'Kunci lisensi yang digunakan bertipe <b>Regular License</b> yang terikat khusus untuk satu domain pertama kali instalasi. Seluruh halaman menu, dashboard admin, dan fitur aplikasi dinonaktifkan di domain ini.';
        } else {
            $badgeText = 'Akses Aplikasi Terkunci';
            $badgeColor = '#f87171';
            $badgeBg = 'rgba(239, 68, 68, 0.15)';
            $badgeBorder = 'rgba(239, 68, 68, 0.3)';
            $iconClass = 'fas fa-lock';
            $iconColor = '#ef4444';
            $iconBg = 'rgba(239, 68, 68, 0.12)';
            $iconBorder = 'rgba(239, 68, 68, 0.3)';
            $title = 'Lisensi Tidak Valid';
            $desc = htmlspecialchars($msg);
        }
        ?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aplikasi Terkunci — <?= htmlspecialchars($title); ?> | MixToko</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"/>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif; background: #090d16; color: #f8fafc; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px 16px; }
        .lock-container { width: 100%; max-width: 580px; background: #0f172a; border: 1px solid #1e293b; border-radius: 20px; padding: 32px 28px; box-shadow: 0 25px 60px rgba(0,0,0,0.5); text-align: center; }
        .lock-icon-wrap { width: 76px; height: 76px; background: <?= $iconBg; ?>; border: 2px solid <?= $iconBorder; ?>; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; color: <?= $iconColor; ?>; font-size: 32px; margin-bottom: 20px; }
        .lock-badge { display: inline-block; background: <?= $badgeBg; ?>; color: <?= $badgeColor; ?>; border: 1px solid <?= $badgeBorder; ?>; font-size: 11.5px; font-weight: 800; padding: 4px 14px; border-radius: 9999px; text-transform: uppercase; letter-spacing: 0.8px; margin-bottom: 12px; }
        .lock-title { font-size: 22px; font-weight: 800; color: #ffffff; line-height: 1.3; margin-bottom: 8px; }
        .lock-desc { font-size: 13.5px; color: #94a3b8; line-height: 1.6; margin-bottom: 24px; }
        .info-box { background: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 16px; margin-bottom: 24px; text-align: left; font-size: 12.5px; }
        .info-row { display: flex; justify-content: space-between; padding: 7px 0; border-bottom: 1px solid rgba(255,255,255,0.06); gap: 12px; }
        .info-row:last-child { border-bottom: none; }
        .info-lbl { color: #94a3b8; font-weight: 600; flex-shrink: 0; }
        .info-val { color: #f1f5f9; font-weight: 700; word-break: break-all; text-align: right; }
        .info-val.danger { color: #f87171; }
        .info-val.warning { color: #fbbf24; }
        .info-val.success { color: #34d399; }
        .info-val.mono { font-family: monospace; }
        .action-btns { display: flex; flex-direction: column; gap: 10px; }
        .btn-primary { display: inline-flex; align-items: center; justify-content: center; gap: 8px; background: #0284c7; color: #ffffff; text-decoration: none; padding: 12px 20px; border-radius: 10px; font-weight: 800; font-size: 13.5px; transition: all 0.15s; }
        .btn-primary:hover { background: #0369a1; }
        .btn-secondary { display: inline-flex; align-items: center; justify-content: center; gap: 8px; background: rgba(255,255,255,0.06); border: 1px solid #334155; color: #cbd5e1; text-decoration: none; padding: 11px 20px; border-radius: 10px; font-weight: 700; font-size: 13px; transition: all 0.15s; }
        .btn-secondary:hover { background: rgba(255,255,255,0.1); color: #ffffff; }
        .lock-footer { margin-top: 24px; font-size: 11px; color: #64748b; }
    </style>
</head>
<body>
    <div class="lock-container">
        <div class="lock-icon-wrap">
            <i class="<?= $iconClass; ?>"></i>
        </div>
        
        <div>
            <span class="lock-badge"><?= htmlspecialchars($badgeText); ?></span>
        </div>

        <h1 class="lock-title"><?= htmlspecialchars($title); ?></h1>

        <p class="lock-desc"><?= $desc; ?></p>

        <div class="info-box">
            <div class="info-row">
                <span class="info-lbl"><i class="fas fa-key"></i> Kunci Lisensi:</span>
                <span class="info-val mono"><?= htmlspecialchars($maskedKey); ?> <span style="font-size:10px; color:#94a3b8; font-weight:normal;">(Privasi Terlindungi)</span></span>
            </div>
            
            <?php if ($isMismatch): ?>
            <div class="info-row">
                <span class="info-lbl"><i class="fas fa-certificate"></i> Tipe Lisensi:</span>
                <span class="info-val">Regular License (1 Domain)</span>
            </div>
            <div class="info-row">
                <span class="info-lbl"><i class="fas fa-check-circle"></i> Domain Terdaftar:</span>
                <span class="info-val success"><?= htmlspecialchars($regDomain); ?></span>
            </div>
            <div class="info-row">
                <span class="info-lbl"><i class="fas fa-times-circle"></i> Domain Saat Ini:</span>
                <span class="info-val danger"><?= htmlspecialchars($currentDomain); ?></span>
            </div>
            <?php endif; ?>

            <div class="info-row">
                <span class="info-lbl"><i class="fas fa-info-circle"></i> Status Sistem:</span>
                <span class="info-val <?= $isSuspended ? 'warning' : 'danger'; ?>"><?= htmlspecialchars($status); ?></span>
            </div>
        </div>

        <div class="action-btns">
            <?php if ($isMismatch): ?>
                <a href="https://mixtoko.net/user/license" target="_blank" class="btn-primary">
                    <i class="fas fa-arrow-circle-up"></i> Beli / Upgrade ke Advance License di MixToko
                </a>
            <?php elseif ($isSuspended): ?>
                <a href="https://mixtoko.net/user/license" target="_blank" class="btn-primary" style="background:#f59e0b; color:#000;">
                    <i class="fas fa-headset"></i> Hubungi Penjual / Buka Panel Lisensi MixToko
                </a>
            <?php else: ?>
                <a href="https://mixtoko.net/user/license" target="_blank" class="btn-primary">
                    <i class="fas fa-external-link-alt"></i> Cek Lisensi di MixToko
                </a>
            <?php endif; ?>

            <a href="https://mixtoko.net" target="_blank" class="btn-secondary">
                <i class="fas fa-store"></i> Kunjungi Marketplace MixToko
            </a>
        </div>

        <div class="lock-footer">
            Protected by MixToko Anti-Piracy & Digital License Security System
        </div>
    </div>
</body>
</html>
        <?php
        exit;
    }
}
