<?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) {
    $filePath = str_replace(getBaseUrl() . getBaseDir(), '', $filePath);
    $realPath = $_SERVER['DOCUMENT_ROOT'] . '/' . ltrim($filePath, '/');
    if (file_exists($realPath)) {
        unlink($realPath);
        error_log("Deleted file: " . $realPath);
    } else {
        error_log("File not found: " . $realPath);
    }
}

function processImageUpload($fileInput, $folder, &$config, $configField) {
    if (isset($_FILES[$fileInput]) && $_FILES[$fileInput]["error"] == UPLOAD_ERR_OK) {
        if (!empty($config[$configField])) {
            deleteOldFile($config[$configField]);
        }
        
        $targetDir = __DIR__ . "/public/" . $folder . "/";
        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0755, true);
        }
        $fileExtension = 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, '/');
                return $baseUrl . $baseDir . '/public/' . $folder . '/' . $newFileName;
            }
        }
    }
    return null;
}

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

    $db->exec("CREATE TABLE IF NOT EXISTS config (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        title VARCHAR(100),
        description TEXT,
        plataform TEXT,
        url_image TEXT
    )");

    $stmt = $db->query("SELECT * FROM config LIMIT 1");
    $config = $stmt->fetch(PDO::FETCH_ASSOC);

    if (isset($_POST['submit'])) {
        $title = $_POST['title'] ?? '';
        $description = $_POST['description'] ?? '';
        $plataform = $_POST['plataform'] ?? '';
        $url_image = processImageUpload('background', 'background', $config, 'url_image') ?? $config['url_image'];

        if ($config) {
            
            $stmt = $db->prepare("UPDATE config SET title = :title, description = :description, plataform = :plataform, url_image = :url_image WHERE id = :id");
            $stmt->bindParam(':id', $config['id']);
        } else {
           
            $stmt = $db->prepare("INSERT INTO config (title, description, plataform, url_image) VALUES (:title, :description, :plataform, :url_image)");
        }

        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':plataform', $plataform);
        $stmt->bindParam(':url_image', $url_image);
        $stmt->execute();

        echo '<div class="alert alert-success" id="flash-msg"><h4>Altercação foi um sucesso!</h4></div>';
    }

} 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="col-12">
          <strong><h3></h3></strong>
        </div>
      </div>
      <form action="config_app.php" method="post" enctype="multipart/form-data">
        <div class="form-group">
          <label class="control-label" for="title"><strong>Titulo</strong></label>
          <input class="form-control text-primary" id="title" name="title" type="text" value="<?= htmlspecialchars($config['title'] ?? '') ?>" required />
        </div>
        <div class="form-group">
          <label class="control-label" for="plataform"><strong>Primeiro Texto</strong></label>
          <input class="form-control text-primary" id="plataform" name="plataform" type="text" value="<?= htmlspecialchars($config['plataform'] ?? '') ?>" required />
        </div>
        <div class="form-group">
          <label class="control-label" for="description"><strong>Segundo Texto</strong></label>
          <input class="form-control text-primary" id="description" name="description" type="text" value="<?= htmlspecialchars($config['description'] ?? '') ?>" required />
        </div>
        <div class="form-group">
          <label class="control-label" for="BLACKF1"><strong>PLANO DE FUNDO</strong></label>
          <?php if (!empty($config['url_image'])) : ?>
            <div class="mt-3">
              <label class="control-label"><strong>Imagem Atual:</strong></label>
              <div>
                <img src="<?= htmlspecialchars($config['url_image']) ?>" alt="Imagem Atual" style="max-width: 100px; height: auto;" />
              </div>
            </div>
          <?php endif; ?>
          <div class="input-group">
            <input class="form-control text-primary" id="BLACKF1" name="background" type="file" accept="image/*" />
          </div>
        </div>
        <div>
          <button class="btn btn-success" name="submit" type="submit">
            <i class="fa fa-check"></i> <strong>Salvar</strong>
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php include ('includes/footer.php'); ?>
<script src="js/sb-admin.min.js"></script>
</body>
<script>
$(function() {
  $inp = $("#btn_signup");
  $cb = $("#checkbox");
  if ($cb.is(':checked')) {
      $inp.prop('disabled', false);
  } else {
      $inp.prop('disabled', true);
  }

  $cb.on('change', function() {
    if ($cb.is(':checked')) {
      $inp.prop('disabled', false);
    } else {
      $inp.prop('disabled', true);
    }
  });
});

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