<?php
/**
 * ============================================================================
 * MixToko License Guard for Laravel (Laravel 9, 10, 11)
 * Versi: 2.1 (Full Auto Domain-Lock & Protection Screen)
 * ============================================================================
 * 
 * CARA PEMASANGAN DI LARAVEL:
 * ----------------------------------------------------------------------------
 * 1. Simpan file ini di: app/Http/Middleware/MixTokoLicenseGuard.php
 * 2. Tambahkan kunci lisensi di file .env Laravel Anda:
 *    MIXTOKO_LICENSE_KEY=MTK-REG-XXXX-XXXX-XXXX
 * 
 * 3. Daftarkan Middleware di Laravel:
 *    - Laravel 11 (bootstrap/app.php):
 *      ->withMiddleware(function (Middleware $middleware) {
 *          $middleware->append(\App\Http\Middleware\MixTokoLicenseGuard::class);
 *      })
 * 
 *    - Laravel 9 & 10 (app/Http/Kernel.php):
 *      protected $middleware = [
 *          // ... middleware lainnya ...
 *          \App\Http\Middleware\MixTokoLicenseGuard::class,
 *      ];
 * 
 * ============================================================================
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

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

    public function handle(Request $request, Closure $next): Response {
        $licenseKey = config('services.mixtoko.license_key') ?: env('MIXTOKO_LICENSE_KEY');

        $domain = $request->getHost();
        $domain = preg_replace('#^www\.#i', '', strtolower(trim($domain)));

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

        $cacheKey = 'mtk_lic_' . md5($licenseKey . '_' . $domain);
        $data = null;

        // Cek Cache Laravel jika tersedia
        if (function_exists('cache')) {
            $data = cache()->get($cacheKey);
        }

        if (!$data) {
            $data = self::callApi($licenseKey, $domain);
            if (!empty($data) && isset($data['valid']) && function_exists('cache')) {
                cache()->put($cacheKey, $data, now()->addHours(6));
            }
        }

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

        return $next($request);
    }

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

        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) {
            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 getLockScreenHtml($info, $licenseKey, $currentDomain) {
        $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');

        if ($isSuspended) {
            $badge = '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 route, controller, dan fitur Laravel dinonaktifkan sementara waktu.';
        } elseif ($isRevoked) {
            $badge = '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) {
            $badge = '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 route, controller, dan fitur Laravel dinonaktifkan di domain ini.';
        } else {
            $badge = '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);
        }

        $escMasked = htmlspecialchars($maskedKey);
        $escReg = htmlspecialchars($regDomain);
        $escCur = htmlspecialchars($currentDomain);
        $escStatus = htmlspecialchars($status);

        $extraRows = '';
        if ($isMismatch) {
            $extraRows = '
            <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">' . $escReg . '</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">' . $escCur . '</span></div>';
        }

        $actionBtn = '';
        if ($isMismatch) {
            $actionBtn = '<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>';
        } elseif ($isSuspended) {
            $actionBtn = '<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>';
        } else {
            $actionBtn = '<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>';
        }

        return <<<HTML
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aplikasi Terkunci — {$title} | MixToko (Laravel)</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', 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 { 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; }
        .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; }
        .lock-footer { margin-top: 24px; font-size: 11px; color: #64748b; }
    </style>
</head>
<body>
    <div class="lock-container">
        <div class="lock-icon"><i class="{$iconClass}"></i></div>
        <div><span class="lock-badge">{$badge}</span></div>
        <h1 class="lock-title">{$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">{$escMasked} <span style="font-size:10px; color:#94a3b8; font-weight:normal;">(Privasi Terlindungi)</span></span></div>
            {$extraRows}
            <div class="info-row"><span class="info-lbl"><i class="fas fa-info-circle"></i> Status Sistem:</span><span class="info-val danger">{$escStatus}</span></div>
        </div>
        <div class="action-btns">
            {$actionBtn}
            <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>
HTML;
    }
}
