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

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

/**
 * TEMP DEBUG LOG (optional)
 * Writes PHP errors to /RPG/php-edit-error.log
 */
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/php-edit-error.log');
error_reporting(E_ALL);

/**
 * NOTE:
 * Do NOT declare esc() here.
 * header.php already declares esc(), and redeclaring causes a fatal error.
 */

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

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

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

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

  try {
    /* =========================
       DELETE
       ========================= */
    if ($do === 'delete' && $id > 0) {
      $db->beginTransaction();

      if ($type === 'habit') {
        if ($hasCostsTable) {
          $stmt = $db->prepare("DELETE FROM habit_item_costs WHERE habit_id = ?");
          $stmt->execute([$id]);
        }

        // delete completion history for habit (XP stays unchanged)
        $stmt = $db->prepare("DELETE FROM completions WHERE habit_id = ?");
        $stmt->execute([$id]);

        $stmt = $db->prepare("DELETE FROM habits WHERE id = ?");
        $stmt->execute([$id]);

        $message = "Quest deleted. (Champion XP unchanged.)";
      }

      if ($type === 'item') {
        // BLOCK deletion if linked to a quest
        if ($hasCostsTable) {
          $stmt = $db->prepare("SELECT COUNT(*) AS c FROM habit_item_costs WHERE item_id = ?");
          $stmt->execute([$id]);
          $linked = (int)($stmt->fetch()['c'] ?? 0);
          if ($linked > 0) {
            $db->rollBack();
            throw new Exception("Cannot delete item: it is linked to {$linked} quest(s). Unlink it from those quests first.");
          }
        }

        $stmt = $db->prepare("DELETE FROM items WHERE id = ?");
        $stmt->execute([$id]);

        $message = "Item deleted.";
      }

      if ($type === 'bounty') {
        // deleting claimed bounty removes badge (row gone). XP stays.
        $stmt = $db->prepare("DELETE FROM bounties WHERE id = ?");
        $stmt->execute([$id]);

        $message = "Bounty deleted. (Badge removed if claimed; XP unchanged.)";
      }

      $db->commit();
    }

    /* =========================
       SAVE
       ========================= */
    if ($do === 'save' && $id > 0) {

      if ($type === 'habit') {
        $name = trim($_POST['name'] ?? '');
        if ($name === '') throw new Exception("Quest 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]);
        }

        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 = "Quest updated!";
      }

      if ($type === 'item') {
        $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') {
        $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, completed_by_champion_id = NULL WHERE id=?");
          $stmt->execute([$id]);
        }

        $message = "Bounty updated!";
      }
    }

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

/* ========= Load data ========= */
$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();

$costMap = [];
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'];
  }
}
?>

<?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 esc($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 esc($error); ?>
  </div>
<?php endif; ?>

<div class="hero-section">
  <h1 class="champion-name">🛠️ Edit Console</h1>
  <div class="champion-tagline">Delete enabled. Item delete blocked if linked to a quest.</div>
</div>

<div class="quest-grid">

  <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 if (empty($habits)): ?>
        <div style="color:#666; text-align:center; padding:20px;">No quests yet.</div>
      <?php endif; ?>

      <?php foreach ($habits as $h): $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 esc($h['name']); ?></div>
              <form method="POST" style="margin:0;">
                <input type="hidden" name="type" value="habit">
                <input type="hidden" name="id" value="<?php echo $hid; ?>">
                <input type="hidden" name="do" value="delete">
                <button class="nav-btn" type="submit"
                        onclick="return confirm('Delete this quest? XP will NOT change.');"
                        style="border-color:#f44336;color:#f44336;">Delete</button>
              </form>
            </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; ?>">
              <input type="hidden" name="do" value="save">
              <div class="form-group">
                <label class="form-label">Name</label>
                <input class="form-input" name="name" value="<?php echo esc($h['name']); ?>">
              </div>
              <div class="form-group">
                <label class="form-label">Description</label>
                <textarea class="form-textarea" name="description" rows="2"><?php echo esc($h['description'] ?? ''); ?></textarea>
              </div>
              <button type="submit" class="btn-submit">Save Quest</button>
            </form>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <div class="quest-category">
    <div class="category-header">
      <div class="category-icon">🎒</div>
      <div class="category-title">Items</div>
    </div>

    <div class="quest-list">
      <?php if (empty($items)): ?>
        <div style="color:#666; text-align:center; padding:20px;">No items yet.</div>
      <?php endif; ?>

      <?php foreach ($items as $it): $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 esc($it['name']); ?></div>
              <form method="POST" style="margin:0;">
                <input type="hidden" name="type" value="item">
                <input type="hidden" name="id" value="<?php echo $iid; ?>">
                <input type="hidden" name="do" value="delete">
                <button class="nav-btn" type="submit"
                        onclick="return confirm('Delete this item? If linked to quests, deletion is blocked.');"
                        style="border-color:#f44336;color:#f44336;">Delete</button>
              </form>
            </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; ?>">
              <input type="hidden" name="do" value="save">
              <div class="form-group">
                <label class="form-label">Name</label>
                <input class="form-input" name="name" value="<?php echo esc($it['name']); ?>">
              </div>
              <button type="submit" class="btn-submit">Save Item</button>
            </form>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <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 if (empty($bounties)): ?>
        <div style="color:#666; text-align:center; padding:20px;">No bounties yet.</div>
      <?php endif; ?>

      <?php foreach ($bounties as $b): $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 esc($b['name']); ?></div>
              <form method="POST" style="margin:0;">
                <input type="hidden" name="type" value="bounty">
                <input type="hidden" name="id" value="<?php echo $bid; ?>">
                <input type="hidden" name="do" value="delete">
                <button class="nav-btn" type="submit"
                        onclick="return confirm('Delete this bounty? Badge disappears if claimed. XP will NOT roll back.');"
                        style="border-color:#f44336;color:#f44336;">Delete</button>
              </form>
            </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; ?>">
              <input type="hidden" name="do" value="save">
              <div class="form-group">
                <label class="form-label">Name</label>
                <input class="form-input" name="name" value="<?php echo esc($b['name']); ?>">
              </div>
              <button type="submit" class="btn-submit">Save Bounty</button>
            </form>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

</div>

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