<?php
session_start();
require __DIR__ . '/auth.php';
require __DIR__ . '/includes/admin_lib.php';

$dataFile = __DIR__ . '/../about-data.json';
$entries = smurf_read_json($dataFile, []);
if (!is_array($entries)) $entries = [];

$action = $_GET['action'] ?? '';
$i = isset($_GET['i']) ? (int)$_GET['i'] : -1;
$edit = ($action === 'edit' && $i >= 0 && isset($entries[$i]))
  ? $entries[$i]
  : ['title'=>'','description'=>'','image'=>''];

if ($action === 'delete' && $i >= 0) {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to edit About.');
  if (isset($entries[$i])) {
    array_splice($entries, $i, 1);
    smurf_write_json($dataFile, array_values($entries));
  }
  smurf_redirect_self([], ['action','i']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to edit About.');
  $mode = $_POST['mode'] ?? 'create';
  $editIndex = (int)($_POST['edit_index'] ?? -1);
  $title = trim($_POST['title'] ?? '');
  $description = trim($_POST['description'] ?? '');
  $image = trim($_POST['image'] ?? '');
  if ($image === '') {
    $uploaded = smurf_handle_upload('image_file', __DIR__ . '/../uploads');
    if ($uploaded !== '') $image = $uploaded;
  }
  if ($title !== '' || $description !== '') {
    $row = [
      'title' => $title,
      'description' => $description,
      'image' => $image,
      'id' => ($mode === 'update' && !empty($entries[$editIndex]['id'])) ? $entries[$editIndex]['id'] : bin2hex(random_bytes(8)),
    ];
    if ($mode === 'update' && isset($entries[$editIndex])) $entries[$editIndex] = $row;
    else $entries[] = $row;
    smurf_write_json($dataFile, array_values($entries));
    smurf_redirect_self(['saved'=>1], ['action','i']);
  }
}

include __DIR__ . '/includes/admin_header.php';
?>
<section class="admin-page-shell">
  <h1 class="admin-title">ℹ️ About Page</h1>
  <p style="opacity:.8;">Front-end reads: <code>/about-data.json</code> • This now matches the public About page cards.</p>
  <?php if (!empty($_GET['saved'])): ?><div class="msg success">Saved.</div><?php endif; ?>

  <div class="admin-wrap stack" style="margin-top:10px;">
    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;"><?= ($action === 'edit') ? 'Edit About Card' : 'Add About Card' ?></h3>
      <form method="POST" enctype="multipart/form-data" class="admin-form-stack">
        <input type="hidden" name="mode" value="<?= ($action === 'edit') ? 'update' : 'create' ?>">
        <input type="hidden" name="edit_index" value="<?= (int)$i ?>">

        <div><label>Title</label><input class="input-field" name="title" required value="<?= smurf_h($edit['title'] ?? '') ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>></div>

        <div>
          <label>Description</label>
          <textarea class="input-field" name="description" rows="12" <?= $CAN_EDIT ? '' : 'disabled' ?>><?= smurf_h($edit['description'] ?? '') ?></textarea>
        </div>

        <div class="admin-form-grid-2">
          <div><label>Image Link (optional)</label><input class="input-field" name="image" placeholder="https://example.com/photo.png" value="<?= smurf_h($edit['image'] ?? '') ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>></div>
          <div>
            <label>Or Upload Image File</label>
            <div class="upload-box"><input type="file" class="admin-file-input" name="image_file" accept="image/*" <?= $CAN_EDIT ? '' : 'disabled' ?>><small class="upload-help">Use the image link above OR choose a file here. If both are filled, the image link is used. Uploaded files save into <code>/uploads/</code></small></div>
          </div>
        </div>

        <?php if ($CAN_EDIT): ?>
          <div class="admin-card-actions">
            <button class="admin-btn primary" type="submit"><?= ($action === 'edit') ? 'Save About Card' : 'Add About Card' ?></button>
            <?php if ($action === 'edit'): ?><a class="admin-btn" href="/admin/about.php">Cancel</a><?php endif; ?>
          </div>
        <?php else: ?>
          <p style="opacity:.7;margin-top:10px;">View-only mode — editing disabled.</p>
        <?php endif; ?>
      </form>
    </section>

    <section class="content-card admin-list-panel" style="text-align:left;">
      <h3 style="margin-top:0;">Current About Cards</h3>
      <?php if (empty($entries)): ?>
        <p>No About cards yet.</p>
      <?php else: ?>
        <div class="admin-entry-grid">
        <?php foreach ($entries as $idx => $entry): $img = smurf_public_asset_url((string)($entry['image'] ?? ''), 'uploads'); ?>
          <div class="admin-media-card">
            <?php if ($img): ?><img class="admin-media-thumb contain" src="<?= smurf_h($img) ?>" alt="<?= smurf_h($entry['title'] ?? '') ?>"><?php else: ?><div class="admin-media-placeholder">No image yet</div><?php endif; ?>
            <div class="admin-media-meta"><h3><?= smurf_h($entry['title'] ?? '') ?></h3></div>
            <div class="admin-media-body"><?= !empty($entry['description']) ? nl2br(smurf_h($entry['description'])) : 'No description yet.' ?></div>
            <div class="admin-card-actions">
              <a class="admin-btn" href="/admin/about.php?action=edit&i=<?= $idx ?>">Edit</a>
              <?php if ($CAN_EDIT): ?><a class="admin-btn" href="/admin/about.php?action=delete&i=<?= $idx ?>" onclick="return confirm('Delete this About card?');">Delete</a><?php endif; ?>
            </div>
          </div>
        <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </section>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
