<?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'];

        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, &$packageName) {
    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;
                
                $apk = new \ApkParser\Parser($targetFilePath);
                $manifest = $apk->getManifest();
                $packageName = $manifest->getPackageName();

                return $baseUrl . $baseDir . '/public/' . $folder . '/' . $newFileName;
            }
        }
    }
    return null;
}

if (isset($_GET['id'])) {
    $appId = $_GET['id'];

    try {
        $db = new PDO('sqlite:./api/.apps.db');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $db->prepare("SELECT * FROM apks WHERE id = :id");
        $stmt->bindParam(':id', $appId);
        $stmt->execute();
        $app = $stmt->fetch(PDO::FETCH_ASSOC);

        if (isset($_POST['submit'])) {
            $nameapp = $_POST['nameapp'];
            $ext_provider = 1;
            $package = $app['package'];
            $fileimageName = null;
            $iconeapp = null;
            $extImage = null;

            if (isset($_POST['iconeapp_selector']) && $_POST['iconeapp_selector'] === 'upload') {
                $iconeapp = processImageUpload('iconeapp', 'iconeapp', $extImage, $fileimageName);
                if ($iconeapp && $app['iconeapp']) {
                    deleteOldFile($app['iconeapp']);
                }
            } else {
                $iconeapp = $_POST['iconeapp_url'];
                $extImage = pathinfo($iconeapp, PATHINFO_EXTENSION) === 'jpg' ? 0 : (pathinfo($iconeapp, PATHINFO_EXTENSION) === 'png' ? 1 : 2);
                $fileimageName = basename($iconeapp);
            }

            $localFilePath = '';
            $packageName = '';
            $buylink = processApkUpload('buylink', 'apkfiles', $localFilePath, $packageName);

            if ($packageName) {
                $package = $packageName;
            } else {
                $buylink = $app['buylink'];
            }

            if ($buylink && $app['buylink'] && $buylink !== $app['buylink']) {
                deleteOldFile($app['buylink']);
            }

            $stmt = $db->prepare("UPDATE apks SET nameapp = :nameapp, extimage = :extimage, ext_provider = :ext_provider, buylink = :buylink, package = :package, fileimage = :fileimage, iconeapp = :iconeapp WHERE id = :id");
            $stmt->bindParam(':nameapp', $nameapp);
            $stmt->bindParam(':extimage', $extImage);
            $stmt->bindParam(':ext_provider', $ext_provider);
            $stmt->bindParam(':buylink', $buylink);
            $stmt->bindParam(':package', $package);
            $stmt->bindParam(':fileimage', $fileimageName);
            $stmt->bindParam(':iconeapp', $iconeapp);
            $stmt->bindParam(':id', $appId);
            $stmt->execute();

            echo "<div class='alert alert-success'>Aplicativo atualizado com sucesso!</div>";
            echo "<script>
                    setTimeout(function() {
                        window.location.href = 'view_apps.php';
                    }, 3000);
                  </script>";
        }

    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
        die();
    }
} else {
    echo "No app ID provided.";
    die();
}
?>
<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 text-center text-dark mt-5">
                      <div class="row">
                        <div class="col-lg-12 d-block mx-auto mt-5">
                          <div class="row">
                            <div class="col-xl-12 col-md-12 col-md-12">
                              <div class="card">
                                <div class="card-body wow-bg" id="formBg">
                                  <center><h2 class="colorboard">Editar App</h2></center>
                                  <form method="post" enctype="multipart/form-data">
                                    <div class="form-group">
                                       <label class="form-label" for="nameapp">Nome do App</label>
                                       <input class="form-control" id="nameapp" name="nameapp" placeholder="Nome do App" value="<?= htmlspecialchars($app['nameapp']) ?>" type="text" required/>
                                    </div>
                                    <div class="form-group">
                                       <label class="form-label" for="buylink">Arquivo (APK)</label>
                                       <input class="form-control" id="buylink" name="buylink" type="file" accept=".apk" />
                                    </div>
                                    <div class="form-group">
                                       <label class="form-label" for="iconeapp">Ícone atual do aplicativo</label>
                                       <div class="img-edit-form">
                                        <?php if ($app['iconeapp']): ?>
                                        <img src="<?= htmlspecialchars($app['iconeapp']) ?>" alt="Icone App" style="max-width: 200px; height: auto; border-radius: 10px;">
                                        <?php endif; ?>
                                       </div>
                                       <label class="form-label" for="iconeapp">Escolha uma opção para carregar o ícone</label><br>
                                       <label class="form-label" for="iconeapp">Recomendação do tamanho: 320x180</label>
                                       <select class="form-control" id="iconeapp_selector" name="iconeapp_selector">
                                           <option value="upload">Upload</option>
                                           <option value="url" selected>URL</option>
                                       </select>
                                       <input class="form-control mt-2" id="iconeapp" name="iconeapp" type="file" accept=".jpg,.png,.jpeg" style="display:none;" />
                                       <input class="form-control mt-2" id="iconeapp_url" name="iconeapp_url" type="text" placeholder="URL da Imagem" value="<?= htmlspecialchars($app['iconeapp']) ?>" />
                                    </div>
                                    <input type="hidden" name="id" value="<?= $appId ?>" />
                                    <div class="form-group">
                                       <center><button class="btn btn-info" name="submit" type="submit">Salvar</button></center>
                                    </div>
                                  </form>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                </div>    
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('iconeapp_selector').addEventListener('change', function() {
    var fileInput = document.getElementById('iconeapp');
    var urlInput = document.getElementById('iconeapp_url');
    if (this.value === 'upload') {
        fileInput.style.display = 'block';
        urlInput.style.display = 'none';
    } else {
        fileInput.style.display = 'none';
        urlInput.style.display = 'block';
    }
});
</script>

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