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

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

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; // 2MB

  $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;
}

// Items for linking to habits
$itemsForLinking = [];
try {
  $stmt = $db->query("SELECT id, name, quantity, rarity FROM items ORDER BY name ASC");
  $itemsForLinking = $stmt->fetchAll();
} catch (Throwable $e) {
  $itemsForLinking = [];
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  try {
    if (isset($_POST['add_habit'])) {
      $habitName = trim($_POST['habit_name'] ?? '');
      $habitDesc = trim($_POST['habit_desc'] ?? '');
      $habitTime = $_POST['habit_time'] ?? 'morning';
      $habitFreq = $_POST['habit_freq'] ?? 'daily';
      $habitXP   = (int)($_POST['habit_xp'] ?? 25);
      $showCal   = isset($_POST['habit_calendar']) ? 1 : 0;

      if ($habitName === '') throw new Exception("Quest name is required.");

      $imagePath = safeImageUpload('habit_image', 'habits');

      $db->beginTransaction();

      $stmt = $db->prepare("
        INSERT INTO habits (name, description, time_of_day, frequency, xp_reward, show_on_calendar, image_path)
        VALUES (?, ?, ?, ?, ?, ?, ?)
      ");
      $stmt->execute([$habitName, $habitDesc, $habitTime, $habitFreq, $habitXP, $showCal, $imagePath]);

      $habitId = (int)$db->lastInsertId();

      // Link items (multiple)
      $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 (?, ?, ?)
                             ON DUPLICATE KEY UPDATE qty = VALUES(qty)");

        foreach ($linkItemIds as $itemIdRaw) {
          $itemId = (int)$itemIdRaw;
          if ($itemId <= 0) continue;
          $qty = (int)($linkQtys[$itemIdRaw] ?? 1);
          if ($qty <= 0) $qty = 1;
          $ins->execute([$habitId, $itemId, $qty]);
        }
      }

      $db->commit();
      $message = "Quest created successfully (with item costs if selected)!";
    }

    if (isset($_POST['add_item'])) {
      $itemName = trim($_POST['item_name'] ?? '');
      if ($itemName === '') throw new Exception("Item name is required.");

      $imagePath = safeImageUpload('item_image', 'items');

      $stmt = $db->prepare("
        INSERT INTO items (name, subtitle, description, rarity, stat_effect, quantity, image_path)
        VALUES (?, ?, ?, ?, ?, ?, ?)
      ");
      $stmt->execute([
        $itemName,
        trim($_POST['item_subtitle'] ?? ''),
        trim($_POST['item_desc'] ?? ''),
        $_POST['item_rarity'] ?? 'common',
        trim($_POST['item_stat'] ?? ''),
        (int)($_POST['item_qty'] ?? 1),
        $imagePath
      ]);

      $message = "Item added to inventory!";
    }

    if (isset($_POST['add_bounty'])) {
      $bountyName = trim($_POST['bounty_name'] ?? '');
      if ($bountyName === '') throw new Exception("Bounty name is required.");

      $imagePath = safeImageUpload('bounty_image', 'bounties');

      $stmt = $db->prepare("
        INSERT INTO bounties (name, description, xp_reward, image_path)
        VALUES (?, ?, ?, ?)
      ");
      $stmt->execute([
        $bountyName,
        trim($_POST['bounty_desc'] ?? ''),
        (int)($_POST['bounty_xp'] ?? 100),
        $imagePath
      ]);

      $message = "Bounty posted!";
    }
  } catch (Throwable $e) {
    if ($db->inTransaction()) $db->rollBack();
    $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; ?>

<div class="grid-2">
  <!-- New Quest -->
  <div class="form-container">
    <h2 style="color: var(--gold); margin-bottom: 20px; text-align: center;">⚔️ New Quest</h2>

    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="add_habit" value="1">

      <div class="form-group">
        <label class="form-label">Quest Name</label>
        <input type="text" class="form-input" name="habit_name" required placeholder="e.g., Take Apple Cider Vinegar">
      </div>

      <div class="form-group">
        <label class="form-label">Description</label>
        <textarea class="form-textarea" name="habit_desc" rows="2" placeholder="Brief description..."></textarea>
      </div>

      <div class="form-group">
        <label class="form-label">Time of Day</label>
        <select class="form-select" name="habit_time">
          <option value="morning">🌅 Morning</option>
          <option value="midday">☀️ Midday</option>
          <option value="evening">🌙 Evening</option>
        </select>
      </div>

      <div class="form-group">
        <label class="form-label">Frequency</label>
        <select class="form-select" name="habit_freq">
          <option value="daily">Daily</option>
          <option value="weekly">Weekly</option>
          <option value="monthly">Monthly</option>
          <option value="once">One-time</option>
        </select>
      </div>

      <div class="form-group">
        <label class="form-label">XP Reward</label>
        <input type="number" class="form-input" name="habit_xp" value="25" min="5" max="500">
      </div>

      <div class="form-group">
        <label class="form-label">Quest Image</label>
        <div class="file-input-wrapper">
          <label class="file-input-label">
            <input type="file" name="habit_image" accept="image/*" onchange="previewImage(this, 'habitPreview')">
            Click to upload image
          </label>
        </div>
        <img id="habitPreview" class="image-preview" alt="">
      </div>

      <div class="form-group">
        <label class="form-label">
          <input type="checkbox" name="habit_calendar"> Show on Calendar
        </label>
      </div>

      <!-- NEW: Link items consumed -->
      <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:240px;overflow:auto;">
          <?php if (count($itemsForLinking) === 0): ?>
            <div style="color:#888;">No items in inventory yet. Add items first, then come back to link them.</div>
          <?php else: ?>
            <?php foreach ($itemsForLinking as $it): ?>
              <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 (int)$it['id']; ?>">
                  <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 (int)$it['id']; ?>]"
                    value="1"
                    min="1"
                  >
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
        <div style="color:#888;font-size:0.85rem;margin-top:8px;">
          Example: “Take Apple Cider Vinegar” → link item “Apple Cider Vinegar” qty 1.
        </div>
      </div>

      <button type="submit" class="btn-submit">Create Quest</button>
    </form>
  </div>

  <!-- New Item -->
  <div class="form-container">
    <h2 style="color: var(--gold); margin-bottom: 20px; text-align: center;">🎒 New Item</h2>
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="add_item" value="1">

      <div class="form-group">
        <label class="form-label">Item Name</label>
        <input type="text" class="form-input" name="item_name" required placeholder="e.g., Apple Cider Vinegar">
      </div>

      <div class="form-group">
        <label class="form-label">Subtitle</label>
        <input type="text" class="form-input" name="item_subtitle" placeholder="e.g., Supplement">
      </div>

      <div class="form-group">
        <label class="form-label">Description</label>
        <textarea class="form-textarea" name="item_desc" rows="2"></textarea>
      </div>

      <div class="form-group">
        <label class="form-label">Rarity</label>
        <select class="form-select" name="item_rarity">
          <option value="common">Common</option>
          <option value="uncommon">Uncommon</option>
          <option value="rare">Rare</option>
          <option value="epic">Epic</option>
          <option value="legendary">Legendary</option>
        </select>
      </div>

      <div class="form-group">
        <label class="form-label">Stat/Effect</label>
        <input type="text" class="form-input" name="item_stat" placeholder="e.g., +5 Gut Health">
      </div>

      <div class="form-group">
        <label class="form-label">Quantity</label>
        <input type="number" class="form-input" name="item_qty" value="1" min="0">
      </div>

      <div class="form-group">
        <label class="form-label">Item Image</label>
        <div class="file-input-wrapper">
          <label class="file-input-label">
            <input type="file" name="item_image" accept="image/*" onchange="previewImage(this, 'itemPreview')">
            Click to upload image
          </label>
        </div>
        <img id="itemPreview" class="image-preview" alt="">
      </div>

      <button type="submit" class="btn-submit">Add to Inventory</button>
    </form>
  </div>

  <!-- New Bounty -->
  <div class="form-container">
    <h2 style="color: var(--gold); margin-bottom: 20px; text-align: center;">💰 New Bounty</h2>
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="add_bounty" value="1">

      <div class="form-group">
        <label class="form-label">Bounty Name</label>
        <input type="text" class="form-input" name="bounty_name" required placeholder="e.g., Mow the Lawn">
      </div>

      <div class="form-group">
        <label class="form-label">Description</label>
        <textarea class="form-textarea" name="bounty_desc" rows="2"></textarea>
      </div>

      <div class="form-group">
        <label class="form-label">XP Reward</label>
        <input type="number" class="form-input" name="bounty_xp" value="100" min="10" max="1000">
      </div>

      <div class="form-group">
        <label class="form-label">Bounty Image</label>
        <div class="file-input-wrapper">
          <label class="file-input-label">
            <input type="file" name="bounty_image" accept="image/*" onchange="previewImage(this, 'bountyPreview')">
            Click to upload image
          </label>
        </div>
        <img id="bountyPreview" class="image-preview" alt="">
      </div>

      <button type="submit" class="btn-submit">Post Bounty</button>
    </form>
  </div>
</div>

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