<?php
// editar_app.php

// Conexão com o banco SQLite
$dbPath = __DIR__ . '/api/max.db';
$db = new PDO('sqlite:' . $dbPath);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Recebe o ID pela query string
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

// Flags de retorno
$updated = isset($_GET['updated']);
$deleted = isset($_GET['deleted']);
$error = '';

// Tratamento de POST para update ou delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // Busca URLs antigas para gerenciar arquivos
    $stmtOld = $db->prepare("SELECT apk_url, icon_url FROM apps WHERE id = ?");
    $stmtOld->execute([$id]);
    $old = $stmtOld->fetch(PDO::FETCH_ASSOC);

    if ($_POST['action'] === 'update' && $old) {
        // Dados do formulário
        $name = trim($_POST['name']);
        $package = trim($_POST['package']);

        // Diretórios de upload
        $uploadsDirIcons = __DIR__ . '/uploads/icons/';
        $uploadsDirApks  = __DIR__ . '/uploads/apks/';
        if (!is_dir($uploadsDirIcons)) mkdir($uploadsDirIcons, 0777, true);
        if (!is_dir($uploadsDirApks))  mkdir($uploadsDirApks, 0777, true);

        // Base URL para montar os caminhos públicos
        $baseURL = (isset($_SERVER['HTTPS']) ? 'https' : 'http')
            . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);

        // Mantém URLs antigas até haver novo upload
        $iconUrl = $old['icon_url'];
        $apkUrl  = $old['apk_url'];

        // Se enviou novo ícone
        if (!empty(\$_FILES['icon_file']['tmp_name'])) {
            \$iconName = uniqid('icon_') . '_' . basename(\$_FILES['icon_file']['name']);
            \$iconPath = \$uploadsDirIcons . \$iconName;
            move_uploaded_file(\$_FILES['icon_file']['tmp_name'], \$iconPath);
            @unlink(__DIR__ . '/uploads/icons/' . basename(\$old['icon_url']));
            \$iconUrl = \$baseURL . '/uploads/icons/' . \$iconName;
        }

        // Se enviou novo APK
        if (!empty(\$_FILES['apk_file']['tmp_name'])) {
            \$apkName = uniqid('apk_') . '_' . basename(\$_FILES['apk_file']['name']);
            \$apkPath = \$uploadsDirApks . \$apkName;
            move_uploaded_file(\$_FILES['apk_file']['tmp_name'], \$apkPath);
            @unlink(__DIR__ . '/uploads/apks/' . basename(\$old['apk_url']));
            \$apkUrl = \$baseURL . '/uploads/apks/' . \$apkName;
        }

        // Atualiza no banco
        \$stmt = \$db->prepare("UPDATE apps SET name = ?, package = ?, apk_url = ?, icon_url = ? WHERE id = ?");
        \$stmt->execute([
            \$name,
            \$package,
            \$apkUrl,
            \$iconUrl,
            \$id
        ]);

        // Redireciona mantendo na tela de edição
        header('Location: editar_app.php?id=' . \$id . '&updated=1');
        exit;

    } elseif (\$_POST['action'] === 'delete' && \$old) {
        // Exclui arquivos
        @unlink(__DIR__ . '/uploads/icons/' . basename(\$old['icon_url']));
        @unlink(__DIR__ . '/uploads/apks/'  . basename(\$old['apk_url']));
        // Deleta do banco
        \$db->prepare("DELETE FROM apps WHERE id = ?")->execute([\$id]);
        header('Location: editar_app.php?id=' . \$id . '&deleted=1');
        exit;
    } else {
        \$error = 'App não encontrado.';
    }
}

// Busca o registro para exibir
\$stmt = \$db->prepare("SELECT * FROM apps WHERE id = ?");
\$stmt->execute([\$id]);
\$app = \$stmt->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Editar App #<?= \$id ?></title>
    <style>
      body { font-family: sans-serif; margin:2em; }
      label { display:block; margin:0.5em 0; }
      input[type=text] { width:100%; padding:0.3em; }
      img { max-height:48px; display:block; margin-top:0.3em; }
      .msg { background:#e0ffe0; padding:0.5em; margin-bottom:1em; border:1px solid #0c0; }
      .error { background:#ffe0e0; padding:0.5em; margin-bottom:1em; border:1px solid #c00; }
    </style>
</head>
<body>
  <h1>Editar App #<?= \$id ?></h1>

  <?php if (\$updated): ?>
    <div class="msg">App atualizado com sucesso!</div>
  <?php endif; ?>
  <?php if (\$deleted): ?>
    <div class="msg">App excluído com sucesso!</div>
  <?php endif; ?>
  <?php if (\$error): ?>
    <div class="error"><?= \$error ?></div>
  <?php endif; ?>

  <?php if (\$app): ?>
    <form method="post" enctype="multipart/form-data">
      <input type="hidden" name="action" value="update">
      <label>
        Nome:
        <input type="text" name="name" value="<?= htmlspecialchars(\$app['name'], ENT_QUOTES) ?>" required>
      </label>
      <label>
        Pacote:
        <input type="text" name="package" value="<?= htmlspecialchars(\$app['package'], ENT_QUOTES) ?>" required>
      </label>
      <label>
        Ícone atual:
        <img src="<?= htmlspecialchars(\$app['icon_url'], ENT_QUOTES) ?>" alt="Ícone">
      </label>
      <label>
        Trocar ícone:
        <input type="file" name="icon_file" accept="image/*">
      </label>
      <label>
        APK atual:
        <a href="<?= htmlspecialchars(\$app['apk_url'], ENT_QUOTES) ?>" target="_blank">Download</a>
      </label>
      <label>
        Trocar APK:
        <input type="file" name="apk_file" accept=".apk">
      </label>
      <button type="submit">Salvar alterações</button>
    </form>

    <form method="post" onsubmit="return confirm('Confirma exclusão deste app?');">
      <input type="hidden" name="action" value="delete">
      <button type="submit" style="margin-top:1em;">Excluir app</button>
    </form>

    <p><a href="painel.php">Voltar ao painel</a></p>

  <?php else: ?>
    <p>App não encontrado. <a href="painel.php">Voltar ao painel</a></p>
  <?php endif; ?>

</body>
</html>