<?php
session_start();
require_once 'db.php';

// ── Admin auth guard ──────────────────────────────────────
if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit;
}
$admin_id = $_SESSION['admin_id'];
$admin    = $conn->query("SELECT * FROM admin_users WHERE id = $admin_id")->fetch_assoc();

$success = '';
$error   = '';

// ── Handle POST actions ───────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'create' || $action === 'edit') {
        $name        = $conn->real_escape_string(trim($_POST['name'] ?? ''));
        $min_amount  = (float)($_POST['min_amount']  ?? 1000);
        $max_amount  = (float)($_POST['max_amount']  ?? 100000);
        $daily_rate  = (float)($_POST['daily_rate']  ?? 2.00);
        $cycle_days  = (int)($_POST['cycle_days']    ?? 365);
        $color_from  = $conn->real_escape_string($_POST['color_from']  ?? '#3eaabb');
        $color_to    = $conn->real_escape_string($_POST['color_to']    ?? '#92c7dd');
        $description = $conn->real_escape_string(trim($_POST['description'] ?? ''));
        $sort_order  = (int)($_POST['sort_order'] ?? 0);
        $active      = isset($_POST['active']) ? 1 : 0;

        if ($name === '') {
            $error = 'Plan name is required.';
        } elseif ($min_amount < 1) {
            $error = 'Minimum amount must be at least 1.';
        } elseif ($max_amount <= $min_amount) {
            $error = 'Maximum amount must be greater than minimum amount.';
        } elseif ($daily_rate <= 0 || $daily_rate > 100) {
            $error = 'Daily rate must be between 0.01% and 100%.';
        } elseif ($cycle_days < 1) {
            $error = 'Cycle days must be at least 1.';
        } else {
            if ($action === 'create') {
                $sql = "INSERT INTO investment_plans 
                        (name, min_amount, max_amount, daily_rate, cycle_days, color_from, color_to, description, sort_order, active)
                        VALUES ('$name', $min_amount, $max_amount, $daily_rate, $cycle_days, '$color_from', '$color_to', '$description', $sort_order, $active)";
                if ($conn->query($sql)) {
                    $success = "Investment plan <strong>$name</strong> created successfully!";
                } else {
                    $error = 'Database error: ' . $conn->error;
                }
            } else {
                $plan_id = (int)$_POST['plan_id'];
                $sql = "UPDATE investment_plans SET
                        name='$name', min_amount=$min_amount, max_amount=$max_amount,
                        daily_rate=$daily_rate, cycle_days=$cycle_days,
                        color_from='$color_from', color_to='$color_to',
                        description='$description', sort_order=$sort_order, active=$active
                        WHERE id=$plan_id";
                if ($conn->query($sql)) {
                    $success = "Plan <strong>$name</strong> updated successfully!";
                } else {
                    $error = 'Database error: ' . $conn->error;
                }
            }
        }
    }

    if ($action === 'toggle') {
        $plan_id = (int)$_POST['plan_id'];
        $conn->query("UPDATE investment_plans SET active = 1 - active WHERE id = $plan_id");
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    if ($action === 'delete') {
        $plan_id = (int)$_POST['plan_id'];
        // Check if any active investment uses this plan
        $in_use = $conn->query("SELECT COUNT(*) AS c FROM investments WHERE plan_id=$plan_id AND status='active'")->fetch_assoc()['c'];
        if ($in_use > 0) {
            $error = "Cannot delete: there are $in_use active investment(s) using this plan.";
        } else {
            $conn->query("DELETE FROM investment_plans WHERE id=$plan_id");
            $success = "Plan deleted.";
        }
    }
}

// ── Fetch all plans ───────────────────────────────────────
$plans = $conn->query("SELECT p.*, 
    (SELECT COUNT(*) FROM investments i WHERE i.plan_id=p.id AND i.status='active') AS active_investors,
    (SELECT COALESCE(SUM(i.amount),0) FROM investments i WHERE i.plan_id=p.id AND i.status='active') AS total_invested
    FROM investment_plans p ORDER BY sort_order ASC, id ASC")->fetch_all(MYSQLI_ASSOC);

// If editing, fetch plan to pre-fill
$edit_plan = null;
if (isset($_GET['edit'])) {
    $eid = (int)$_GET['edit'];
    $edit_plan = $conn->query("SELECT * FROM investment_plans WHERE id=$eid")->fetch_assoc();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Investment Plans — Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css">
<style>
  :root {
    --bg-dark: #0d0f1a;
    --bg-card: #141829;
    --bg-input: #1c2035;
    --accent: #6c63ff;
    --accent2: #00d4aa;
    --text-main: #e8eaf6;
    --text-muted: #7986a3;
    --border: #252a45;
    --danger: #ff4f6a;
    --success: #00d4aa;
    --warning: #ffb13b;
  }
  * { box-sizing: border-box; }
  body {
    background: var(--bg-dark);
    color: var(--text-main);
    font-family: 'Segoe UI', system-ui, sans-serif;
    min-height: 100vh;
  }
  /* Sidebar wrapper */
  .admin-layout { display: flex; min-height: 100vh; }
  .admin-sidebar {
    width: 240px; min-height: 100vh;
    background: var(--bg-card);
    border-right: 1px solid var(--border);
    padding: 24px 0;
    position: sticky; top: 0; height: 100vh; overflow-y: auto;
    flex-shrink: 0;
  }
  .sidebar-brand {
    display: flex; align-items: center; gap: 10px;
    padding: 0 20px 24px;
    border-bottom: 1px solid var(--border);
    margin-bottom: 12px;
  }
  .sidebar-brand .logo {
    width: 36px; height: 36px; border-radius: 10px;
    background: linear-gradient(135deg, var(--accent), var(--accent2));
    display: flex; align-items: center; justify-content: center;
    font-weight: 700; font-size: 16px; color: #fff;
  }
  .sidebar-brand span { font-weight: 700; font-size: 15px; }
  .nav-link-admin {
    display: flex; align-items: center; gap: 10px;
    padding: 10px 20px; color: var(--text-muted);
    text-decoration: none; border-radius: 0; font-size: 14px;
    transition: all .2s;
  }
  .nav-link-admin:hover, .nav-link-admin.active {
    color: var(--text-main);
    background: rgba(108,99,255,.15);
    border-left: 3px solid var(--accent);
  }
  .nav-link-admin i { font-size: 17px; }

  /* Main content */
  .admin-main { flex: 1; padding: 28px 32px; }
  .page-header {
    display: flex; align-items: center; justify-content: space-between;
    margin-bottom: 28px;
  }
  .page-title { font-size: 22px; font-weight: 700; margin: 0; }
  .page-sub { color: var(--text-muted); font-size: 13px; margin-top: 2px; }

  /* Card */
  .card-admin {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 14px; overflow: hidden;
  }
  .card-admin-header {
    padding: 16px 20px;
    border-bottom: 1px solid var(--border);
    display: flex; align-items: center; justify-content: space-between;
    font-weight: 600; font-size: 15px;
  }

  /* Table */
  .table-admin { width: 100%; border-collapse: collapse; font-size: 13.5px; }
  .table-admin thead th {
    padding: 12px 16px; background: rgba(255,255,255,.03);
    color: var(--text-muted); font-weight: 600; text-transform: uppercase;
    font-size: 11px; letter-spacing: .6px; border-bottom: 1px solid var(--border);
    white-space: nowrap;
  }
  .table-admin tbody td {
    padding: 13px 16px; border-bottom: 1px solid var(--border);
    vertical-align: middle;
  }
  .table-admin tbody tr:last-child td { border-bottom: none; }
  .table-admin tbody tr:hover td { background: rgba(255,255,255,.02); }

  /* Badges */
  .badge-status {
    display: inline-block; padding: 4px 10px;
    border-radius: 20px; font-size: 11px; font-weight: 600;
  }
  .badge-active { background: rgba(0,212,170,.15); color: var(--success); }
  .badge-inactive { background: rgba(255,79,106,.12); color: var(--danger); }

  /* Plan color swatch */
  .color-swatch {
    display: inline-block; width: 60px; height: 20px;
    border-radius: 4px; vertical-align: middle;
  }

  /* Form */
  .form-label-admin { font-size: 12px; color: var(--text-muted); margin-bottom: 5px; font-weight: 600; text-transform: uppercase; letter-spacing: .5px; }
  .form-ctrl {
    width: 100%;
    background: var(--bg-input);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 9px 13px;
    color: var(--text-main);
    font-size: 14px;
    outline: none; transition: border .2s;
  }
  .form-ctrl:focus { border-color: var(--accent); }
  .form-ctrl::placeholder { color: var(--text-muted); }
  select.form-ctrl option { background: var(--bg-card); }

  .btn-accent {
    background: linear-gradient(135deg, var(--accent), #8b7cf8);
    color: #fff; border: none; border-radius: 8px;
    padding: 9px 20px; font-size: 14px; font-weight: 600;
    cursor: pointer; transition: opacity .2s;
  }
  .btn-accent:hover { opacity: .88; color: #fff; }
  .btn-outline-danger-sm {
    background: transparent; border: 1px solid var(--danger);
    color: var(--danger); border-radius: 6px; padding: 5px 11px;
    font-size: 12px; cursor: pointer; transition: all .2s;
  }
  .btn-outline-danger-sm:hover { background: var(--danger); color: #fff; }
  .btn-sm-edit {
    background: rgba(108,99,255,.2); border: none;
    color: var(--accent); border-radius: 6px; padding: 5px 11px;
    font-size: 12px; cursor: pointer; text-decoration: none; display: inline-block;
    transition: background .2s;
  }
  .btn-sm-edit:hover { background: rgba(108,99,255,.35); color: var(--accent); }
  .btn-toggle {
    background: none; border: none; font-size: 20px; cursor: pointer; line-height: 1;
    transition: transform .15s;
  }
  .btn-toggle:hover { transform: scale(1.15); }

  .alert-admin {
    padding: 12px 16px; border-radius: 9px; font-size: 14px; margin-bottom: 20px;
  }
  .alert-success-admin { background: rgba(0,212,170,.12); color: var(--success); border: 1px solid rgba(0,212,170,.25); }
  .alert-danger-admin  { background: rgba(255,79,106,.12);  color: var(--danger);  border: 1px solid rgba(255,79,106,.25); }

  /* Stats row */
  .stat-chip {
    display: inline-flex; align-items: center; gap: 6px;
    background: rgba(255,255,255,.05); border-radius: 20px;
    padding: 4px 12px; font-size: 12px; color: var(--text-muted);
  }
  .stat-chip strong { color: var(--text-main); }

  @media(max-width:768px){
    .admin-sidebar { display: none; }
    .admin-main { padding: 16px; }
  }
</style>
</head>
<body>
<div class="admin-layout">

  <!-- Sidebar -->
  <nav class="admin-sidebar">
    <div class="sidebar-brand">
      <div class="logo">A</div>
      <span><?= htmlspecialchars($admin['name']) ?></span>
    </div>
    <a href="admin_dashboard.php" class="nav-link-admin"><i class="bi bi-speedometer2"></i> Dashboard</a>
    <a href="admin_plans.php"     class="nav-link-admin"><i class="bi bi-layers"></i> Plans</a>
    <a href="admin_investments.php" class="nav-link-admin active"><i class="bi bi-graph-up-arrow"></i> Investments</a>
    <a href="admin_users.php"     class="nav-link-admin"><i class="bi bi-people"></i> Users</a>
    <a href="admin_settings.php"  class="nav-link-admin"><i class="bi bi-gear"></i> Settings</a>
    <a href="admin_logout.php"    class="nav-link-admin" style="margin-top:auto;color:var(--danger)"><i class="bi bi-box-arrow-right"></i> Logout</a>
  </nav>

  <!-- Main -->
  <main class="admin-main">

    <div class="page-header">
      <div>
        <div class="page-title"><i class="bi bi-graph-up-arrow me-2" style="color:var(--accent)"></i>Investment Plans</div>
        <div class="page-sub">Create and manage investment packages for users</div>
      </div>
      <button class="btn-accent" data-bs-toggle="modal" data-bs-target="#planModal" onclick="resetForm()">
        <i class="bi bi-plus-lg me-1"></i> New Plan
      </button>
    </div>

    <?php if ($success): ?>
      <div class="alert-admin alert-success-admin"><i class="bi bi-check-circle me-2"></i><?= $success ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
      <div class="alert-admin alert-danger-admin"><i class="bi bi-exclamation-triangle me-2"></i><?= $error ?></div>
    <?php endif; ?>

    <!-- Plans Table -->
    <div class="card-admin">
      <div class="card-admin-header">
        <span><i class="bi bi-list-ul me-2"></i>All Investment Plans</span>
        <span class="stat-chip"><strong><?= count($plans) ?></strong> plans</span>
      </div>
      <?php if (empty($plans)): ?>
        <div style="padding:40px;text-align:center;color:var(--text-muted)">
          <i class="bi bi-inbox" style="font-size:36px"></i><br>
          No investment plans yet. Click <strong>New Plan</strong> to create one.
        </div>
      <?php else: ?>
      <div style="overflow-x:auto">
        <table class="table-admin">
          <thead>
            <tr>
              <th>#</th>
              <th>Name</th>
              <th>Min Amount</th>
              <th>Max Amount</th>
              <th>Daily Rate</th>
              <th>Cycle</th>
              <th>Total Return</th>
              <th>Colour</th>
              <th>Investors</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($plans as $p):
              $total_profit_pct = $p['daily_rate'] * $p['cycle_days'];
              $total_return_pct = 100 + $total_profit_pct;
            ?>
            <tr>
              <td style="color:var(--text-muted)"><?= $p['id'] ?></td>
              <td>
                <strong><?= htmlspecialchars($p['name']) ?></strong>
                <?php if ($p['description']): ?>
                  <div style="font-size:11px;color:var(--text-muted);margin-top:2px"><?= htmlspecialchars(mb_strimwidth($p['description'],0,50,'…')) ?></div>
                <?php endif; ?>
              </td>
              <td>TZS <?= number_format($p['min_amount']) ?></td>
              <td>TZS <?= number_format($p['max_amount']) ?></td>
              <td><span style="color:var(--success);font-weight:600"><?= $p['daily_rate'] ?>%</span>/day</td>
              <td><?= $p['cycle_days'] ?> days</td>
              <td style="color:var(--warning);font-weight:600"><?= number_format($total_return_pct, 1) ?>%</td>
              <td>
                <span class="color-swatch" style="background:linear-gradient(90deg,<?= htmlspecialchars($p['color_from']) ?>,<?= htmlspecialchars($p['color_to']) ?>)"></span>
              </td>
              <td>
                <span class="stat-chip"><i class="bi bi-people-fill"></i> <strong><?= $p['active_investors'] ?></strong></span>
              </td>
              <td>
                <?php if ($p['active']): ?>
                  <span class="badge-status badge-active"><i class="bi bi-circle-fill" style="font-size:7px"></i> Active</span>
                <?php else: ?>
                  <span class="badge-status badge-inactive"><i class="bi bi-circle" style="font-size:7px"></i> Inactive</span>
                <?php endif; ?>
              </td>
              <td>
                <div style="display:flex;gap:6px;align-items:center">
                  <!-- Edit -->
                  <a href="#" class="btn-sm-edit" onclick="openEdit(<?= htmlspecialchars(json_encode($p)) ?>)" data-bs-toggle="modal" data-bs-target="#planModal">
                    <i class="bi bi-pencil"></i>
                  </a>
                  <!-- Toggle active -->
                  <form method="POST" style="display:inline">
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="plan_id" value="<?= $p['id'] ?>">
                    <button type="submit" class="btn-toggle" title="Toggle active" style="color:<?= $p['active'] ? 'var(--warning)' : 'var(--success)' ?>">
                      <?= $p['active'] ? '⏸' : '▶' ?>
                    </button>
                  </form>
                  <!-- Delete -->
                  <form method="POST" style="display:inline" onsubmit="return confirm('Delete this plan? This cannot be undone.')">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="plan_id" value="<?= $p['id'] ?>">
                    <button type="submit" class="btn-outline-danger-sm"><i class="bi bi-trash"></i></button>
                  </form>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </div>

  </main>
</div>

<!-- ── Create / Edit Modal ─────────────────────────────── -->
<div class="modal fade" id="planModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content" style="background:var(--bg-card);border:1px solid var(--border);border-radius:16px">
      <div class="modal-header" style="border-bottom:1px solid var(--border)">
        <h5 class="modal-title" style="font-weight:700" id="modalTitle">New Investment Plan</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <div class="modal-body" style="padding:24px">
          <input type="hidden" name="action" id="formAction" value="create">
          <input type="hidden" name="plan_id" id="formPlanId" value="">

          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label-admin">Plan Name *</label>
              <input type="text" name="name" id="fieldName" class="form-ctrl" placeholder="e.g. Gold Plan" required>
            </div>
            <div class="col-md-3">
              <label class="form-label-admin">Sort Order</label>
              <input type="number" name="sort_order" id="fieldSortOrder" class="form-ctrl" value="0" min="0">
            </div>
            <div class="col-md-3" style="display:flex;align-items:flex-end;padding-bottom:2px">
              <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:14px">
                <input type="checkbox" name="active" id="fieldActive" checked style="width:16px;height:16px;accent-color:var(--accent)">
                Active
              </label>
            </div>

            <div class="col-md-6">
              <label class="form-label-admin">Minimum Amount (TZS) *</label>
              <input type="number" name="min_amount" id="fieldMinAmount" class="form-ctrl" value="1000" min="1" required>
            </div>
            <div class="col-md-6">
              <label class="form-label-admin">Maximum Amount (TZS) *</label>
              <input type="number" name="max_amount" id="fieldMaxAmount" class="form-ctrl" value="100000" min="1" required>
            </div>

            <div class="col-md-6">
              <label class="form-label-admin">Daily Increase Rate (%) *</label>
              <input type="number" name="daily_rate" id="fieldDailyRate" class="form-ctrl" value="2.00" min="0.01" max="100" step="0.01" required oninput="calcPreview()">
            </div>
            <div class="col-md-6">
              <label class="form-label-admin">Project Cycle (Days) *</label>
              <input type="number" name="cycle_days" id="fieldCycleDays" class="form-ctrl" value="365" min="1" required oninput="calcPreview()">
            </div>

            <!-- Live preview -->
            <div class="col-12">
              <div id="returnPreview" style="background:rgba(0,212,170,.07);border:1px solid rgba(0,212,170,.2);border-radius:9px;padding:12px 16px;font-size:13px;">
                <i class="bi bi-calculator me-2" style="color:var(--success)"></i>
                <span id="previewText">Total return: <strong>—</strong></span>
              </div>
            </div>

            <div class="col-md-6">
              <label class="form-label-admin">Gradient Color From</label>
              <div style="display:flex;gap:8px;align-items:center">
                <input type="color" name="color_from" id="fieldColorFrom" value="#3eaabb" style="width:44px;height:38px;border:none;background:none;cursor:pointer;padding:0">
                <input type="text" id="fieldColorFromText" class="form-ctrl" value="#3eaabb" oninput="document.getElementById('fieldColorFrom').value=this.value" style="flex:1">
              </div>
            </div>
            <div class="col-md-6">
              <label class="form-label-admin">Gradient Color To</label>
              <div style="display:flex;gap:8px;align-items:center">
                <input type="color" name="color_to" id="fieldColorTo" value="#92c7dd" style="width:44px;height:38px;border:none;background:none;cursor:pointer;padding:0">
                <input type="text" id="fieldColorToText" class="form-ctrl" value="#92c7dd" oninput="document.getElementById('fieldColorTo').value=this.value" style="flex:1">
              </div>
            </div>

            <!-- Colour preview bar -->
            <div class="col-12">
              <div id="colorPreviewBar" style="height:12px;border-radius:6px;background:linear-gradient(90deg,#3eaabb,#92c7dd);transition:background .3s"></div>
            </div>

            <div class="col-12">
              <label class="form-label-admin">Description (optional)</label>
              <textarea name="description" id="fieldDescription" class="form-ctrl" rows="2" placeholder="Short description shown to users…"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer" style="border-top:1px solid var(--border);padding:16px 24px">
          <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn-accent"><i class="bi bi-save me-1"></i> <span id="submitLabel">Create Plan</span></button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
<script>
function calcPreview() {
  const rate = parseFloat(document.getElementById('fieldDailyRate').value) || 0;
  const days = parseInt(document.getElementById('fieldCycleDays').value)   || 0;
  const totalPct = (rate * days).toFixed(2);
  const totalRet = (100 + parseFloat(totalPct)).toFixed(2);
  document.getElementById('previewText').innerHTML =
    `Daily: <strong>${rate}%</strong> × ${days} days = <strong style="color:var(--success)">${totalPct}% profit</strong> &nbsp;|&nbsp; Total return: <strong style="color:var(--warning)">${totalRet}% of principal</strong>`;
}
calcPreview();

// Sync color pickers with text inputs
document.getElementById('fieldColorFrom').addEventListener('input', function(){
  document.getElementById('fieldColorFromText').value = this.value;
  updateColorBar();
});
document.getElementById('fieldColorTo').addEventListener('input', function(){
  document.getElementById('fieldColorToText').value = this.value;
  updateColorBar();
});
function updateColorBar(){
  const f = document.getElementById('fieldColorFrom').value;
  const t = document.getElementById('fieldColorTo').value;
  document.getElementById('colorPreviewBar').style.background = `linear-gradient(90deg,${f},${t})`;
}

function resetForm(){
  document.getElementById('formAction').value  = 'create';
  document.getElementById('formPlanId').value  = '';
  document.getElementById('modalTitle').textContent = 'New Investment Plan';
  document.getElementById('submitLabel').textContent = 'Create Plan';
  document.getElementById('fieldName').value        = '';
  document.getElementById('fieldMinAmount').value   = '1000';
  document.getElementById('fieldMaxAmount').value   = '100000';
  document.getElementById('fieldDailyRate').value   = '2.00';
  document.getElementById('fieldCycleDays').value   = '365';
  document.getElementById('fieldColorFrom').value   = '#3eaabb';
  document.getElementById('fieldColorFromText').value = '#3eaabb';
  document.getElementById('fieldColorTo').value     = '#92c7dd';
  document.getElementById('fieldColorToText').value = '#92c7dd';
  document.getElementById('fieldDescription').value = '';
  document.getElementById('fieldSortOrder').value   = '0';
  document.getElementById('fieldActive').checked    = true;
  updateColorBar(); calcPreview();
}

function openEdit(p){
  document.getElementById('formAction').value  = 'edit';
  document.getElementById('formPlanId').value  = p.id;
  document.getElementById('modalTitle').textContent = 'Edit Plan — ' + p.name;
  document.getElementById('submitLabel').textContent = 'Save Changes';
  document.getElementById('fieldName').value        = p.name;
  document.getElementById('fieldMinAmount').value   = p.min_amount;
  document.getElementById('fieldMaxAmount').value   = p.max_amount;
  document.getElementById('fieldDailyRate').value   = p.daily_rate;
  document.getElementById('fieldCycleDays').value   = p.cycle_days;
  document.getElementById('fieldColorFrom').value   = p.color_from;
  document.getElementById('fieldColorFromText').value = p.color_from;
  document.getElementById('fieldColorTo').value     = p.color_to;
  document.getElementById('fieldColorToText').value = p.color_to;
  document.getElementById('fieldDescription').value = p.description || '';
  document.getElementById('fieldSortOrder').value   = p.sort_order;
  document.getElementById('fieldActive').checked    = p.active == 1;
  updateColorBar(); calcPreview();
}

<?php if ($edit_plan): ?>
openEdit(<?= json_encode($edit_plan) ?>);
var modal = new bootstrap.Modal(document.getElementById('planModal'));
modal.show();
<?php endif; ?>
</script>
</body>
</html>