<?php
require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/../includes/data.php';
admin_require();

$action = $_GET['action'] ?? 'list';
$flash = null;
$flash_type = 'ok';
$items = load_forsale();

// ---------- POST acties ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!csrf_check($_POST['_csrf'] ?? '')) {
    $flash = 'Ongeldige sessie. Probeer opnieuw.'; $flash_type = 'error';
  } else {
    $op = $_POST['op'] ?? '';

    if ($op === 'save') {
      $id = trim($_POST['id'] ?? '');
      $isNew = ($id === '');
      if ($isNew) $id = 'b' . substr(bin2hex(random_bytes(4)), 0, 8);

      $entry = [
        'id'          => $id,
        'name'        => trim($_POST['name'] ?? ''),
        'type'        => trim($_POST['type'] ?? ''),
        'year'        => (int)($_POST['year'] ?? 0) ?: null,
        'length'      => trim($_POST['length'] ?? ''),
        'price'       => trim($_POST['price'] ?? ''),
        'description' => trim($_POST['description'] ?? ''),
        'broker'      => trim($_POST['broker'] ?? ''),
        'broker_url'  => trim($_POST['broker_url'] ?? ''),
        'images'      => [],
        'added'       => $isNew ? date('Y-m-d') : (find_forsale_item($items, $id)['added'] ?? date('Y-m-d')),
      ];

      // Behoud bestaande afbeeldingen die niet verwijderd zijn
      $keepImgs = $_POST['keep_images'] ?? [];
      if (is_array($keepImgs)) {
        $entry['images'] = array_values(array_filter(array_map('strval', $keepImgs)));
      }

      // Verwerk uploads
      if (!empty($_FILES['images']['name'][0])) {
        $uploadDir = __DIR__ . '/../uploads';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
        foreach ($_FILES['images']['name'] as $i => $origName) {
          if ($_FILES['images']['error'][$i] !== UPLOAD_ERR_OK) continue;
          $tmp  = $_FILES['images']['tmp_name'][$i];
          $size = $_FILES['images']['size'][$i];
          if ($size > 8 * 1024 * 1024) continue; // max 8MB
          $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
          if (!in_array($ext, ['jpg','jpeg','png','webp'], true)) continue;
          $newName = $id . '-' . time() . '-' . $i . '.' . $ext;
          if (move_uploaded_file($tmp, "$uploadDir/$newName")) {
            $entry['images'][] = $newName;
          }
        }
      }

      // Validatie
      if ($entry['name'] === '') {
        $flash = 'Naam is verplicht.'; $flash_type = 'error';
      } else {
        // Update of voeg toe
        $found = false;
        foreach ($items as $i => $it) {
          if (($it['id'] ?? '') === $id) { $items[$i] = $entry; $found = true; break; }
        }
        if (!$found) $items[] = $entry;

        if (save_forsale($items)) {
          $flash = $isNew ? 'Schip toegevoegd.' : 'Schip bijgewerkt.';
          // Reload + redirect naar list
          header('Location: te-koop.php?saved=1');
          exit;
        } else {
          $flash = 'Kon te-koop.json niet schrijven. Controleer rechten op /data/.'; $flash_type = 'error';
        }
      }
    }

    if ($op === 'delete') {
      $id = $_POST['id'] ?? '';
      $items = array_values(array_filter($items, fn($it) => ($it['id'] ?? '') !== $id));
      if (save_forsale($items)) {
        $flash = 'Schip verwijderd.';
      } else {
        $flash = 'Verwijderen mislukt.'; $flash_type = 'error';
      }
    }
  }
  // Vernieuw na POST
  $items = load_forsale();
}

if (isset($_GET['saved'])) { $flash = 'Wijzigingen opgeslagen.'; }

function find_forsale_item(array $items, string $id): ?array {
  foreach ($items as $it) if (($it['id'] ?? '') === $id) return $it;
  return null;
}

// ---------- Edit/Add view ----------
$editing = null;
if ($action === 'edit') {
  $editing = find_forsale_item($items, $_GET['id'] ?? '');
  if (!$editing) { header('Location: te-koop.php'); exit; }
}
if ($action === 'add') {
  $editing = ['id'=>'','name'=>'','type'=>'','year'=>'','length'=>'','price'=>'','description'=>'','broker'=>'','broker_url'=>'','images'=>[]];
}

$admin_title = 'Te koop beheren';
include __DIR__ . '/_layout.php';
?>

<?php if ($flash): ?>
  <div class="flash <?= $flash_type === 'error' ? 'error' : '' ?>"><?= e($flash) ?></div>
<?php endif; ?>

<?php if ($editing): ?>

  <h1><?= $editing['id'] === '' ? 'Nieuw schip toevoegen' : 'Schip bewerken' ?> <small><?= e($editing['name']) ?></small></h1>
  <p class="lede">Vul de gegevens in. Foto's zijn optioneel — meerdere kunnen tegelijk geüpload worden.</p>

  <form method="post" enctype="multipart/form-data" class="panel">
    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
    <input type="hidden" name="op" value="save">
    <input type="hidden" name="id" value="<?= e($editing['id']) ?>">

    <div class="row">
      <div class="field">
        <label>Naam *</label>
        <input name="name" required value="<?= e($editing['name']) ?>" placeholder="bv. Noordkaper 1300">
      </div>
      <div class="field">
        <label>Type</label>
        <input name="type" value="<?= e($editing['type']) ?>" placeholder="bv. Visserman, Kajuitzeiljacht">
      </div>
    </div>

    <div class="row">
      <div class="field">
        <label>Bouwjaar</label>
        <input name="year" type="number" min="1900" max="<?= date('Y') ?>" value="<?= e((string)$editing['year']) ?>">
      </div>
      <div class="field">
        <label>Lengte</label>
        <input name="length" value="<?= e($editing['length']) ?>" placeholder="bv. 13,00 m">
      </div>
    </div>

    <div class="field">
      <label>Vraagprijs</label>
      <input name="price" value="<?= e($editing['price']) ?>" placeholder="bv. € 245.000 of 'op aanvraag'">
    </div>

    <div class="field">
      <label>Beschrijving</label>
      <textarea name="description"><?= e($editing['description']) ?></textarea>
    </div>

    <div class="row">
      <div class="field">
        <label>Makelaar</label>
        <input name="broker" value="<?= e($editing['broker']) ?>" placeholder="bv. Doeve Makelaars">
      </div>
      <div class="field">
        <label>Link naar makelaar</label>
        <input name="broker_url" type="url" value="<?= e($editing['broker_url']) ?>" placeholder="https://...">
      </div>
    </div>

    <div class="field">
      <label>Bestaande foto's</label>
      <?php if (empty($editing['images'])): ?>
        <p style="color:rgba(236,226,203,.5);font-size:13px">Nog geen foto's geüpload.</p>
      <?php else: ?>
        <div class="img-list">
          <?php foreach ($editing['images'] as $img): ?>
            <label class="item" style="cursor:pointer" title="Aangevinkt = behouden">
              <input type="checkbox" name="keep_images[]" value="<?= e($img) ?>" checked style="position:absolute;top:4px;left:4px;width:auto;z-index:2">
              <img src="../uploads/<?= e(rawurlencode($img)) ?>" alt="">
            </label>
          <?php endforeach; ?>
        </div>
        <p style="font-size:12px;color:rgba(236,226,203,.5);margin-top:8px">Vinkje uitzetten om foto te verwijderen bij opslaan.</p>
      <?php endif; ?>
    </div>

    <div class="field">
      <label>Nieuwe foto's uploaden (jpg/png/webp, max 8MB per stuk)</label>
      <input type="file" name="images[]" multiple accept="image/jpeg,image/png,image/webp">
    </div>

    <div style="display:flex;gap:10px;margin-top:20px">
      <button type="submit" class="btn">Opslaan</button>
      <a href="te-koop.php" class="btn btn-ghost">Annuleren</a>
    </div>
  </form>

<?php else: ?>

  <h1>Te koop beheren <small><?= count($items) ?> <?= count($items) === 1 ? 'schip' : 'schepen' ?></small></h1>
  <p class="lede">Voeg schepen toe, bewerk bestaande of verwijder ze. Wijzigingen verschijnen direct op de publieke <a href="../te-koop.php" target="_blank">Te koop</a>-pagina.</p>

  <div style="margin-bottom:20px">
    <a href="te-koop.php?action=add" class="btn">+ Nieuw schip</a>
  </div>

  <div class="panel" style="padding:0;overflow:auto">
    <?php if (empty($items)): ?>
      <div class="empty-state">
        Nog geen schepen toegevoegd. Klik op "+ Nieuw schip" om te beginnen.
      </div>
    <?php else: ?>
      <table>
        <thead><tr><th>Naam</th><th>Type / Jaar</th><th>Vraagprijs</th><th>Toegevoegd</th><th></th></tr></thead>
        <tbody>
          <?php foreach ($items as $it): ?>
            <tr>
              <td>
                <div class="name"><?= e($it['name']) ?></div>
                <div class="meta"><?= e($it['broker'] ?? '') ?></div>
              </td>
              <td>
                <?= e($it['type'] ?? '') ?>
                <?php if (!empty($it['year'])): ?> · <?= e((string)$it['year']) ?><?php endif; ?>
                <?php if (!empty($it['length'])): ?><div class="meta"><?= e($it['length']) ?></div><?php endif; ?>
              </td>
              <td><?= e($it['price'] ?? '') ?></td>
              <td><?= e($it['added'] ?? '') ?></td>
              <td class="actions">
                <a href="te-koop.php?action=edit&id=<?= e($it['id']) ?>" class="btn btn-ghost" style="padding:6px 14px;font-size:10px">Bewerken</a>
                <form method="post" style="display:inline" onsubmit="return confirm('Zeker weten dat je &quot;<?= e($it['name']) ?>&quot; wilt verwijderen?')">
                  <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
                  <input type="hidden" name="op" value="delete">
                  <input type="hidden" name="id" value="<?= e($it['id']) ?>">
                  <button type="submit" class="btn btn-danger" style="padding:6px 14px;font-size:10px">Verwijderen</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>

<?php endif; ?>

</main></body></html>
