<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_plans') {
        $plans = getPlans();
        foreach ($plans as &$plan) {
            $id = $plan['id'];
            if (isset($_POST["price_$id"])) {
                $plan['price'] = floatval($_POST["price_$id"]);
                $plan['days'] = intval($_POST["days_$id"]);
                $plan['label'] = trim($_POST["label_$id"]);
                $plan['offer'] = isset($_POST["offer_$id"]);
                $originalPrice = trim($_POST["original_price_$id"] ?? '');
                $plan['original_price'] = ($originalPrice !== '') ? floatval($originalPrice) : null;
            }
        }
        unset($plan);
        writeJson(PLANS_FILE, $plans);
        $message = 'Plans updated successfully!';
        $messageType = 'success';
    } elseif ($action === 'add_plan') {
        $plans = getPlans();
        $newId = 'plan_' . time();
        $plans[] = [
            'id' => $newId,
            'price' => floatval($_POST['new_price'] ?? 0),
            'days' => intval($_POST['new_days'] ?? 0),
            'original_price' => null,
            'offer' => false,
            'label' => trim($_POST['new_label'] ?? 'New Plan')
        ];
        writeJson(PLANS_FILE, $plans);
        $message = 'New plan added!';
        $messageType = 'success';
    } elseif ($action === 'delete_plan') {
        $plans = getPlans();
        $planIdToDelete = $_POST['plan_id'] ?? '';
        $plans = array_values(array_filter($plans, function($p) use ($planIdToDelete) {
            return $p['id'] !== $planIdToDelete;
        }));
        writeJson(PLANS_FILE, $plans);
        $message = 'Plan deleted.';
        $messageType = 'success';
    }
}

$plans = getPlans();

$pageTitle = 'Plan Editor';
$pageSub = 'Edit prices, durations and special-offer flags.';
include __DIR__ . '/../includes/admin_header.php';
?>

<div class="admin-wrap">
  <?php if ($message): ?>
    <div class="alert alert-<?= $messageType === 'success' ? 'ok' : 'warn' ?>"><?= htmlspecialchars($message) ?></div>
  <?php endif; ?>

  <form method="POST">
    <input type="hidden" name="action" value="update_plans">

    <?php foreach ($plans as $plan): $id = $plan['id']; ?>
      <div class="card">
        <div class="grid3">
          <div>
            <label class="label" for="label_<?= $id ?>">Label</label>
            <input class="input" type="text" id="label_<?= $id ?>" name="label_<?= $id ?>" value="<?= htmlspecialchars($plan['label']) ?>">
          </div>
          <div>
            <label class="label" for="price_<?= $id ?>">Price (₹)</label>
            <input class="input" type="number" step="0.01" id="price_<?= $id ?>" name="price_<?= $id ?>" value="<?= $plan['price'] ?>">
          </div>
          <div>
            <label class="label" for="days_<?= $id ?>">Duration (days)</label>
            <input class="input" type="number" id="days_<?= $id ?>" name="days_<?= $id ?>" value="<?= $plan['days'] ?>">
          </div>
        </div>
        <div class="grid3" style="margin-top:16px;">
          <div>
            <label class="label" for="orig_<?= $id ?>">Original price (strikethrough, optional)</label>
            <input class="input" type="number" step="0.01" id="orig_<?= $id ?>" name="original_price_<?= $id ?>" value="<?= $plan['original_price'] ?? '' ?>" placeholder="e.g. 500">
          </div>
          <div>
            <label class="label">Special offer</label>
            <label class="switch">
              <input type="checkbox" name="offer_<?= $id ?>" <?= $plan['offer'] ? 'checked' : '' ?>>
              <span class="switch-track"><span class="switch-thumb"></span></span>
            </label>
          </div>
          <div style="display:flex; align-items:flex-end;">
            <button type="button" class="btn btn-danger btn-sm" onclick="deletePlan('<?= $id ?>')">Delete plan</button>
          </div>
        </div>
      </div>
    <?php endforeach; ?>

    <button type="submit" class="btn btn-primary btn-block" style="padding:14px;">Save all changes</button>
  </form>

  <div class="card" style="margin-top:26px;">
    <h2 class="card-title">Add new plan</h2>
    <form method="POST">
      <input type="hidden" name="action" value="add_plan">
      <div class="grid3">
        <div>
          <label class="label" for="newLabel">Label</label>
          <input class="input" type="text" id="newLabel" name="new_label" placeholder="e.g. 500 Days" required>
        </div>
        <div>
          <label class="label" for="newPrice">Price (₹)</label>
          <input class="input" type="number" step="0.01" id="newPrice" name="new_price" required>
        </div>
        <div>
          <label class="label" for="newDays">Duration (days)</label>
          <input class="input" type="number" id="newDays" name="new_days" required>
        </div>
      </div>
      <div class="row mt-24">
        <button type="submit" class="btn btn-primary">Add plan</button>
      </div>
    </form>
  </div>
</div>

<form method="POST" id="deletePlanForm" style="display:none;">
  <input type="hidden" name="action" value="delete_plan">
  <input type="hidden" name="plan_id" id="deletePlanId">
</form>

<script>
    function deletePlan(id) {
        if (confirm('Delete this plan permanently?')) {
            document.getElementById('deletePlanId').value = id;
            document.getElementById('deletePlanForm').submit();
        }
    }
</script>

<?php include __DIR__ . '/../includes/admin_footer.php'; ?>
