<?php
/**
 * Filename: check_license_api.php
 * Location: Root folder (School System)
 * Function: Jambatan antara butang 'Verify' di Admin Settings dan License Server
 */

require_once 'config.php';
header('Content-Type: application/json');

// 1. Semak fail lesen tempatan
if (!file_exists('license.key')) {
    echo json_encode(['success' => false, 'message' => 'Local license file not found. Please activate first.']);
    exit;
}

// 2. Baca dan Decrypt License Key Tempatan
try {
    $licenseContent = file_get_contents('license.key');
    $key = hash('sha256', $_SERVER['HTTP_HOST'] . $_SERVER['DOCUMENT_ROOT'], true);
    $decoded = base64_decode($licenseContent);
    
    if (strlen($decoded) <= 16) {
        throw new Exception("Invalid license file format");
    }

    $iv = substr($decoded, 0, 16);
    $encrypted = substr($decoded, 16);
    $decrypted = @openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
    
    if (!$decrypted) {
        throw new Exception("Decryption failed. Machine mismatch?");
    }

    $localData = json_decode($decrypted, true);
    if (!$localData || !isset($localData['license_key'])) {
        throw new Exception("Corrupted license data");
    }

    // 3. Persiapkan Data untuk dihantar ke Server
    // Kita guna action 'verify' sepertimana yang ada dalam license_server.php
    $postData = [
        'action' => 'verify',
        'license_key' => $localData['license_key'],
        'domain' => $_SERVER['HTTP_HOST']
    ];

    // 4. Hantar Request ke License Server
    $options = [
        'http' => [
            'header'  => "Content-Type: application/json\r\n",
            'method'  => 'POST',
            'content' => json_encode($postData),
            'timeout' => 10,
            'ignore_errors' => true // Tangkap error dari server jika ada
        ],
        "ssl" => [
            "verify_peer" => false,
            "verify_peer_name" => false,
        ],
    ];

    $context  = stream_context_create($options);
    $result = @file_get_contents(LICENSE_SERVER, false, $context);

    if ($result === FALSE) {
        throw new Exception("Could not connect to license server.");
    }

    // 5. Proses Jawapan dari Server
    $response = json_decode($result, true);

    if ($response && $response['success']) {
        // PENTING: Jika server kata OK, kita kemaskini data tempatan (sync)
        // Contohnya jika tarikh expired berubah atau status berubah
        
        $localData['status'] = $response['status'];
        if (isset($response['expires_at'])) {
            $localData['expires_at'] = $response['expires_at'];
        }
        $localData['last_check'] = date('Y-m-d H:i:s');

        // Simpan semula data yang telah dikemaskini ke fail license.key
        $jsonData = json_encode($localData);
        $newIv = openssl_random_pseudo_bytes(16);
        $newEncrypted = openssl_encrypt($jsonData, 'AES-256-CBC', $key, 0, $newIv);
        $newEncoded = base64_encode($newIv . $newEncrypted);
        
        file_put_contents('license.key', $newEncoded);

        echo json_encode([
            'success' => true,
            'status' => ucfirst($response['status']),
            'message' => 'License verified successfully with server.'
        ]);
    } else {
        // Jika server kata lesen tak valid (Suspended/Expired/Salah Domain)
        echo json_encode([
            'success' => false,
            'message' => $response['message'] ?? 'License verification failed at server.'
        ]);
    }

} catch (Exception $e) {
    echo json_encode([
        'success' => false, 
        'message' => $e->getMessage()
    ]);
}
?>