<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/inc/auth.php';
require_once __DIR__ . '/inc/master_db.php';
require_once __DIR__ . '/inc/csrf.php';
require_once dirname(__DIR__) . '/lib/SubscriptionManager.php';

$active_nav = 'plans';
$masterConn = get_master_connection();
$subMgr     = new SubscriptionManager($masterConn);

// Handle POST: Update Plan
// Handle POST Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? '';

    if ($action === 'create_plan') {
        $priceTermly      = (float)($_POST['price_termly'] ?? $_POST['price_monthly'] ?? 0);
        $priceSessionally = (float)($_POST['price_sessionally'] ?? $_POST['price_annually'] ?? 0);

        $result = $subMgr->createPlan([
            'name'                  => trim($_POST['name'] ?? ''),
            'slug'                  => trim($_POST['slug'] ?? ''),
            'price_termly'          => $priceTermly,
            'price_sessionally'     => $priceSessionally,
            'price_monthly'         => $priceTermly,
            'price_annually'        => $priceSessionally,
            'max_students'          => (int)($_POST['max_students'] ?? 500),
            'max_staff'             => (int)($_POST['max_staff'] ?? 25),
            'feature_cbt'           => !empty($_POST['feature_cbt']),
            'feature_sms'           => !empty($_POST['feature_sms']),
            'feature_finance'       => !empty($_POST['feature_finance']),
            'feature_custom_domain' => !empty($_POST['feature_custom_domain']),
            'is_active'             => isset($_POST['is_active']) ? 1 : 0,
        ]);

        if ($result['success']) {
            set_admin_flash('success', $result['message']);
        } else {
            set_admin_flash('error', $result['message']);
        }
    } elseif ($action === 'update_plan') {
        $planId           = (int)($_POST['plan_id'] ?? 0);
        $name             = trim($_POST['name'] ?? '');
        $priceTermly      = max(0, (float)($_POST['price_termly'] ?? $_POST['price_monthly'] ?? 0));
        $priceSessionally = max(0, (float)($_POST['price_sessionally'] ?? $_POST['price_annually'] ?? 0));
        $maxStudents      = max(1, (int)($_POST['max_students'] ?? 500));
        $maxStaff         = max(1, (int)($_POST['max_staff'] ?? 25));

        if ($planId <= 0 || empty($name)) {
            set_admin_flash('error', 'Plan ID and display name are required.');
        } else {
            $ok = $subMgr->updatePlan($planId, [
                'name'                  => $name,
                'price_termly'          => $priceTermly,
                'price_sessionally'     => $priceSessionally,
                'price_monthly'         => $priceTermly,
                'price_annually'        => $priceSessionally,
                'max_students'          => $maxStudents,
                'max_staff'             => $maxStaff,
                'feature_cbt'           => !empty($_POST['feature_cbt']),
                'feature_sms'           => !empty($_POST['feature_sms']),
                'feature_finance'       => !empty($_POST['feature_finance']),
                'feature_custom_domain' => !empty($_POST['feature_custom_domain']),
                'is_active'             => isset($_POST['is_active']) ? 1 : 0,
            ]);

            if ($ok) {
                set_admin_flash('success', "Subscription plan '{$name}' updated successfully.");
            } else {
                set_admin_flash('error', 'Failed to update plan. Please verify inputs.');
            }
        }
    } elseif ($action === 'delete_plan') {
        $planId = (int)($_POST['plan_id'] ?? 0);
        $result = $subMgr->deletePlan($planId);
        if ($result['success']) {
            set_admin_flash('success', $result['message']);
        } else {
            set_admin_flash('error', $result['message']);
        }
    }

    header('Location: plans.php');
    exit();
}

$plans = $subMgr->getPlans(false);

// Query subscriber counts per plan
$subscriberCounts = [];
$countsRes = mysqli_query($masterConn, "SELECT plan_id, COUNT(*) AS n FROM tenants WHERE plan_id IS NOT NULL GROUP BY plan_id");
if ($countsRes) {
    while ($r = mysqli_fetch_assoc($countsRes)) {
        $subscriberCounts[(int)$r['plan_id']] = (int)$r['n'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Plans & Pricing — EdumacFlo Admin</title>
    <link rel="stylesheet" href="assets/admin.css">
    <style>
        .plan-editor-card {
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 24px;
            display: flex;
            flex-direction: column;
            transition: border-color var(--transition), transform var(--transition);
        }
        .plan-editor-card:hover {
            border-color: rgba(255, 255, 255, 0.16);
        }
        .plan-editor-card h3 {
            font-size: 1.15rem;
            color: #fff;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-bottom: 12px;
            border-bottom: 1px solid var(--border-light);
        }
    </style>
</head>
<body>
<div class="admin-wrapper">

    <?php include __DIR__ . '/inc/sidebar.php'; ?>

    <main class="admin-main">
        <div class="admin-topbar">
            <div style="display:flex;align-items:center;gap:12px">
                <button type="button" class="mobile-nav-toggle" onclick="toggleSidebar()">☰</button>
                <div>
                    <h2>Subscription Plans & Pricing Tiers</h2>
                    <div class="topbar-meta">Configure student quotas, termly/sessionally pricing, and module entitlements</div>
                </div>
            </div>
            <div class="topbar-actions">
                <button type="button" class="btn btn-primary" onclick="openModal('createPlanModal')">
                    <svg width="15" height="15" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path d="M12 4v16m8-8H4"/>
                    </svg>
                    Create New Plan
                </button>
            </div>
        </div>

        <div class="admin-content">
            <div class="admin-container">

                <?= render_admin_flash() ?>

                <div class="plans-admin-grid">
                    <?php foreach ($plans as $p): ?>
                        <?php 
                        $f = $p['features_array']; 
                        $subs = $subscriberCounts[$p['id']] ?? 0;
                        ?>
                        <div class="plan-editor-card">
                            <form method="POST">
                                <?= csrf_field() ?>
                                <input type="hidden" name="action" value="update_plan">
                                <input type="hidden" name="plan_id" value="<?= $p['id'] ?>">

                                <h3>
                                    <div>
                                        <span><?= htmlspecialchars($p['name']) ?></span>
                                        <div style="font-size:0.75rem;font-weight:400;color:var(--text-muted);margin-top:4px">
                                            <?= $subs > 0 ? "<span style='color:var(--green)'>🏫 {$subs} Subscribed School" . ($subs > 1 ? 's' : '') . "</span>" : "<span style='color:var(--text-muted)'>No active subscribers</span>" ?>
                                        </div>
                                    </div>
                                    <span class="badge badge-<?= htmlspecialchars($p['slug']) ?>"><?= strtoupper($p['slug']) ?></span>
                                </h3>

                                <div class="form-group mb-4">
                                    <label>Plan Display Name</label>
                                    <input type="text" name="name" value="<?= htmlspecialchars($p['name']) ?>" required>
                                </div>

                                <div class="form-grid mb-4">
                                    <div class="form-group">
                                        <label>Termly (₦) <small style="color:var(--text-muted)">Per Term</small></label>
                                        <input type="number" step="0.01" name="price_termly" value="<?= $p['price_termly'] ?: $p['price_monthly'] ?>" required>
                                    </div>
                                    <div class="form-group">
                                        <label>Sessionally (₦) <small style="color:var(--text-muted)">Full Session / Year</small></label>
                                        <input type="number" step="0.01" name="price_sessionally" value="<?= $p['price_sessionally'] ?: $p['price_annually'] ?>" required>
                                    </div>
                                </div>

                                <div class="form-grid mb-4">
                                    <div class="form-group">
                                        <label>Max Students</label>
                                        <input type="number" name="max_students" value="<?= $p['max_students'] ?>" required>
                                    </div>
                                    <div class="form-group">
                                        <label>Max Staff</label>
                                        <input type="number" name="max_staff" value="<?= (int)($f['max_staff'] ?? 25) ?>" required>
                                    </div>
                                </div>

                                <div style="margin-bottom:18px">
                                    <label style="display:block;margin-bottom:10px">Included Module Features</label>

                                    <label class="checkbox-label" style="margin-bottom:8px">
                                        <input type="checkbox" name="feature_cbt" value="1" <?= !empty($f['cbt']) ? 'checked' : '' ?>>
                                        <span>Computer-Based Testing (CBT Engine)</span>
                                    </label>

                                    <label class="checkbox-label" style="margin-bottom:8px">
                                        <input type="checkbox" name="feature_sms" value="1" <?= !empty($f['sms']) ? 'checked' : '' ?>>
                                        <span>SMS & WhatsApp Notifications</span>
                                    </label>

                                    <label class="checkbox-label" style="margin-bottom:8px">
                                        <input type="checkbox" name="feature_finance" value="1" <?= !empty($f['finance']) ? 'checked' : '' ?>>
                                        <span>Fee Collection & Accounting</span>
                                    </label>

                                    <label class="checkbox-label" style="margin-bottom:8px">
                                        <input type="checkbox" name="feature_custom_domain" value="1" <?= !empty($f['custom_domain']) ? 'checked' : '' ?>>
                                        <span>Custom Domain & SSL Mapping</span>
                                    </label>
                                </div>

                                <div style="margin-bottom:20px">
                                    <label class="checkbox-label">
                                        <input type="checkbox" name="is_active" value="1" <?= $p['is_active'] ? 'checked' : '' ?>>
                                        <span style="font-weight:600">Active & Available for Schools</span>
                                    </label>
                                </div>

                                <div class="gap-2">
                                    <button type="submit" class="btn btn-primary" style="flex:1">
                                        Save Plan Changes
                                    </button>
                                </div>
                            </form>

                            <?php if ($subs === 0): ?>
                                <form method="POST" style="margin-top:10px;text-align:right">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="delete_plan">
                                    <input type="hidden" name="plan_id" value="<?= $p['id'] ?>">
                                    <button type="submit" class="btn btn-danger btn-xs" onclick="return confirm('Permanently delete unassigned plan <?= htmlspecialchars($p['name']) ?>?')">
                                        Delete Plan
                                    </button>
                                </form>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>

            </div><!-- /admin-container -->
        </div><!-- /admin-content -->
    </main>
</div>

<!-- Modal: Create New Plan -->
<div class="modal" id="createPlanModal">
    <div class="modal-card">
        <div class="modal-header">
            <h3>Create New Subscription Tier</h3>
            <button type="button" class="modal-close" onclick="closeModal('createPlanModal')">&times;</button>
        </div>
        <form method="POST">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="create_plan">

            <div class="form-group mb-4">
                <label>Plan Display Name</label>
                <input type="text" name="name" id="new_plan_name" placeholder="e.g. Premium Academy Tier" required oninput="autoSlugPlan(this.value)">
            </div>

            <div class="form-group mb-4">
                <label>Identifier Slug</label>
                <input type="text" name="slug" id="new_plan_slug" placeholder="e.g. premium-academy" pattern="[a-z0-9\-]+" required>
                <span class="text-muted" style="font-size:0.75rem">Unique identifier used for badges and billing references (lowercase, numbers, hyphens).</span>
            </div>

            <div class="form-grid mb-4">
                <div class="form-group">
                    <label>Termly Price (₦) <small style="color:var(--text-muted)">Per Term</small></label>
                    <input type="number" step="0.01" name="price_termly" placeholder="50000.00" required>
                </div>
                <div class="form-group">
                    <label>Sessionally Price (₦) <small style="color:var(--text-muted)">Per Academic Session / Year</small></label>
                    <input type="number" step="0.01" name="price_sessionally" placeholder="150000.00" required>
                </div>
            </div>

            <div class="form-grid mb-4">
                <div class="form-group">
                    <label>Max Students Quota</label>
                    <input type="number" name="max_students" placeholder="1200" required>
                </div>
                <div class="form-group">
                    <label>Max Staff Quota</label>
                    <input type="number" name="max_staff" placeholder="50" required>
                </div>
            </div>

            <div style="margin-bottom:18px">
                <label style="display:block;margin-bottom:10px">Included Module Features</label>

                <label class="checkbox-label" style="margin-bottom:8px">
                    <input type="checkbox" name="feature_cbt" value="1" checked>
                    <span>Computer-Based Testing (CBT Engine)</span>
                </label>

                <label class="checkbox-label" style="margin-bottom:8px">
                    <input type="checkbox" name="feature_sms" value="1" checked>
                    <span>SMS & WhatsApp Notifications</span>
                </label>

                <label class="checkbox-label" style="margin-bottom:8px">
                    <input type="checkbox" name="feature_finance" value="1" checked>
                    <span>Fee Collection & Accounting</span>
                </label>

                <label class="checkbox-label" style="margin-bottom:8px">
                    <input type="checkbox" name="feature_custom_domain" value="1" checked>
                    <span>Custom Domain & SSL Mapping</span>
                </label>
            </div>

            <div style="margin-bottom:20px">
                <label class="checkbox-label">
                    <input type="checkbox" name="is_active" value="1" checked>
                    <span style="font-weight:600">Active & Immediately Available for Subscriptions</span>
                </label>
            </div>

            <div class="gap-2 mt-4" style="justify-content:flex-end">
                <button type="button" class="btn btn-ghost" onclick="closeModal('createPlanModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Create Subscription Tier</button>
            </div>
        </form>
    </div>
</div>

<script src="assets/admin.js"></script>
<script>
function autoSlugPlan(val) {
    const slugInput = document.getElementById('new_plan_slug');
    if (!slugInput || slugInput.dataset.manual) return;
    slugInput.value = val.toLowerCase().trim()
        .replace(/[^a-z0-9\s-]/g, '')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-');
}
document.getElementById('new_plan_slug')?.addEventListener('input', function() {
    this.dataset.manual = '1';
});
</script>
</body>
</html>

