<?php include "header.php"; ?>

<?php
include_once __DIR__ . '/../includes/subscription_lib.php';

if ($userdata["role"] != 'Admin') {
    echo '<script>window.location.href = "dashboard";</script>';
    exit;
}

// ---------- ADD ----------
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["addsub"])) {
    $planname = $_POST['plan_name'];
    $amount = $_POST['amount'];
    $expiry = $_POST['expiry'];
    $period_type = $_POST['period_type'];
    $max_transactions = (int)$_POST['max_transactions'];
    $cashier_limit = (int)$_POST['cashier_limit'];
    $static_paylink_limit = (int)$_POST['static_paylink_limit'];
    $is_trial = isset($_POST['is_trial']) ? 1 : 0;

    if ($is_trial) {
        // Only one trial plan allowed - demote any existing one
        $conn->query("UPDATE subscription_plan SET is_trial = 0 WHERE is_trial = 1");
    }

    $stmt = $conn->prepare("INSERT INTO subscription_plan (plan_name, amount, expiry, period_type, max_transactions, cashier_limit, static_paylink_limit, is_trial, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Active')");
    if (!$stmt) {
        echo "<script>Swal.fire({title: 'Setup needed', text: '" . addslashes($conn->error) . " - Please run sql/RUN_THIS_ALL_IN_ONE.sql in phpMyAdmin first.', icon: 'error', confirmButtonText: 'OK'});</script>";
        exit;
    }
    $stmt->bind_param("ssssiiii", $planname, $amount, $expiry, $period_type, $max_transactions, $cashier_limit, $static_paylink_limit, $is_trial);
    $ok = $stmt->execute();
    $stmt->close();

    echo "<script>Swal.fire({title: '" . ($ok ? "Success!" : "Error!") . "', text: '" . ($ok ? "Plan added successfully!" : "Could not add plan") . "', icon: '" . ($ok ? "success" : "error") . "', confirmButtonText: 'OK'}).then(() => { window.location.href = 'manage_subscription'; });</script>";
    exit;
}

// ---------- UPDATE ----------
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["updatesub"])) {
    $srno = $_POST['srno'];
    $planname = $_POST['plan_name'];
    $amount = $_POST['amount'];
    $expiry = $_POST['expiry'];
    $period_type = $_POST['period_type'];
    $max_transactions = (int)$_POST['max_transactions'];
    $cashier_limit = (int)$_POST['cashier_limit'];
    $static_paylink_limit = (int)$_POST['static_paylink_limit'];
    $is_trial = isset($_POST['is_trial']) ? 1 : 0;

    if ($is_trial) {
        $conn->query("UPDATE subscription_plan SET is_trial = 0 WHERE id != " . (int)$srno);
    }

    $update_query = "UPDATE subscription_plan SET plan_name = ?, amount = ?, expiry = ?, period_type = ?, max_transactions = ?, cashier_limit = ?, static_paylink_limit = ?, is_trial = ? WHERE id = ?";
    $update_stmt = $conn->prepare($update_query);
    if (!$update_stmt) {
        echo "<script>Swal.fire({title: 'Setup needed', text: '" . addslashes($conn->error) . " - Please run sql/RUN_THIS_ALL_IN_ONE.sql in phpMyAdmin first.', icon: 'error', confirmButtonText: 'OK'});</script>";
        exit;
    }
    $update_stmt->bind_param("ssssiiiii", $planname, $amount, $expiry, $period_type, $max_transactions, $cashier_limit, $static_paylink_limit, $is_trial, $srno);
    $ok = $update_stmt->execute();
    $update_stmt->close();

    echo "<script>Swal.fire({title: '" . ($ok ? "Success!" : "Error!") . "', text: '" . ($ok ? "Subscription updated successfully!" : "Error updating Subscription") . "', icon: '" . ($ok ? "success" : "error") . "', confirmButtonText: 'OK'}).then(() => { window.location.href = 'manage_subscription'; });</script>";
    exit;
}

// ---------- TOGGLE ACTIVE/INACTIVE ----------
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $conn->query("UPDATE subscription_plan SET status = IF(status='Active','Inactive','Active') WHERE id = $id");
    echo '<script>window.location.href = "manage_subscription";</script>';
    exit;
}

// ---------- DELETE ----------
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $inUse = $conn->query("SELECT COUNT(*) AS c FROM user_subscriptions WHERE plan_id = $id AND status='Active'")->fetch_assoc();
    if ($inUse['c'] > 0) {
        echo "<script>Swal.fire({title: 'Cannot Delete', text: 'This plan is currently active for {$inUse['c']} user(s). Deactivate it instead, or wait until nobody is subscribed.', icon: 'warning', confirmButtonText: 'OK'}).then(() => { window.location.href = 'manage_subscription'; });</script>";
        exit;
    }
    $conn->query("DELETE FROM subscription_plan WHERE id = $id");
    echo '<script>Swal.fire({title: "Deleted!", text: "Plan removed.", icon: "success", confirmButtonText: "OK"}).then(() => { window.location.href = "manage_subscription"; });</script>';
    exit;
}

// ---------- MANUAL GRANT (admin gives a user a plan directly, no payment) ----------
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["grantPlan"])) {
    $mobile = trim($_POST['grant_mobile']);
    $grantType = $_POST['grant_type'] ?? 'existing';

    $userRes = $conn->query("SELECT id, name FROM users WHERE mobile = '" . $conn->real_escape_string($mobile) . "' LIMIT 1");
    if (!$userRes || $userRes->num_rows === 0) {
        echo "<script>Swal.fire({title: 'User Not Found', text: 'Is mobile number se koi user register nahi hai.', icon: 'error', confirmButtonText: 'OK'}).then(() => { window.location.href = 'manage_subscription'; });</script>";
        exit;
    }
    $grantUser = $userRes->fetch_assoc();
    $grantUserId = (int)$grantUser['id'];

    if ($grantType === 'existing') {
        $planId = (int)$_POST['grant_plan_id'];
        $ok = activatePlanForUser($conn, $grantUserId, $planId);
    } else {
        // Custom one-off grant: quietly create a hidden (Inactive, so it
        // never appears on the public subscription.php list) plan row just
        // for this grant, then activate it the normal way. This reuses all
        // existing quota/expiry logic with zero special-casing needed.
        $cExpiry = max(1, (int)$_POST['grant_custom_expiry']);
        $cPeriod = in_array($_POST['grant_custom_period'], ['day','week','month','year']) ? $_POST['grant_custom_period'] : 'month';
        $cMaxTx = (int)$_POST['grant_custom_max_transactions'];
        $cCashier = max(1, (int)$_POST['grant_custom_cashier_limit']);
        $cStaticLinks = (int)$_POST['grant_custom_static_paylink_limit'];
        $customName = 'Custom Grant - ' . $mobile . ' - ' . date('Y-m-d H:i');

        $stmt = $conn->prepare("INSERT INTO subscription_plan (plan_name, amount, expiry, period_type, max_transactions, cashier_limit, static_paylink_limit, is_trial, status) VALUES (?, 0, ?, ?, ?, ?, ?, 0, 'Inactive')");
        $stmt->bind_param("sisiii", $customName, $cExpiry, $cPeriod, $cMaxTx, $cCashier, $cStaticLinks);
        $stmt->execute();
        $customPlanId = $stmt->insert_id;
        $stmt->close();

        $ok = $customPlanId ? activatePlanForUser($conn, $grantUserId, $customPlanId) : false;
    }

    $msg = $ok ? "Plan safaltapoorvak {$grantUser['name']} ({$mobile}) ko de diya gaya." : "Plan grant nahi ho paya. Dobara try karein.";
    echo "<script>Swal.fire({title: '" . ($ok ? "Done!" : "Error") . "', text: '" . addslashes($msg) . "', icon: '" . ($ok ? "success" : "error") . "', confirmButtonText: 'OK'}).then(() => { window.location.href = 'manage_subscription'; });</script>";
    exit;
}

$query = $conn->query("SELECT * FROM `subscription_plan` ORDER BY amount ASC");
$plans = [];
if ($query) { while ($row = $query->fetch_assoc()) { $plans[] = $row; } }
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
        --success:#43e97b; --danger:#ff6584; --warning:#f5b93b; --info:#3ea6ff;
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}

    .ms-wrap{padding:20px;max-width:1300px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .ms-head{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px;margin-bottom:22px}
    .ms-head h1{font-size:1.55rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .ms-head h1 .icn{
        width:38px;height:38px;border-radius:12px;background:var(--g);display:inline-flex;
        align-items:center;justify-content:center;font-size:16px;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .ms-head p{font-size:.85rem;color:rgba(255,255,255,.45);margin:4px 0 0 48px}

    .btn-primary-cta{
        background:var(--g);border:none;color:#fff;padding:11px 20px;border-radius:10px;
        font-size:.85rem;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:8px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);text-decoration:none;
    }
    .btn-primary-cta:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45);color:#fff}
    .btn-ghost{
        background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:#fff;
        padding:11px 20px;border-radius:10px;font-size:.85rem;font-weight:600;cursor:pointer;
        display:inline-flex;align-items:center;gap:7px;transition:.2s;text-decoration:none;
    }
    .btn-ghost:hover{background:rgba(255,255,255,.1);color:#fff}

    .glass-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;margin-bottom:20px;
    }
    .card-header{
        padding:18px 22px;border-bottom:1px solid rgba(255,255,255,.07);
        display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;
    }
    .card-header h3{font-size:1.05rem;font-weight:700;margin:0;color:#fff;display:flex;align-items:center;gap:8px}
    .card-header h3 i{color:var(--p)}
    .card-body{padding:22px}

    .form-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:16px}
    @media(max-width:640px){.form-grid{grid-template-columns:1fr}}
    .form-label{display:block;font-size:.78rem;font-weight:600;color:rgba(255,255,255,.5);margin-bottom:7px;text-transform:uppercase;letter-spacing:.3px}
    .form-control{
        width:100%;background:rgba(255,255,255,.05);border:1.5px solid rgba(255,255,255,.1);border-radius:10px;
        padding:11px 13px;color:#fff;font-size:.88rem;outline:none;transition:.2s;font-family:'Inter',sans-serif;
    }
    .form-control:focus{border-color:var(--p);background:rgba(108,99,255,.08);box-shadow:0 0 0 3px rgba(108,99,255,.15)}
    select.form-control{
        -webkit-appearance:none;appearance:none;color:#fff !important;
        background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='14' height='9' viewBox='0 0 14 9'><path d='M1 1l6 6 6-6' stroke='%23a99bff' stroke-width='2' fill='none' stroke-linecap='round' stroke-linejoin='round'/></svg>");
        background-repeat:no-repeat;background-position:right 14px center;padding-right:36px;
    }
    select.form-control option{background:#14141f;color:#fff}

    .check-row{
        display:flex;align-items:center;gap:10px;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.08);
        border-radius:10px;padding:11px 14px;font-size:.82rem;color:rgba(255,255,255,.7);height:100%;
    }
    .check-row input{width:17px;height:17px;accent-color:var(--p);flex-shrink:0}

    .form-actions{display:flex;gap:10px;margin-top:20px}

    /* Plans grid */
    .plans-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:18px}
    .plan-card{
        background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);border-radius:18px;
        overflow:hidden;display:flex;flex-direction:column;transition:.25s;position:relative;
    }
    .plan-card.inactive{opacity:.55}
    .plan-card:hover{transform:translateY(-4px);border-color:rgba(108,99,255,.3)}
    .trial-badge{
        position:absolute;top:12px;right:12px;background:var(--info);color:#fff;font-size:.65rem;
        font-weight:800;padding:4px 9px;border-radius:20px;letter-spacing:.3px;
    }
    .plan-head{padding:22px 18px 16px;text-align:center;border-bottom:1px solid rgba(255,255,255,.07)}
    .plan-name{font-size:.95rem;font-weight:700;color:#a99bff;margin-bottom:8px;text-transform:uppercase;letter-spacing:.3px}
    .plan-price{font-size:1.9rem;font-weight:800;color:#fff;line-height:1}
    .plan-duration{font-size:.78rem;color:rgba(255,255,255,.4);margin-top:6px}
    .plan-body{padding:16px 18px;flex:1}
    .plan-body div{display:flex;justify-content:space-between;font-size:.8rem;color:rgba(255,255,255,.65);padding:6px 0}
    .plan-body div b{color:#fff}
    .status-pill{display:inline-flex;align-items:center;gap:5px;padding:3px 10px;border-radius:20px;font-size:.7rem;font-weight:700}
    .status-active{background:rgba(67,233,123,.13);color:var(--success)}
    .status-inactive{background:rgba(255,255,255,.08);color:rgba(255,255,255,.5)}
    .plan-footer{padding:14px 18px 18px;display:flex;gap:6px;flex-wrap:wrap}
    .act-btn{
        flex:1;min-width:70px;border:none;border-radius:8px;padding:8px 6px;font-size:.72rem;font-weight:700;cursor:pointer;
        display:flex;align-items:center;justify-content:center;gap:5px;transition:.2s;
    }
    .act-edit{background:rgba(62,166,255,.15);color:var(--info)}
    .act-edit:hover{background:rgba(62,166,255,.28)}
    .act-toggle{background:rgba(245,185,59,.15);color:var(--warning)}
    .act-toggle:hover{background:rgba(245,185,59,.28)}
    .act-del{background:rgba(255,101,132,.13);color:var(--danger)}
    .act-del:hover{background:rgba(255,101,132,.28)}

    .empty-state{text-align:center;padding:50px 20px;color:rgba(255,255,255,.35)}
    .empty-state i{font-size:2.2rem;margin-bottom:12px;display:block;color:rgba(255,255,255,.15)}
</style>

<div class="ms-wrap">
    <div class="ms-head">
        <div>
            <h1><span class="icn"><i class="fas fa-crown"></i></span>Manage Subscriptions</h1>
            <p>Create, edit, and control the plans merchants can subscribe to</p>
        </div>
    </div>

    <?php if (isset($_GET["srno"]) && $_GET["srno"] != ''):
        $fetchdata = $conn->query("SELECT * FROM `subscription_plan` WHERE id = '{$_GET["srno"]}'")->fetch_assoc();
    ?>
    <div class="glass-card">
        <div class="card-header"><h3><i class="fas fa-pen"></i> Edit Plan</h3></div>
        <div class="card-body">
            <form method="POST" action="">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <input type="hidden" name="srno" value="<?php echo htmlspecialchars($fetchdata["id"]); ?>">
                <div class="form-grid">
                    <div>
                        <label class="form-label">Plan Name</label>
                        <input type="text" name="plan_name" value="<?php echo htmlspecialchars($fetchdata["plan_name"]); ?>" class="form-control" required>
                    </div>
                    <div>
                        <label class="form-label">Amount (₹)</label>
                        <input type="number" step="0.01" name="amount" value="<?php echo htmlspecialchars($fetchdata["amount"]); ?>" class="form-control" required>
                    </div>
                    <div>
                        <label class="form-label">Duration (number)</label>
                        <input type="number" name="expiry" value="<?php echo htmlspecialchars($fetchdata["expiry"]); ?>" class="form-control" required>
                    </div>
                    <div>
                        <label class="form-label">Duration Unit</label>
                        <select name="period_type" class="form-control">
                            <?php foreach (['day','week','month','year'] as $u): ?>
                                <option value="<?= $u ?>" <?= ($fetchdata['period_type'] ?? 'month') == $u ? 'selected' : '' ?>><?= ucfirst($u) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="form-label">Max Transactions / period (0 = unlimited)</label>
                        <input type="number" name="max_transactions" value="<?php echo htmlspecialchars($fetchdata["max_transactions"] ?? 0); ?>" class="form-control" required>
                    </div>
                    <div>
                        <label class="form-label">Cashier / Merchant Limit</label>
                        <input type="number" name="cashier_limit" value="<?php echo htmlspecialchars($fetchdata["cashier_limit"] ?? 1); ?>" class="form-control" required>
                    </div>
                    <div>
                        <label class="form-label">Static Paylink Limit (0 = unlimited)</label>
                        <input type="number" name="static_paylink_limit" value="<?php echo htmlspecialchars($fetchdata["static_paylink_limit"] ?? 1); ?>" class="form-control" required>
                    </div>
                    <div style="grid-column:1/-1">
                        <label class="check-row">
                            <input type="checkbox" name="is_trial" id="is_trial" value="1" <?= !empty($fetchdata['is_trial']) ? 'checked' : '' ?>>
                            Use as the automatic Trial plan for new signups
                        </label>
                    </div>
                </div>
                <div class="form-actions">
                    <button type="submit" name="updatesub" class="btn-primary-cta"><i class="fas fa-floppy-disk"></i> Save Changes</button>
                    <a href="manage_subscription" class="btn-ghost"><i class="fas fa-xmark"></i> Cancel</a>
                </div>
            </form>
        </div>
    </div>

    <?php else: ?>

    <div class="glass-card" style="margin-bottom:20px">
        <div class="card-header"><h3><i class="fas fa-hand-holding-heart"></i> Grant Plan to a User</h3></div>
        <div class="card-body">
            <p style="font-size:.8rem;color:rgba(255,255,255,.45);margin:0 0 16px">Kisi specific user ko bina payment liye seedha plan de sakte hain - koi existing plan (1 month, 2 month, etc.) ya ek custom one-off plan.</p>
            <form method="POST" action="" id="grantPlanForm">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <div class="form-grid">
                    <div>
                        <label class="form-label">User's Mobile Number</label>
                        <input type="text" name="grant_mobile" class="form-control" placeholder="10-digit mobile" required>
                    </div>
                    <div>
                        <label class="form-label">Grant Type</label>
                        <select class="form-control" id="grantTypeSelect" onchange="
                            document.getElementById('grantExisting').style.display = this.value === 'existing' ? '' : 'none';
                            document.getElementById('grantCustom').style.display = this.value === 'custom' ? '' : 'none';
                        ">
                            <option value="existing" name="grant_type_label">Existing Plan</option>
                            <option value="custom">Custom Plan (one-off)</option>
                        </select>
                        <input type="hidden" name="grant_type" id="grantTypeHidden" value="existing">
                    </div>
                </div>

                <div id="grantExisting" class="form-grid" style="margin-top:14px">
                    <div>
                        <label class="form-label">Choose Plan</label>
                        <select name="grant_plan_id" class="form-control">
                            <?php foreach ($plans as $p): ?>
                                <option value="<?php echo (int)$p['id']; ?>">
                                    <?php echo htmlspecialchars($p['plan_name']); ?> — <?php echo (int)$p['expiry']; ?> <?php echo ucfirst($p['period_type'] ?? 'month'); ?>(s), ₹<?php echo htmlspecialchars($p['amount']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div id="grantCustom" class="form-grid" style="margin-top:14px;display:none">
                    <div>
                        <label class="form-label">Duration (number)</label>
                        <input type="number" name="grant_custom_expiry" class="form-control" value="1" min="1">
                    </div>
                    <div>
                        <label class="form-label">Duration Unit</label>
                        <select name="grant_custom_period" class="form-control">
                            <?php foreach (['day','week','month','year'] as $u): ?>
                                <option value="<?= $u ?>" <?= $u === 'month' ? 'selected' : '' ?>><?= ucfirst($u) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="form-label">Max Transactions (0 = unlimited)</label>
                        <input type="number" name="grant_custom_max_transactions" class="form-control" value="0" min="0">
                    </div>
                    <div>
                        <label class="form-label">Merchant Limit</label>
                        <input type="number" name="grant_custom_cashier_limit" class="form-control" value="1" min="1">
                    </div>
                    <div>
                        <label class="form-label">Static Paylinks (0 = unlimited)</label>
                        <input type="number" name="grant_custom_static_paylink_limit" class="form-control" value="1" min="0">
                    </div>
                </div>

                <div class="form-actions" style="margin-top:16px">
                    <button type="submit" name="grantPlan" class="btn-primary-cta"><i class="fas fa-gift"></i> Grant Plan</button>
                </div>
            </form>
        </div>
    </div>
    <script>
        document.getElementById('grantTypeSelect').addEventListener('change', function(){
            document.getElementById('grantTypeHidden').value = this.value;
        });
    </script>

    <div class="glass-card">
        <div class="card-header">
            <h3><i class="fas fa-list"></i> All Plans</h3>
            <button class="btn-primary-cta" onclick="document.getElementById('addPlanForm').style.display='block'; this.style.display='none';"><i class="fas fa-plus"></i> Add New Plan</button>
        </div>
        <div class="card-body" id="addPlanForm" style="display:none">
            <form method="POST" action="">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <div class="form-grid">
                    <div>
                        <label class="form-label">Plan Name</label>
                        <input type="text" name="plan_name" class="form-control" required>
                    </div>
                    <div>
                        <label class="form-label">Amount (₹)</label>
                        <input type="number" step="0.01" name="amount" class="form-control" required>
                    </div>
                    <div>
                        <label class="form-label">Duration (number)</label>
                        <input type="number" name="expiry" value="1" class="form-control" required>
                    </div>
                    <div>
                        <label class="form-label">Duration Unit</label>
                        <select name="period_type" class="form-control">
                            <option value="day">Day</option>
                            <option value="week">Week</option>
                            <option value="month" selected>Month</option>
                            <option value="year">Year</option>
                        </select>
                    </div>
                    <div>
                        <label class="form-label">Max Transactions / period (0 = unlimited)</label>
                        <input type="number" name="max_transactions" value="0" class="form-control" required>
                    </div>
                    <div>
                        <label class="form-label">Cashier / Merchant Limit</label>
                        <input type="number" name="cashier_limit" value="1" class="form-control" required>
                    </div>
                    <div>
                        <label class="form-label">Static Paylink Limit (0 = unlimited)</label>
                        <input type="number" name="static_paylink_limit" value="1" class="form-control" required>
                    </div>
                    <div style="grid-column:1/-1">
                        <label class="check-row">
                            <input type="checkbox" name="is_trial" id="is_trial_new" value="1">
                            Use as the automatic Trial plan for new signups
                        </label>
                    </div>
                </div>
                <div class="form-actions">
                    <button type="submit" name="addsub" class="btn-primary-cta"><i class="fas fa-circle-plus"></i> Create Plan</button>
                </div>
            </form>
        </div>
    </div>

    <?php
    if (count($plans) === 0):
    ?>
        <div class="glass-card"><div class="card-body">
            <div class="empty-state">
                <i class="fas fa-box-open"></i>
                <h4>No plans yet</h4>
                <p>Click "Add New Plan" above to create your first one.</p>
            </div>
        </div></div>
    <?php else: ?>
    <div class="plans-grid">
        <?php foreach ($plans as $row):
            $isActive = ($row['status'] ?? 'Active') == 'Active';
        ?>
        <div class="plan-card<?= $isActive ? '' : ' inactive' ?>">
            <?php if (!empty($row['is_trial'])): ?><span class="trial-badge">TRIAL</span><?php endif; ?>
            <div class="plan-head">
                <div class="plan-name"><?= htmlspecialchars($row["plan_name"]) ?></div>
                <div class="plan-price">₹<?= number_format($row["amount"]) ?></div>
                <div class="plan-duration"><?= $row["expiry"] ?> <?= ucfirst($row['period_type'] ?? 'month') ?> Plan</div>
            </div>
            <div class="plan-body">
                <div><span>Transactions</span> <b><?= $row['max_transactions'] > 0 ? $row['max_transactions'] : 'Unlimited' ?></b></div>
                <div><span>Cashiers/Merchants</span> <b><?= $row['cashier_limit'] ?? 1 ?></b></div>
                <div><span>Static Paylinks</span> <b><?= ((int)($row['static_paylink_limit'] ?? 1) > 0) ? $row['static_paylink_limit'] : 'Unlimited' ?></b></div>
                <div><span>Status</span> <span class="status-pill <?= $isActive ? 'status-active' : 'status-inactive' ?>"><i class="fas <?= $isActive ? 'fa-circle-check' : 'fa-circle-pause' ?>"></i> <?= $row['status'] ?? 'Active' ?></span></div>
            </div>
            <div class="plan-footer">
                <button onclick="window.location.href = 'manage_subscription?srno=<?= $row["id"] ?>'" class="act-btn act-edit"><i class="fas fa-pen"></i> Edit</button>
                <button onclick="window.location.href = 'manage_subscription?toggle=<?= $row["id"] ?>'" class="act-btn act-toggle"><i class="fas fa-power-off"></i> <?= $isActive ? 'Deactivate' : 'Activate' ?></button>
                <button onclick="Swal.fire({title:'Delete this plan?', icon:'warning', showCancelButton:true, confirmButtonText:'Delete', background:'#14141f', color:'#fff'}).then((r)=>{ if(r.isConfirmed) window.location.href='manage_subscription?delete=<?= $row["id"] ?>'; })" class="act-btn act-del"><i class="fas fa-trash"></i> Delete</button>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
    <?php endif; ?>
</div>

<script src="./assets/vendors/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="assets/js/app.min.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>
</body>
</html>
