<?php
$title='Ajustes';
require_once __DIR__ . '/../inc/header.php';
require_once __DIR__ . '/../inc/docs.php';
ensure_part2_tables();
if(!is_admin()){ http_response_code(403); exit('Solo admin'); }

$co = get_company();

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();

  // Upload logo - admitir varios formatos (se guardará tal cual)
  if(isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK){
    $file = $_FILES['logo'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg','jpeg','png','gif','webp'];
    if(!in_array($ext, $allowed, true)){
      flash_set('danger','Formato de logotipo no permitido. Usa JPG/PNG/GIF/WEBP.');
      redirect('settings/index.php');
    }
    if($file['size'] > 3*1024*1024){
      flash_set('danger','Logotipo máximo 3MB.');
      redirect('settings/index.php');
    }
    $dir = __DIR__ . '/../uploads/logo';
    if(!is_dir($dir)) @mkdir($dir, 0775, true);
    $name = 'logo_'.time().'.'.$ext;
    $dest = $dir . '/' . $name;
    if(!move_uploaded_file($file['tmp_name'], $dest)){
      flash_set('danger','No se pudo guardar el logotipo.');
      redirect('settings/index.php');
    }
    $_POST['logo_path'] = '/uploads/logo/' . $name;
  } else {
    $_POST['logo_path'] = $co['logo_path'] ?? null;
  }

  update_company($_POST);
  flash_set('success','Ajustes guardados.');
  redirect('settings/index.php');
}

$co = get_company();
?>
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <div>
    <h4 class="mb-0">Ajustes</h4>
    <div class="text-muted">Datos de empresa (para PDFs), logotipo y series.</div>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a class="btn btn-outline-primary" href="<?= url('settings/series.php') ?>">Series</a>
  </div>
</div>

<div class="card shadow-sm">
  <div class="card-body">
    <form method="post" enctype="multipart/form-data" class="row g-3">
      <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
      <div class="col-md-6">
        <label class="form-label">Nombre empresa</label>
        <input class="form-control" name="company_name" value="<?= h($co['company_name'] ?? '') ?>" required>
      </div>
      <div class="col-md-6">
        <label class="form-label">NIF/CIF</label>
        <input class="form-control" name="nif_cif" value="<?= h($co['nif_cif'] ?? '') ?>">
      </div>
      <div class="col-12">
        <label class="form-label">Dirección</label>
        <input class="form-control" name="address" value="<?= h($co['address'] ?? '') ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">Teléfono</label>
        <input class="form-control" name="phone" value="<?= h($co['phone'] ?? '') ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">Email</label>
        <input class="form-control" name="email" value="<?= h($co['email'] ?? '') ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">IBAN</label>
        <input class="form-control" name="iban" value="<?= h($co['iban'] ?? '') ?>">
      </div>
      <div class="col-12">
        <label class="form-label">Nota pie (PDF)</label>
        <input class="form-control" name="footer_note" value="<?= h($co['footer_note'] ?? '') ?>">
      </div>

      <div class="col-md-6">
        <label class="form-label">Logotipo (JPG/PNG/GIF/WEBP)</label>
        <input class="form-control" type="file" name="logo" accept=".jpg,.jpeg,.png,.gif,.webp">
        <div class="form-text">Para PDF se adaptará automáticamente (si el servidor soporta convertir).</div>
      </div>
      <div class="col-md-6">
        <label class="form-label">Logotipo actual</label><br>
        <?php if(!empty($co['logo_path'])): ?>
          <img src="<?= h($co['logo_path']) ?>" style="max-height:80px; border:1px solid #e5e7eb; border-radius:10px; background:#fff; padding:6px;">
        <?php else: ?>
          <div class="text-muted">Sin logotipo</div>
        <?php endif; ?>
      </div>

      <div class="col-12">
        <button class="btn btn-primary">Guardar</button>
      </div>
    </form>
  </div>
</div>

<?php require_once __DIR__ . '/../inc/footer.php'; ?>
