<?php
require_once __DIR__ . "/classes/ApkParser.php";

$apkFiles = glob(__DIR__ . "/library/*.apk");
?>
<!DOCTYPE html>
<html>
<head>
    <title>APK Library Viewer</title>
    <style>
        body { font-family: Arial; background: #f5f5f5; padding: 20px; }
        table { width: 100%; border-collapse: collapse; background: white; }
        th, td { padding: 10px; border-bottom: 1px solid #ddd; vertical-align: top; }
        th { background: #333; color: white; }
        tr:hover { background: #f0f0f0; }
        img.icon { width: 64px; height: 64px; object-fit: contain; }
        .perm-tech { font-weight: bold; }
        .perm-human { color: #555; font-size: 12px; }
    </style>
</head>
<body>

<h1>📦 APK Library</h1>

<table>
    <tr>
        <th>Icon</th>
        <th>App</th>
        <th>Package</th>
        <th>Version</th>
        <th>SDK</th>
        <th>Permissions</th>
    </tr>

<?php
foreach ($apkFiles as $file) {
    try {
        $apk = new ApkParser($file);

        $icon = $apk->getIconBase64();
        $appName = $apk->getAppName();
        $pkg = $apk->getPackageName();
        $ver = $apk->getVersionName();
        $verCode = $apk->getVersionCode();
        $minSdk = $apk->getMinSdk();
        $targetSdk = $apk->getTargetSdk();
        $perms = $apk->getPermissionsDetailed();

        echo "<tr>";

        // Icon
        echo "<td>";
        if ($icon) {
            echo "<img class='icon' src='data:image/png;base64,$icon'>";
        } else {
            echo "—";
        }
        echo "</td>";

        // App name + file
        echo "<td><strong>$appName</strong><br><small>" . basename($file) . "</small></td>";

        echo "<td>$pkg</td>";
        echo "<td>$ver<br><small>Code: $verCode</small></td>";
        echo "<td>Min: $minSdk<br>Target: $targetSdk</td>";

        // Permissions
        echo "<td>";
        if (empty($perms)) {
            echo "None";
        } else {
            foreach ($perms as $p) {
                echo "<div class='perm-tech'>{$p['technical']}</div>";
                echo "<div class='perm-human'>{$p['friendly']}</div><br>";
            }
        }
        echo "</td>";

        echo "</tr>";

    } catch (Exception $e) {
        echo "<tr><td colspan='6'>Error reading " . basename($file) . "</td></tr>";
    }
}
?>

</table>

</body>
</html>