<?php
session_start();

// configurações de erro (mantenha display_errors = 0 em produção)
ini_set("display_errors", 0);
ini_set("display_startup_errors", 0);
error_reporting(E_ALL);

// caminho do arquivo JSON
$jsonPath = __DIR__ . '/api/update.json';

// lê o JSON com checagem
$avc = '';
$apkurl = '';
if (file_exists($jsonPath)) {
    $jsondata = file_get_contents($jsonPath);
    $data = json_decode($jsondata, true);
    if (is_array($data) && isset($data['app_info'])) {
        $avc = $data['app_info']['android_version_code'] ?? '';
        $apkurl = $data['app_info']['apk_url'] ?? '';
    }
}

// processa envio do form
if (isset($_POST['submit'])) {
    // sanitização simples
    $new_version_code = isset($_POST['android_version_code']) ? trim($_POST['android_version_code']) : '';
    $new_apk_url = isset($_POST['apk_url']) ? trim($_POST['apk_url']) : '';

    // garante que temos um array base
    $arrayData = [];
    if (file_exists($jsonPath)) {
        $jsonData = file_get_contents($jsonPath);
        $arrayData = json_decode($jsonData, true);
        if (!is_array($arrayData)) $arrayData = [];
    }

    // monta estrutura se necessário
    if (!isset($arrayData['app_info']) || !is_array($arrayData['app_info'])) {
        $arrayData['app_info'] = [];
    }

    // atualiza valores
    $arrayData['app_info']['android_version_code'] = $new_version_code;
    $arrayData['app_info']['apk_url'] = $new_apk_url;

    // salva no arquivo
    $newJsonData = json_encode($arrayData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    if (file_put_contents($jsonPath, $newJsonData) === false) {
        $_SESSION['flash_error'] = 'Erro ao salvar update.json. Verifique permissões do arquivo.';
    } else {
        $_SESSION['flash_success'] = 'Apk Details Updated!';
    }

    // redireciona para evitar reenvio do form
    header('Location: update.php');
    exit;
}

// include do header (apenas 1 vez)
include 'includes/header.php';
?>

<div class="container-fluid">
  <!-- Page Heading -->
  <h1 class="h3 mb-1 text-gray-800">Apk Update</h1>

  <!-- Content Row -->
  <div class="row">
    <div class="col-lg-12">
      <div class="card border-left-primary shadow h-100 mb-4">
        <div class="card-header py-3">
          <h6 class="m-0 font-weight-bold text-primary"><i class="fa fa-refresh"></i> Apk Update</h6>
        </div>
        <div class="card-body">
          <?php
            // mostra mensagens flash (se houver)
            if (isset($_SESSION['flash_success'])) {
                echo '<div class="alert alert-primary" id="flash-msg"><h4><i class="icon fa fa-check"></i> ' . htmlspecialchars($_SESSION['flash_success']) . '</h4></div>';
                unset($_SESSION['flash_success']);
            }
            if (isset($_SESSION['flash_error'])) {
                echo '<div class="alert alert-danger" id="flash-msg"><h4><i class="icon fa fa-exclamation-triangle"></i> ' . htmlspecialchars($_SESSION['flash_error']) . '</h4></div>';
                unset($_SESSION['flash_error']);
            }
          ?>

          <form method="post">
            <div class="form-group">
              <h6 class="form-text"><strong>Version Code</strong></h6>
              <input type="text" class="form-control" placeholder="Version Code" name="android_version_code" value="<?php echo htmlspecialchars($avc); ?>">
            </div>

            <div class="form-group">
              <h6 class="form-text"><strong>Download Url</strong></h6>
              <input type="text" class="form-control" placeholder="http://link to app.apk" name="apk_url" value="<?php echo htmlspecialchars($apkurl); ?>">
            </div>

            <button class="btn btn-primary btn-icon-split" name="submit" type="submit">
              <span class="icon text-white-50"><i class="fas fa-check"></i></span>
              <span class="text">Submit</span>
            </button>
          </form>

        </div>
      </div>

    </div>
  </div>

  <br><br><br>
</div>

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

<script>
$(document).ready(function () {
    $("#flash-msg").delay(3000).fadeOut("slow");
});
</script>

</body>
</html>
