<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/flash.php';
require_admin();
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
$id = (int)($_GET['id'] ?? 0);
$row = null;
if ($id > 0) {
    $st = db()->prepare('SELECT * FROM pricing_plans WHERE id = ?');
    $st->execute([$id]);
    $row = $st->fetch();
}
$featureRows = [];
if ($id > 0 && $row) {
    $fs = db()->prepare('SELECT * FROM pricing_features WHERE plan_id = ? ORDER BY sort_order ASC, id ASC');
    $fs->execute([$id]);
    $featureRows = $fs->fetchAll() ?: [];
}
if ($featureRows === []) {
    $featureRows = [
        ['label' => '', 'icon_style' => 'check', 'sort_order' => 0],
    ];
}
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify($_POST['csrf'] ?? null)) {
    $cardTitle = trim((string)($_POST['card_title'] ?? ''));
    $priceDisplay = trim((string)($_POST['price_display'] ?? ''));
    $planName = trim((string)($_POST['plan_name'] ?? ''));
    $ctaUrl = trim((string)($_POST['cta_url'] ?? ''));
    if ($ctaUrl === '') {
        $ctaUrl = 'contact.php';
    }
    $ctaLabel = trim((string)($_POST['cta_label'] ?? ''));
    if ($ctaLabel === '') {
        $ctaLabel = 'Choose Packages';
    }
    $isFeatured = !empty($_POST['is_featured']) ? 1 : 0;
    $ctaYellow = !empty($_POST['cta_yellow']) ? 1 : 0;
    $ctaInWrapper = !empty($_POST['cta_in_wrapper']) ? 1 : 0;
    $isActive = !empty($_POST['is_active']) ? 1 : 0;
    $sort = (int)($_POST['sort_order'] ?? 0);
    if ($cardTitle === '') {
        $cardTitle = 'Solar Service Price';
    }
    if ($priceDisplay === '') {
        $error = 'Price display is required (e.g. $80 or ₹4,999).';
    } elseif ($planName === '') {
        $error = 'Plan name is required.';
    } else {
        $labels = (array)($_POST['feature_label'] ?? []);
        $styles = (array)($_POST['feature_style'] ?? []);
        $cleanFeatures = [];
        $n = max(count($labels), count($styles));
        for ($i = 0; $i < $n; $i++) {
            $lab = trim((string)($labels[$i] ?? ''));
            if ($lab === '') {
                continue;
            }
            $styl = (string)($styles[$i] ?? 'check');
            if ($styl !== 'mark') {
                $styl = 'check';
            }
            $cleanFeatures[] = ['label' => $lab, 'icon_style' => $styl];
        }
        if ($cleanFeatures === []) {
            $error = 'Add at least one feature line.';
        } else {
            if ($id > 0) {
                db()->prepare(
                    'UPDATE pricing_plans SET card_title=?, price_display=?, plan_name=?, cta_url=?, cta_label=?, is_featured=?, cta_yellow=?, cta_in_wrapper=?, sort_order=?, is_active=? WHERE id=?'
                )->execute([
                    $cardTitle, $priceDisplay, $planName, $ctaUrl, $ctaLabel,
                    $isFeatured, $ctaYellow, $ctaInWrapper, $sort, $isActive, $id,
                ]);
                db()->prepare('DELETE FROM pricing_features WHERE plan_id = ?')->execute([$id]);
            } else {
                db()->prepare(
                    'INSERT INTO pricing_plans (card_title, price_display, plan_name, cta_url, cta_label, is_featured, cta_yellow, cta_in_wrapper, sort_order, is_active) VALUES (?,?,?,?,?,?,?,?,?,?)'
                )->execute([
                    $cardTitle, $priceDisplay, $planName, $ctaUrl, $ctaLabel,
                    $isFeatured, $ctaYellow, $ctaInWrapper, $sort, $isActive,
                ]);
                $id = (int)db()->lastInsertId();
            }
            $insF = db()->prepare(
                'INSERT INTO pricing_features (plan_id, label, icon_style, sort_order) VALUES (?,?,?,?)'
            );
            $ord = 0;
            foreach ($cleanFeatures as $cf) {
                $ord++;
                $insF->execute([$id, $cf['label'], $cf['icon_style'], $ord]);
            }
            $fromEdit = (int)($_GET['id'] ?? 0) > 0;
            admin_flash_set('success', $fromEdit ? 'Pricing plan updated.' : 'Pricing plan created.');
            header('Location: pricing.php');
            exit;
        }
    }
}
if ($id > 0 && !$row) {
    admin_flash_set('danger', 'Not found.');
    header('Location: pricing.php');
    exit;
}
if ($error !== '' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $featureRows = [];
    $labs = (array)($_POST['feature_label'] ?? []);
    $stys = (array)($_POST['feature_style'] ?? []);
    for ($i = 0, $c = max(count($labs), count($stys), 1); $i < $c; $i++) {
        $featureRows[] = [
            'label' => (string)($labs[$i] ?? ''),
            'icon_style' => (string)($stys[$i] ?? 'check') === 'mark' ? 'mark' : 'check',
        ];
    }
}
$page = 'pricing';
$pageTitle = $id ? 'Edit pricing plan' : 'New pricing plan';
$pageSubtitle = 'Card text, price, CTA, and check-list lines (matches the home page layout).';
$breadcrumbs = [['label' => 'Dashboard', 'href' => 'index.php'], ['label' => 'Home pricing', 'href' => 'pricing.php'], ['label' => $id ? 'Edit' : 'New', 'href' => null]];
$headerActions = '<a href="pricing.php" class="btn btn-outline-secondary btn-sm">Back to list</a>';
require __DIR__ . '/includes/layout-header.php';
$defaults = [
    'card_title' => 'Solar Service Price',
    'price_display' => '',
    'plan_name' => '',
    'cta_url' => 'contact.php',
    'cta_label' => 'Choose Packages',
    'is_featured' => 0,
    'cta_yellow' => 0,
    'cta_in_wrapper' => 1,
    'is_active' => 1,
    'sort_order' => 0,
];
$r = array_merge($defaults, $row ?: []);
if (isset($_POST['card_title']) && $error) {
    $r['card_title'] = (string)($_POST['card_title'] ?? $r['card_title']);
    $r['price_display'] = (string)($_POST['price_display'] ?? '');
    $r['plan_name'] = (string)($_POST['plan_name'] ?? '');
    $r['cta_url'] = (string)($_POST['cta_url'] ?? 'contact.php');
    $r['cta_label'] = (string)($_POST['cta_label'] ?? 'Choose Packages');
    $r['is_featured'] = !empty($_POST['is_featured']) ? 1 : 0;
    $r['cta_yellow'] = !empty($_POST['cta_yellow']) ? 1 : 0;
    $r['cta_in_wrapper'] = !empty($_POST['cta_in_wrapper']) ? 1 : 0;
    $r['is_active'] = !empty($_POST['is_active']) ? 1 : 0;
    $r['sort_order'] = (int)($_POST['sort_order'] ?? 0);
}
if ($error) {
    echo '<div class="alert alert-danger">' . h($error) . '</div>';
}
?>
<form method="post" class="row g-4" id="pricingPlanForm">
  <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
  <div class="col-lg-8">
    <div class="admin-card rounded mb-4">
      <div class="card-header">Plan details</div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label fw-semibold">Card title (top of each card)</label>
            <input type="text" name="card_title" class="form-control" value="<?= h((string)($r['card_title'] ?? '')) ?>">
          </div>
          <div class="col-md-6">
            <label class="form-label fw-semibold">Price <span class="text-danger">*</span></label>
            <input type="text" name="price_display" class="form-control" required value="<?= h((string)($r['price_display'] ?? '')) ?>" placeholder="e.g. $80 or ₹1,200/mo">
          </div>
          <div class="col-12">
            <label class="form-label fw-semibold">Plan name <span class="text-danger">*</span> (line under the price)</label>
            <input type="text" name="plan_name" class="form-control" required value="<?= h((string)($r['plan_name'] ?? '')) ?>" placeholder="e.g. Repairing Plan">
          </div>
        </div>
      </div>
    </div>
    <div class="admin-card rounded mb-4">
      <div class="card-header d-flex justify-content-between align-items-center">
        <span>Feature list</span>
        <button type="button" class="btn btn-sm btn-outline-primary" id="addFeatureRow"><i class="bi bi-plus-lg"></i> Add line</button>
      </div>
      <div class="card-body">
        <p class="text-muted small">Each line appears with a check icon. Use <strong>Alternate (mark)</strong> for the secondary icon style (same as the old template’s last rows).</p>
        <div id="featureRows">
          <?php foreach ($featureRows as $i => $fr): ?>
            <div class="row g-2 align-items-end feature-row mb-2">
              <div class="col">
                <label class="form-label small text-muted">Feature text</label>
                <input type="text" name="feature_label[]" class="form-control" value="<?= h((string)($fr['label'] ?? '')) ?>" placeholder="e.g. Maintained equipment">
              </div>
              <div class="col-md-3">
                <label class="form-label small text-muted">Icon</label>
                <select name="feature_style[]" class="form-select">
                  <option value="check"<?= (isset($fr['icon_style']) && (string)$fr['icon_style'] === 'mark') ? '' : ' selected' ?>>Check</option>
                  <option value="mark"<?= (isset($fr['icon_style']) && (string)$fr['icon_style'] === 'mark') ? ' selected' : '' ?>>Alternate (mark)</option>
                </select>
              </div>
              <div class="col-auto">
                <button type="button" class="btn btn-outline-danger remove-feature" title="Remove" aria-label="Remove"><i class="bi bi-x-lg"></i></button>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="admin-card rounded mb-4">
      <div class="card-header">Call to action</div>
      <div class="card-body">
        <p class="text-muted small">On the home page, the button opens <strong>WhatsApp</strong> with a pre-filled message (plan name, price, and features). Set the number under <a href="contact-settings.php">Contact &amp; map</a> → WhatsApp.</p>
        <div class="mb-3">
          <label class="form-label fw-semibold">Legacy URL (not used on home; kept for data export)</label>
          <input type="text" name="cta_url" class="form-control" value="<?= h((string)($r['cta_url'] ?? 'contact.php')) ?>" placeholder="contact.php">
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">Button label</label>
          <input type="text" name="cta_label" class="form-control" value="<?= h((string)($r['cta_label'] ?? 'Choose Packages')) ?>">
        </div>
        <div class="form-check form-switch mb-2">
          <input class="form-check-input" type="checkbox" name="is_featured" id="is_featured" value="1"<?= !empty($r['is_featured']) ? ' checked' : '' ?>>
          <label class="form-check-label" for="is_featured">Highlight card (ring style)</label>
        </div>
        <div class="form-check form-switch mb-2">
          <input class="form-check-input" type="checkbox" name="cta_yellow" id="cta_yellow" value="1"<?= !empty($r['cta_yellow']) ? ' checked' : '' ?>>
          <label class="form-check-label" for="cta_yellow">Yellow CTA style</label>
        </div>
        <div class="form-check form-switch mb-2">
          <input class="form-check-input" type="checkbox" name="cta_in_wrapper" id="cta_in_wrapper" value="1"<?= !empty($r['cta_in_wrapper']) ? ' checked' : '' ?>>
          <label class="form-check-label" for="cta_in_wrapper">Wrap button in price footer block</label>
        </div>
        <div class="form-check form-switch mb-0">
          <input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1"<?= !empty($r['is_active']) ? ' checked' : '' ?>>
          <label class="form-check-label" for="is_active">Show on home page</label>
        </div>
      </div>
    </div>
    <div class="admin-card rounded mb-4">
      <div class="card-header">Order</div>
      <div class="card-body">
        <label class="form-label">Sort order</label>
        <input type="number" name="sort_order" class="form-control" value="<?= (int)($r['sort_order'] ?? 0) ?>">
        <div class="form-text">Lower numbers appear first.</div>
      </div>
    </div>
    <button type="submit" class="btn btn-primary btn-lg w-100 mb-2"><i class="bi bi-check-lg me-1"></i>Save</button>
    <a href="pricing.php" class="btn btn-outline-secondary w-100">Cancel</a>
  </div>
</form>
<template id="featureRowTemplate">
  <div class="row g-2 align-items-end feature-row mb-2">
    <div class="col">
      <label class="form-label small text-muted">Feature text</label>
      <input type="text" name="feature_label[]" class="form-control" value="" placeholder="e.g. Maintained equipment">
    </div>
    <div class="col-md-3">
      <label class="form-label small text-muted">Icon</label>
      <select name="feature_style[]" class="form-select">
        <option value="check" selected>Check</option>
        <option value="mark">Alternate (mark)</option>
      </select>
    </div>
    <div class="col-auto">
      <button type="button" class="btn btn-outline-danger remove-feature" title="Remove" aria-label="Remove"><i class="bi bi-x-lg"></i></button>
    </div>
  </div>
</template>
<script>
(function () {
  const wrap = document.getElementById('featureRows');
  const tpl = document.getElementById('featureRowTemplate');
  document.getElementById('addFeatureRow')?.addEventListener('click', function () {
    if (!wrap || !tpl) return;
    const node = tpl.content.firstElementChild;
    if (!node) return;
    wrap.appendChild(node.cloneNode(true));
  });
  document.getElementById('pricingPlanForm')?.addEventListener('click', function (e) {
    const t = e.target;
    if (!t) return;
    if (t.closest && t.closest('.remove-feature')) {
      const row = t.closest('.feature-row');
      if (row && wrap && wrap.querySelectorAll('.feature-row').length > 1) {
        row.remove();
      }
    }
  });
})();
</script>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
