<?php
require_once __DIR__ . '/header.php';

$db = getDB();
$message = '';
$error = '';
$tableMissing = false;

function safeImageUpload(string $fileKey, string $subDir): ?string {
  if (empty($_FILES[$fileKey]['tmp_name'])) return null;
  if (($_FILES[$fileKey]['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) return null;
  if (($_FILES[$fileKey]['size'] ?? 0) > 2 * 1024 * 1024) return null;

  $info = @getimagesize($_FILES[$fileKey]['tmp_name']);
  if ($info === false) return null;

  $allowed = [
    'image/jpeg' => 'jpg',
    'image/png'  => 'png',
    'image/webp' => 'webp',
    'image/gif'  => 'gif'
  ];
  $mime = $info['mime'] ?? '';
  if (!isset($allowed[$mime])) return null;

  $uploadDir = IMAGE_PATH . '/' . trim($subDir, '/') . '/';
  if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

  $filename = uniqid('img_', true) . '.' . $allowed[$mime];
  $targetFile = $uploadDir . $filename;

  if (!move_uploaded_file($_FILES[$fileKey]['tmp_name'], $targetFile)) return null;

  return IMAGE_URL . '/' . trim($subDir, '/') . '/' . $filename;
}

function hasTable(PDO $db, string $table): bool {
  try {
    $stmt = $db->prepare("SHOW TABLES LIKE ?");
    $stmt->execute([$table]);
    return (bool)$stmt->fetchColumn();
  } catch (Throwable $e) {
    return false;
  }
}

$hasCostsTable = hasTable($db, 'habit_item_costs');

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  $type = $_POST['type'] ?? '';
  $id   = (int)($_POST['id'] ?? 0);

  try {
    if ($type === 'habit' && $id > 0) {
      $name = trim($_POST['name'] ?? '');
      if ($name === '') throw new Exception("Habit name cannot be empty.");

      $desc = trim($_POST['description'] ?? '');
      $time = $_POST['time_of_day'] ?? 'morning';
      $freq = $_POST['frequency'] ?? 'daily';
      $xp   = (int)($_POST['xp_reward'] ?? 25);
      $cal  = isset($_POST['show_on_calendar']) ? 1 : 0;

      $newImage = safeImageUpload('image', 'habits');

      $db->beginTransaction();

      if ($newImage) {
        $stmt = $db->prepare("UPDATE habits SET name=?, description=?, time_of_day=?, frequency=?, xp_reward=?, show_on_calendar=?, image_path=? WHERE id=?");
        $stmt->execute([$name, $desc, $time, $freq, $xp, $cal, $newImage, $id]);
      } else {
        $stmt = $db->prepare("UPDATE habits SET name=?, description=?, time_of_day=?, frequency=?, xp_reward=?, show_on_calendar=? WHERE id=?");
        $stmt->execute([$name, $desc, $time, $freq, $xp, $cal, $id]);
      }

      // Update costs only if table exists
      if ($hasCostsTable) {
        $stmt = $db->prepare("DELETE FROM habit_item_costs WHERE habit_id=?");
        $stmt->execute([$id]);

        $linkItemIds = $_POST['link_item_id'] ?? [];
        $linkQtys    = $_POST['link_item_qty'] ?? [];

        if (is_array($linkItemIds) && count($linkItemIds) > 0) {
          $ins = $db->prepare("INSERT INTO habit_item_costs (habit_id, item_id, qty) VALUES (?, ?, ?)");
          foreach ($linkItemIds as $itemIdRaw) {
            $itemId = (int)$itemIdRaw;
            if ($itemId <= 0) continue;
            $qty = (int)($linkQtys[$itemIdRaw] ?? 1);
            if ($qty <= 0) $qty = 1;
            $ins->execute([$id, $itemId, $qty]);
          }
        }
      }

      $db->commit();
      $message = "Habit updated!";
    }

    if ($type === 'item' && $id > 0) {
      $name = trim($_POST['name'] ?? '');
      if ($name === '') throw new Exception("Item name cannot be empty.");

      $subtitle = trim($_POST['subtitle'] ?? '');
      $desc = trim($_POST['description'] ?? '');
      $rarity = $_POST['rarity'] ?? 'common';
      $stat = trim($_POST['stat_effect'] ?? '');
      $qty = (int)($_POST['quantity'] ?? 0);

      $newImage = safeImageUpload('image', 'items');

      if ($newImage) {
        $stmt = $db->prepare("UPDATE items SET name=?, subtitle=?, description=?, rarity=?, stat_effect=?, quantity=?, image_path=? WHERE id=?");
        $stmt->execute([$name, $subtitle, $desc, $rarity, $stat, $qty, $newImage, $id]);
      } else {
        $stmt = $db->prepare("UPDATE items SET name=?, subtitle=?, description=?, rarity=?, stat_effect=?, quantity=? WHERE id=?");
        $stmt->execute([$name, $subtitle, $desc, $rarity, $stat, $qty, $id]);
      }

      $message = "Item updated!";
    }

    if ($type === 'bounty' && $id > 0) {
      $name = trim($_POST['name'] ?? '');
      if ($name === '') throw new Exception("Bounty name cannot be empty.");

      $desc = trim($_POST['description'] ?? '');
      $xp = (int)($_POST['xp_reward'] ?? 100);
      $completed = isset($_POST['completed']) ? 1 : 0;

      $newImage = safeImageUpload('image', 'bounties');

      if ($newImage) {
        $stmt = $db->prepare("UPDATE bounties SET name=?, description=?, xp_reward=?, completed=?, image_path=? WHERE id=?");
        $stmt->execute([$name, $desc, $xp, $completed, $newImage, $id]);
      } else {
        $stmt = $db->prepare("UPDATE bounties SET name=?, description=?, xp_reward=?, completed=? WHERE id=?");
        $stmt->execute([$name, $desc, $xp, $completed, $id]);
      }

      if ($completed) {
        $stmt = $db->prepare("UPDATE bounties SET completed_date = COALESCE(completed_date, CURDATE()) WHERE id=?");
        $stmt->execute([$id]);
      } else {
        $stmt = $db->prepare("UPDATE bounties SET completed_date = NULL WHERE id=?");
        $stmt->execute([$id]);
      }

      $message = "Bounty updated!";
    }

  } catch (Throwable $e) {
    if ($db->inTransaction()) $db->rollBack();
    $error = $e->getMessage();
  }
}

// Load data safely
$habits = [];
$items = [];
$bounties = [];
$costMap = [];

try {
  $habits = $db->query("SELECT * FROM habits ORDER BY created_at DESC")->fetchAll();
  $items  = $db->query("SELECT * FROM items ORDER BY name ASC")->fetchAll();
  $bounties = $db->query("SELECT * FROM bounties ORDER BY created_at DESC")->fetchAll();

  if ($hasCostsTable) {
    $stmt = $db->query("SELECT habit_id, item_id, qty FROM habit_item_costs");
    foreach ($stmt->fetchAll() as $row) {
      $costMap[(int)$row['habit_id']][(int)$row['item_id']] = (int)$row['qty'];
    }
  }
} catch (Throwable $e) {
  $error = $error ?: "Database error: " . $e->getMessage();
}

?>

<?php if ($message): ?>
  <div style="background: rgba(76,175,80,0.15); border: 2px solid #4caf50; padding: 15px; margin-bottom: 20px; border-radius: 8px; text-align: center; color: #4caf50;">
    <?php echo htmlspecialchars($message); ?>
  </div>
<?php endif; ?>

<?php if ($error): ?>
  <div style="background: rgba(244,67,54,0.15); border: 2px solid #f44336; padding: 15px; margin-bottom: 20px; border-radius: 8px; text-align: center; color: #f44336;">
    <?php echo htmlspecialchars($error); ?>
  </div>
<?php endif; ?>

<?php if (!$hasCostsTable): ?>
  <div style="background: rgba(255,215,0,0.12); border: 2px solid var(--gold); padding: 15px; margin-bottom: 20px; border-radius: 8px; color: var(--gold);">
    <strong>Heads up:</strong> Table <code>habit_item_costs</code> is missing.  
    The editor will still work, but item consumption links won’t show/save until you run the SQL migration.
  </div>
<?php endif; ?>

<div class="hero-section">
  <h1 class="champion-name">🛠️ Edit Console</h1>
  <div class="champion-tagline">Edit Habits, Items, and Bounties — plus link habits to inventory costs.</div>
</div>

<div class="quest-grid">

  <!-- HABITS -->
  <div class="quest-category">
    <div class="category-header">
      <div class="category-icon">⚔️</div>
      <div class="category-title">Habits (Quests)</div>
    </div>

    <div class="quest-list">
      <?php foreach ($habits as $h): ?>
        <?php $hid = (int)$h['id']; ?>
        <div class="quest-item" style="cursor:default;">
          <div style="width:100%;">
            <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;">
              <div style="font-weight:900;color:#fff;"><?php echo htmlspecialchars($h['name']); ?></div>
              <div style="color:#888;font-size:0.85rem;">#<?php echo $hid; ?></div>
            </div>

            <form method="POST" enctype="multipart/form-data" style="margin-top:12px;">
              <input type="hidden" name="type" value="habit">
              <input type="hidden" name="id" value="<?php echo $hid; ?>">

              <div class="form-group">
                <label class="form-label">Name</label>
                <input class="form-input" name="name" value="<?php echo htmlspecialchars($h['name']); ?>">
              </div>

              <div class="form-group">
                <label class="form-label">Description</label>
                <textarea class="form-textarea" name="description" rows="2"><?php echo htmlspecialchars($h['description'] ?? ''); ?></textarea>
              </div>

              <div class="grid-2">
                <div class="form-group">
                  <label class="form-label">Time of Day</label>
                  <select class="form-select" name="time_of_day">
                    <option value="morning" <?php echo (($h['time_of_day'] ?? '')==='morning')?'selected':''; ?>>Morning</option>
                    <option value="midday" <?php echo (($h['time_of_day'] ?? '')==='midday')?'selected':''; ?>>Midday</option>
                    <option value="evening" <?php echo (($h['time_of_day'] ?? '')==='evening')?'selected':''; ?>>Evening</option>
                  </select>
                </div>

                <div class="form-group">
                  <label class="form-label">Frequency</label>
                  <select class="form-select" name="frequency">
                    <option value="daily" <?php echo (($h['frequency'] ?? '')==='daily')?'selected':''; ?>>Daily</option>
                    <option value="weekly" <?php echo (($h['frequency'] ?? '')==='weekly')?'selected':''; ?>>Weekly</option>
                    <option value="monthly" <?php echo (($h['frequency'] ?? '')==='monthly')?'selected':''; ?>>Monthly</option>
                    <option value="once" <?php echo (($h['frequency'] ?? '')==='once')?'selected':''; ?>>Once</option>
                  </select>
                </div>
              </div>

              <div class="grid-2">
                <div class="form-group">
                  <label class="form-label">XP Reward</label>
                  <input type="number" class="form-input" name="xp_reward" value="<?php echo (int)($h['xp_reward'] ?? 25); ?>" min="0" max="5000">
                </div>

                <div class="form-group">
                  <label class="form-label">Calendar</label>
                  <label style="display:flex;align-items:center;gap:10px;color:#ddd;">
                    <input type="checkbox" name="show_on_calendar" <?php echo !empty($h['show_on_calendar'])?'checked':''; ?>>
                    Show on Calendar
                  </label>
                </div>
              </div>

              <div class="form-group">
                <label class="form-label">Replace Image (optional)</label>
                <input type="file" class="form-input" name="image" accept="image/*">
                <?php if (!empty($h['image_path'])): ?>
                  <div style="margin-top:8px;color:#888;font-size:0.85rem;">
                    Current: <a href="<?php echo htmlspecialchars($h['image_path']); ?>" target="_blank" style="color:var(--gold);">view</a>
                  </div>
                <?php endif; ?>
              </div>

              <?php if ($hasCostsTable): ?>
                <div class="form-group">
                  <label class="form-label">Consumes Inventory Items (optional)</label>
                  <div style="background:rgba(255,255,255,0.04);border:1px solid #333;border-radius:8px;padding:12px;max-height:220px;overflow:auto;">
                    <?php if (count($items) === 0): ?>
                      <div style="color:#888;">No items to link yet.</div>
                    <?php else: ?>
                      <?php foreach ($items as $it): ?>
                        <?php
                          $iid = (int)$it['id'];
                          $checked = isset($costMap[$hid][$iid]);
                          $qtyVal = $checked ? (int)$costMap[$hid][$iid] : 1;
                        ?>
                        <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;padding:8px;border-bottom:1px solid rgba(255,255,255,0.06);">
                          <label style="display:flex;align-items:center;gap:10px;cursor:pointer;">
                            <input type="checkbox" name="link_item_id[]" value="<?php echo $iid; ?>" <?php echo $checked?'checked':''; ?>>
                            <span style="font-weight:700;"><?php echo htmlspecialchars($it['name']); ?></span>
                            <span style="color:#888;font-size:0.85rem;">(Have: <?php echo (int)$it['quantity']; ?>)</span>
                          </label>

                          <div style="display:flex;align-items:center;gap:6px;">
                            <span style="color:#888;font-size:0.85rem;">Qty</span>
                            <input
                              type="number"
                              class="form-input"
                              style="width:90px;padding:6px 10px;"
                              name="link_item_qty[<?php echo $iid; ?>]"
                              value="<?php echo $qtyVal; ?>"
                              min="1"
                            >
                          </div>
                        </div>
                      <?php endforeach; ?>
                    <?php endif; ?>
                  </div>
                </div>
              <?php endif; ?>

              <button type="submit" class="btn-submit">Save Habit</button>
            </form>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- ITEMS -->
  <div class="quest-category">
    <div class="category-header">
      <div class="category-icon">🎒</div>
      <div class="category-title">Items (Inventory)</div>
    </div>

    <div class="quest-list">
      <?php foreach ($items as $it): ?>
        <?php $iid = (int)$it['id']; ?>
        <div class="quest-item" style="cursor:default;">
          <div style="width:100%;">
            <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;">
              <div style="font-weight:900;color:#fff;"><?php echo htmlspecialchars($it['name']); ?></div>
              <div style="color:#888;font-size:0.85rem;">Have: <?php echo (int)$it['quantity']; ?></div>
            </div>

            <form method="POST" enctype="multipart/form-data" style="margin-top:12px;">
              <input type="hidden" name="type" value="item">
              <input type="hidden" name="id" value="<?php echo $iid; ?>">

              <div class="form-group">
                <label class="form-label">Name</label>
                <input class="form-input" name="name" value="<?php echo htmlspecialchars($it['name']); ?>">
              </div>

              <div class="form-group">
                <label class="form-label">Subtitle</label>
                <input class="form-input" name="subtitle" value="<?php echo htmlspecialchars($it['subtitle'] ?? ''); ?>">
              </div>

              <div class="form-group">
                <label class="form-label">Description</label>
                <textarea class="form-textarea" name="description" rows="2"><?php echo htmlspecialchars($it['description'] ?? ''); ?></textarea>
              </div>

              <div class="grid-2">
                <div class="form-group">
                  <label class="form-label">Rarity</label>
                  <select class="form-select" name="rarity">
                    <?php foreach (['common','uncommon','rare','epic','legendary'] as $r): ?>
                      <option value="<?php echo $r; ?>" <?php echo (($it['rarity'] ?? '')===$r)?'selected':''; ?>>
                        <?php echo ucfirst($r); ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </div>

                <div class="form-group">
                  <label class="form-label">Quantity</label>
                  <input type="number" class="form-input" name="quantity" value="<?php echo (int)($it['quantity'] ?? 0); ?>" min="0">
                </div>
              </div>

              <div class="form-group">
                <label class="form-label">Stat/Effect</label>
                <input class="form-input" name="stat_effect" value="<?php echo htmlspecialchars($it['stat_effect'] ?? ''); ?>">
              </div>

              <div class="form-group">
                <label class="form-label">Replace Image (optional)</label>
                <input type="file" class="form-input" name="image" accept="image/*">
                <?php if (!empty($it['image_path'])): ?>
                  <div style="margin-top:8px;color:#888;font-size:0.85rem;">
                    Current: <a href="<?php echo htmlspecialchars($it['image_path']); ?>" target="_blank" style="color:var(--gold);">view</a>
                  </div>
                <?php endif; ?>
              </div>

              <button type="submit" class="btn-submit">Save Item</button>
            </form>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- BOUNTIES -->
  <div class="quest-category">
    <div class="category-header">
      <div class="category-icon">💰</div>
      <div class="category-title">Bounties</div>
    </div>

    <div class="quest-list">
      <?php foreach ($bounties as $b): ?>
        <?php $bid = (int)$b['id']; ?>
        <div class="quest-item" style="cursor:default;">
          <div style="width:100%;">
            <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;">
              <div style="font-weight:900;color:#fff;"><?php echo htmlspecialchars($b['name']); ?></div>
              <div style="color:#888;font-size:0.85rem;"><?php echo !empty($b['completed']) ? '✅ Completed' : '📜 Active'; ?></div>
            </div>

            <form method="POST" enctype="multipart/form-data" style="margin-top:12px;">
              <input type="hidden" name="type" value="bounty">
              <input type="hidden" name="id" value="<?php echo $bid; ?>">

              <div class="form-group">
                <label class="form-label">Name</label>
                <input class="form-input" name="name" value="<?php echo htmlspecialchars($b['name']); ?>">
              </div>

              <div class="form-group">
                <label class="form-label">Description</label>
                <textarea class="form-textarea" name="description" rows="2"><?php echo htmlspecialchars($b['description'] ?? ''); ?></textarea>
              </div>

              <div class="grid-2">
                <div class="form-group">
                  <label class="form-label">XP Reward</label>
                  <input type="number" class="form-input" name="xp_reward" value="<?php echo (int)($b['xp_reward'] ?? 100); ?>" min="0" max="5000">
                </div>

                <div class="form-group">
                  <label class="form-label">Completed</label>
                  <label style="display:flex;align-items:center;gap:10px;color:#ddd;">
                    <input type="checkbox" name="completed" <?php echo !empty($b['completed'])?'checked':''; ?>>
                    Mark as completed
                  </label>
                </div>
              </div>

              <div class="form-group">
                <label class="form-label">Replace Image (optional)</label>
                <input type="file" class="form-input" name="image" accept="image/*">
                <?php if (!empty($b['image_path'])): ?>
                  <div style="margin-top:8px;color:#888;font-size:0.85rem;">
                    Current: <a href="<?php echo htmlspecialchars($b['image_path']); ?>" target="_blank" style="color:var(--gold);">view</a>
                  </div>
                <?php endif; ?>
              </div>

              <button type="submit" class="btn-submit">Save Bounty</button>
            </form>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

</div>

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