<?php
require_once __DIR__ . '/../config/bootstrap.php';
admin_require_login();
$pdo = db();

$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $brand_name = trim((string)($_POST['brand_name'] ?? ''));
  $brand_url = trim((string)($_POST['brand_url'] ?? ''));
  if ($brand_name === '') $brand_name = 'FrameBuilder';

  if (isset($_FILES['brand_logo']) && ($_FILES['brand_logo']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
    $f = $_FILES['brand_logo'];
    if (($f['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
      $err = 'Falha no upload do logo.';
    } else {
      $mime = mime_content_type($f['tmp_name']) ?: '';
      $allowed = ['image/png'=>'png','image/jpeg'=>'jpg','image/webp'=>'webp'];
      if (!isset($allowed[$mime])) {
        $err = 'Logo deve ser PNG/JPG/WEBP.';
      } else {
        ensure_dir(__DIR__ . '/../storage/brand');
        $ext = $allowed[$mime];
        $fname = 'logo-' . date('YmdHis') . '-' . uuid16() . '.' . $ext;
        $rel = '/storage/brand/' . $fname;
        $dest = __DIR__ . '/..' . $rel;
        if (!move_uploaded_file($f['tmp_name'], $dest)) {
          $err = 'Não foi possível salvar o logo.';
        } else {
          app_config_set($pdo, 'brand_logo', $rel);
        }
      }
    }
  }

  if ($err === '') {
    app_config_set($pdo, 'brand_name', $brand_name);
    app_config_set($pdo, 'brand_url', $brand_url);
    $msg = 'Configurações salvas.';
  }
}

$brandName = app_config_get($pdo, 'brand_name', 'FrameBuilder');
$brandUrl  = app_config_get($pdo, 'brand_url', '');
$brandLogo = app_config_get($pdo, 'brand_logo', '');

$title = 'Admin - Marca';
require __DIR__ . '/_partials/header.php';

$base = app_base_path();
$icoLock = $base . '/assets/img/icon-lock.svg';
?>

<div class="fb-card" style="max-width:820px;margin:0 auto;">
  <div class="fb-card-h">
    <h1 class="fb-h1">Marca</h1>
    <div class="fb-sub">Configurações de whitelabel do projeto</div>
  </div>
  <div class="fb-card-b">
    <?php if ($msg): ?>
      <div class="alert alert-success"><?= htmlspecialchars($msg); ?></div>
    <?php endif; ?>
    <?php if ($err): ?>
      <div class="alert alert-danger"><?= htmlspecialchars($err); ?></div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data">
      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label fw-semibold">Nome da marca</label>
          <input name="brand_name" class="form-control fb-input" value="<?= htmlspecialchars($brandName); ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label fw-semibold">URL (opcional)</label>
          <input name="brand_url" class="form-control fb-input" value="<?= htmlspecialchars($brandUrl); ?>" placeholder="https://...">
        </div>
        <div class="col-md-8">
          <label class="form-label fw-semibold">Logo (opcional)</label>
          <input type="file" name="brand_logo" class="form-control fb-input" accept="image/*">
          <div class="text-muted small mt-1">PNG/JPG/WEBP. Recomendado: logo horizontal.</div>
        </div>
        <div class="col-md-4">
          <label class="form-label fw-semibold">Preview</label>
          <div class="p-3 border rounded-4 bg-white" style="min-height:80px;display:flex;align-items:center;justify-content:center;">
            <?php if ($brandLogo): ?>
              <img src="<?= htmlspecialchars(build_url_path($brandLogo)); ?>" alt="Logo" style="max-height:60px;max-width:100%;object-fit:contain;">
            <?php else: ?>
              <div class="text-muted small">sem logo</div>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <div class="d-flex justify-content-end mt-4">
        <button class="btn btn-primary fb-btn" type="submit" style="min-width:240px;">
          <img src="<?= htmlspecialchars($icoLock); ?>" alt="" style="width:18px;height:18px;margin-right:8px;vertical-align:-3px;">
          Gerar e salvar
        </button>
      </div>
    </form>
  </div>
</div>

<?php require __DIR__ . '/_partials/footer.php'; ?>
