<?php
require 'libs/php-apk-parser/vendor/autoload.php';
include 'includes/header.php';

function generateFileName() {
    return str_pad(mt_rand(0, PHP_INT_MAX), 22, '0', STR_PAD_LEFT);
}

function getBaseUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'];
    return $protocol . $domainName;
}

function getBaseDir() {
    $scriptDir = dirname($_SERVER['SCRIPT_NAME']);
    return $scriptDir;
}

function deleteOldFile($filePath) {
    $realPath = $_SERVER['DOCUMENT_ROOT'] . str_replace([getBaseUrl()], '', $filePath);
    if (file_exists($realPath)) {
        unlink($realPath);
    }
}

function sanitizeFileName($fileName) {
    $fileName = preg_replace('/[^A-Za-z0-9.]/', '', $fileName);
    $fileName = preg_replace('/\.+/', '.', $fileName);
    return $fileName;
}

function processImageUpload($fileInput, $folder, &$extImage, &$fileImageName) {
    if (isset($_FILES[$fileInput]) && $_FILES[$fileInput]["error"] == UPLOAD_ERR_OK) {
        $targetDir = __DIR__ . "/public/" . $folder . "/";
        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0755, true);
        }
        $fileExtension = strtolower(pathinfo($_FILES[$fileInput]["name"], PATHINFO_EXTENSION));
        $newFileName = generateFileName() . "." . $fileExtension;
        $targetFilePath = $targetDir . $newFileName;
        $fileType = mime_content_type($_FILES[$fileInput]["tmp_name"]);
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

        if (in_array($fileType, $allowedTypes)) {
            if (move_uploaded_file($_FILES[$fileInput]["tmp_name"], $targetFilePath)) {
                $baseUrl = getBaseUrl();
                $baseDir = getBaseDir();
                $baseDir = rtrim($baseDir, '/');
                $extImage = ($fileExtension == 'jpg') ? 0 : (($fileExtension == 'png') ? 1 : 2);
                $fileImageName = $newFileName;
                return $baseUrl . $baseDir . '/public/' . $folder . '/' . $newFileName;
            }
        }
    }
    return null;
}

function processApkUpload($fileInput, $folder, &$localFilePath) {
    if (isset($_FILES[$fileInput]) && $_FILES[$fileInput]["error"] == UPLOAD_ERR_OK) {
        $targetDir = __DIR__ . "/public/" . $folder . "/";
        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0755, true);
        }

        $originalFileName = pathinfo($_FILES[$fileInput]["name"], PATHINFO_FILENAME);
        $originalFileName = sanitizeFileName($originalFileName);
        $fileExtension = pathinfo($_FILES[$fileInput]["name"], PATHINFO_EXTENSION);
        $newFileName = $originalFileName . generateFileName() . "." . $fileExtension;

        $targetFilePath = $targetDir . $newFileName;
        $fileType = mime_content_type($_FILES[$fileInput]["tmp_name"]);
        $allowedTypes = ['application/vnd.android.package-archive'];

        if (in_array($fileType, $allowedTypes) || $fileExtension === 'apk') {
            if (move_uploaded_file($_FILES[$fileInput]["tmp_name"], $targetFilePath)) {
                $baseUrl = getBaseUrl();
                $baseDir = getBaseDir();
                $baseDir = rtrim($baseDir, '/');
                $localFilePath = $targetFilePath;
                return $baseUrl . $baseDir . '/public/' . $folder . '/' . $newFileName;
            }
        }
    }
    return null;
}

function getApkPackageName($filePath) {
    $apk = new \ApkParser\Parser($filePath);
    $manifest = $apk->getManifest();
    return $manifest->getPackageName();
}

if (isset($_POST['submit'])) {
    try {
        $db = new PDO('sqlite:./api/.apps.db');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $nameapp = $_POST['nameapp'];
        $ext_provider = 1;
        $owner_id = 'QE3-W2H';
        $buylink = null;
        $package = null;

        $fileimageName = null;
        $iconeapp = processImageUpload('iconeapp', 'iconeapp', $extimage, $fileimageName);

        if (isset($_FILES['apkfile'])) {
            $localFilePath = '';
            $buylink = processApkUpload('apkfile', 'apkfiles', $localFilePath);
            if ($buylink) {
                $package = getApkPackageName($localFilePath);
            }
        }

        $stmt = $db->prepare("INSERT INTO apks (owner_id, nameapp, extimage, fileimage, iconeapp, package, ext_provider, buylink) VALUES (:owner_id, :nameapp, :extimage, :fileimage, :iconeapp, :package, :ext_provider, :buylink)");
        $stmt->bindParam(':owner_id', $owner_id);
        $stmt->bindParam(':nameapp', $nameapp);
        $stmt->bindParam(':extimage', $extimage);
        $stmt->bindParam(':fileimage', $fileimageName);
        $stmt->bindParam(':iconeapp', $iconeapp);
        $stmt->bindParam(':package', $package);
        $stmt->bindParam(':ext_provider', $ext_provider);
        $stmt->bindParam(':buylink', $buylink);
        $stmt->execute();

        echo "App added successfully.";
        echo "<script>
                    setTimeout(function() {
                        window.location.href = 'view_apps.php';
                    }, 3000);
                  </script>";
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}
?>
<div class="card-body">
    <div class="card bg-primary text-white">
        <div class="card-header card-header-warning">
            <h2>Config Geral Launcher</h2>
        </div>
        <div class="card-body">
            <div class="alert alert-primary" role="alert">
                <div class="row">
                    <div class="container">
                        <h2>Upload App</h2>
                        <form action="upload_form.php" method="post" enctype="multipart/form-data">
                            <div class="form-group">
                                <label for="nameapp">Nome do aplicativo:</label>
                                <input type="text" class="form-control" name="nameapp" required>
                            </div>
                            <div class="form-group">
                                <label for="iconeapp">Ícone do aplicativo:</label>
                                <input type="file" class="form-control" name="iconeapp" accept=".jpg,.png,.jpeg" required>
                            </div>
                            <div class="form-group">
                                <label for="apkfile">Arquivo APK:</label>
                                <input type="file" class="form-control" name="apkfile" accept=".apk" required>
                            </div>
                            <button type="submit" class="btn btn-primary" name="submit">Subir</button>
                        </form>
                    </div>
                </div>    
            </div>
        </div>
    </div>
</div>

<?php
include 'includes/footer.php';
?>