<?php
/**
 * ============================================
 * LICENSE CLIENT - Taruh di aplikasi billing
 * File ini mengecek lisensi ke server Anda
 * ============================================
 */

// ===== KONFIGURASI - GANTI SESUAI SERVER ANDA =====
define('LICENSE_SERVER', 'https://escobargame.site/license/api.php'); // Ganti dengan URL hosting Anda
define('LICENSE_CHECK_INTERVAL', 3600); // Cek setiap 1 jam (dalam detik)

class LicenseManager {
    
    private $license_key;
    private $cache_file;
    private $domain;
    
    public function __construct() {
        $this->cache_file = __DIR__ . '/license_cache.json';
        $this->domain = $this->getDomain();
        $this->license_key = $this->getLicenseKey();
    }
    
    /**
     * Validasi lisensi - Panggil ini di awal aplikasi
     */
    public function validate() {
        // Cek apakah ada license key
        if (empty($this->license_key)) {
            return $this->fail('NO_LICENSE', 'License key belum dikonfigurasi');
        }
        
        // Cek cache dulu (untuk mengurangi request ke server)
        $cache = $this->getCache();
        if ($cache && $this->isCacheValid($cache)) {
            return $this->success($cache['data']);
        }
        
        // Validasi ke server
        return $this->validateOnline();
    }
    
    /**
     * Aktivasi lisensi pertama kali
     */
    public function activate($license_key) {
        $this->license_key = $license_key;
        
        $response = $this->request('activate', [
            'license_key' => $license_key,
            'domain' => $this->domain
        ]);
        
        if ($response && $response['status'] === 'success') {
            // Simpan license key ke config
            $this->saveLicenseKey($license_key);
            
            // Update cache
            $this->setCache($response);
            
            return $this->success($response['data'] ?? []);
        }
        
        return $this->fail(
            $response['code'] ?? 'ACTIVATION_FAILED',
            $response['message'] ?? 'Aktivasi gagal'
        );
    }
    
    /**
     * Validasi online ke server
     */
    private function validateOnline() {
        $response = $this->request('validate', [
            'license_key' => $this->license_key,
            'domain' => $this->domain
        ]);
        
        if ($response && $response['status'] === 'success') {
            $this->setCache($response);
            return $this->success($response['data'] ?? []);
        }
        
        // Jika gagal connect, cek grace period dari cache
        if (!$response) {
            $cache = $this->getCache();
            if ($cache && $this->isGracePeriod($cache)) {
                return $this->success($cache['data'], true); // true = grace period
            }
        }
        
        return $this->fail(
            $response['code'] ?? 'VALIDATION_FAILED',
            $response['message'] ?? 'Validasi lisensi gagal'
        );
    }
    
    /**
     * Request ke license server
     */
    private function request($action, $data = []) {
        $url = LICENSE_SERVER . '?action=' . $action;
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_USERAGENT => 'BillingPS-Client/1.0'
        ]);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            error_log("License Server Error: " . $error);
            return null;
        }
        
        return json_decode($response, true);
    }
    
    /**
     * Get domain/IP saat ini
     */
    private function getDomain() {
        return $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
    }
    
    /**
     * Get license key dari config
     */
    private function getLicenseKey() {
        // Coba baca dari file config
        $config_file = __DIR__ . '/license_key.php';
        if (file_exists($config_file)) {
            include $config_file;
            return defined('LICENSE_KEY') ? LICENSE_KEY : '';
        }
        return '';
    }
    
    /**
     * Simpan license key ke file
     */
    private function saveLicenseKey($key) {
        $content = "<?php\n// License Key - Jangan dihapus!\ndefine('LICENSE_KEY', '" . addslashes($key) . "');\n";
        file_put_contents(__DIR__ . '/license_key.php', $content);
    }
    
    /**
     * Cache management
     */
    private function getCache() {
        if (!file_exists($this->cache_file)) return null;
        $data = json_decode(file_get_contents($this->cache_file), true);
        return $data;
    }
    
    private function setCache($response) {
        $cache = [
            'timestamp' => time(),
            'data' => $response['data'] ?? [],
            'status' => $response['status']
        ];
        file_put_contents($this->cache_file, json_encode($cache));
    }
    
    private function isCacheValid($cache) {
        // Cache valid jika belum lewat interval
        return (time() - $cache['timestamp']) < LICENSE_CHECK_INTERVAL;
    }
    
    private function isGracePeriod($cache) {
        // Grace period 7 hari jika tidak bisa connect ke server
        $grace_days = 7;
        return (time() - $cache['timestamp']) < ($grace_days * 86400);
    }
    
    /**
     * Response helpers
     */
    private function success($data, $grace = false) {
        return [
            'valid' => true,
            'grace_period' => $grace,
            'data' => $data
        ];
    }
    
    private function fail($code, $message) {
        return [
            'valid' => false,
            'code' => $code,
            'message' => $message
        ];
    }
    
    /**
     * Get info lisensi
     */
    public function getInfo() {
        $cache = $this->getCache();
        return $cache['data'] ?? null;
    }
    
    /**
     * Cek apakah mendekati expired
     */
    public function isExpiringSoon($days = 7) {
        $cache = $this->getCache();
        if ($cache && isset($cache['data']['days_remaining'])) {
            return $cache['data']['days_remaining'] <= $days;
        }
        return false;
    }
}

// ===== FUNGSI HELPER =====

/**
 * Cek lisensi - panggil di awal aplikasi
 */
function checkLicense() {
    $license = new LicenseManager();
    $result = $license->validate();
    
    if (!$result['valid']) {
        // Redirect ke halaman aktivasi
        header('Location: activate.php?error=' . urlencode($result['message']));
        exit;
    }
    
    // Simpan info ke session untuk ditampilkan
    $_SESSION['license_info'] = $result['data'];
    $_SESSION['license_grace'] = $result['grace_period'] ?? false;
    
    return $result;
}

/**
 * Cek apakah lisensi aktif (tanpa redirect)
 */
function isLicenseValid() {
    $license = new LicenseManager();
    $result = $license->validate();
    return $result['valid'];
}
