<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('vendor');
$db   = Database::getInstance();
$page = 'License Management';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = post('action');
    $id     = postInt('id');

    if ($action === 'create_organization') {
        $name     = post('name');
        $licensed = postInt('licensed_users') ?: 1;
        $cost     = cleanFloat($_POST['cost_per_user'] ?? 0);
        $username = post('admin_username');
        if (!$name) {
            setFlash('error', 'Organization name is required.');
        } elseif (!$username) {
            setFlash('error', 'An admin username is required — this is the org\'s first login, they can\'t create it themselves.');
        } else {
            $dup = $db->fetchOne("SELECT id FROM users WHERE username=?", [$username]);
            if ($dup) {
                setFlash('error', "Username '$username' is already taken — usernames must be unique across the whole system, not just within one org. Try something more specific, e.g. prefixed with the company name.");
                header('Location: ' . BASE_URL . '/modules/companies/index.php'); exit;
            }
            $db->execute(
                "INSERT INTO organizations (name,licensed_users,cost_per_user,contact_name,contact_phone,contact_email,notes,status) VALUES (?,?,?,?,?,?,?, 'active')",
                [$name, $licensed, $cost, post('contact_name'), post('contact_phone'), post('contact_email'), post('notes')]
            );
            $orgId = $db->fetchValue("SELECT id FROM organizations WHERE name=? ORDER BY id DESC LIMIT 1", [$name]);
            // Every organization needs at least one default Company so its
            // own admin can start creating employees/users straight away.
            // They can rename it or add more Companies from "My Companies".
            // FIX (09 Jul 2026): companies.code is NOT NULL — generate a
            // simple one from the name instead of leaving it blank.
            $autoCode = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', $name), 0, 8)) ?: 'CO' . $orgId;
            $db->execute("INSERT INTO companies (organization_id,name,code) VALUES (?,?,?)", [$orgId, $name, $autoCode]);
            $companyId = $db->fetchValue("SELECT id FROM companies WHERE organization_id=? ORDER BY id DESC LIMIT 1", [$orgId]);

            // FIX (09 Jul 2026): the vendor previously had no way to
            // create the FIRST login for a brand-new organization —
            // User Management is off-limits to the vendor role, and a
            // new org has zero users, so nobody could log in to create
            // one themselves. This closes that gap: the vendor sets a
            // username + temp password right here; that person can then
            // create every other user in their org from User Management.
            $tempPassword = post('admin_password') ?: ('Welcome@' . rand(1000,9999));
            $hash = password_hash($tempPassword, PASSWORD_BCRYPT, ['cost'=>12]);
            $db->execute("INSERT INTO users (username,password_hash,role,company_id,is_active,must_change_password) VALUES (?,?,?,?,1,1)",
                [$username, $hash, 'superadmin', $companyId]);

            $totalCost = number_format($licensed * $cost, 2);
            setFlash('success', "Organization '$name' created with $licensed user license(s) at ₹$cost/user (₹$totalCost total). Admin login ready — username: $username, temporary password: $tempPassword (they'll be asked to change it on first login). Give these credentials to the organization; they can create every other user themselves from User Management.");
        }
    } elseif ($action === 'update_license') {
        $licensed = postInt('licensed_users');
        $cost     = cleanFloat($_POST['cost_per_user'] ?? 0);
        $usage = getLicenseUsage($db, $id);
        if ($licensed < $usage['used']) {
            setFlash('error', "Cannot set limit to $licensed — this organization already has {$usage['used']} active users (across all its companies). Deactivate some first, or set a limit ≥ {$usage['used']}.");
        } else {
            $db->execute("UPDATE organizations SET licensed_users=?,cost_per_user=? WHERE id=?", [$licensed, $cost, $id]);
            setFlash('success', 'License count and pricing updated.');
        }
    } elseif ($action === 'toggle_status') {
        $org = $db->fetchOne("SELECT * FROM organizations WHERE id=?", [$id]);
        $new = $org['status'] === 'active' ? 'suspended' : 'active';
        $db->execute("UPDATE organizations SET status=? WHERE id=?", [$new, $id]);
        setFlash('success', "Organization " . ($new === 'active' ? 'activated' : 'suspended') . ". Every user in every company under it will " . ($new === 'active' ? 'now be able to' : 'no longer be able to') . " log in.");
    } elseif ($action === 'reset_admin_login') {
        // FIX (09 Jul 2026): lets the vendor create or reset an admin
        // login for an EXISTING organization too — e.g. ones created
        // before this feature existed, or if they've locked themselves out.
        $username = post('admin_username');
        $company  = $db->fetchOne("SELECT id FROM companies WHERE organization_id=? ORDER BY id ASC LIMIT 1", [$id]);
        if (!$username) {
            setFlash('error', 'Username is required.');
        } elseif (!$company) {
            setFlash('error', 'This organization has no company yet — create one first (My Companies).');
        } else {
            $tempPassword = post('admin_password') ?: ('Welcome@' . rand(1000,9999));
            $hash = password_hash($tempPassword, PASSWORD_BCRYPT, ['cost'=>12]);
            $existing = $db->fetchOne("SELECT id FROM users WHERE username=?", [$username]);
            if ($existing) {
                // If it's already a user in THIS org, just reset their password.
                $ownedByThisOrg = $db->fetchOne("SELECT u.id FROM users u JOIN companies c ON c.id=u.company_id WHERE u.id=? AND c.organization_id=?", [$existing['id'], $id]);
                if ($ownedByThisOrg) {
                    $db->execute("UPDATE users SET password_hash=?,role='superadmin',is_active=1,must_change_password=1 WHERE id=?", [$hash, $existing['id']]);
                    setFlash('success', "Password reset for '$username'. New temporary password: $tempPassword");
                } else {
                    setFlash('error', "Username '$username' is already taken by a different organization's user.");
                }
            } else {
                $db->execute("INSERT INTO users (username,password_hash,role,company_id,is_active,must_change_password) VALUES (?,?,?,?,1,1)",
                    [$username, $hash, 'superadmin', $company['id']]);
                setFlash('success', "Admin login created — username: $username, temporary password: $tempPassword");
            }
        }
    } elseif ($action === 'delete_organization') {
        // Only allow deleting an organization that has no employees left
        // in any of its companies — prevents accidentally orphaning real
        // HR/payroll data. They must remove/transfer employees first.
        $empCount = (int)$db->fetchValue(
            "SELECT COUNT(*) FROM employees e JOIN companies c ON c.id=e.company_id WHERE c.organization_id=?",
            [$id]
        );
        if ($empCount > 0) {
            setFlash('error', "Can't delete — this organization still has $empCount employee(s) across its companies. Remove them first, or just Suspend the organization instead.");
        } else {
            $db->execute("DELETE FROM companies WHERE organization_id=?", [$id]);
            $db->execute("DELETE FROM organizations WHERE id=?", [$id]);
            setFlash('success', 'Organization deleted.');
        }
    } elseif ($action === 'post_update') {
        $version = post('version');
        $title   = post('title');
        $message = post('message');
        // Optional — only needed if this release actually needs users to
        // download a new APK. Leave blank for a web-only change / an
        // announcement that doesn't require a mobile update.
        $versionCode = postInt('app_version_code');
        $updateUrl   = post('app_update_url');
        if (!$version || !$title || !$message) {
            setFlash('error', 'Version, title and message are all required.');
        } else {
            $db->execute("INSERT INTO product_updates (version,title,message,is_active) VALUES (?,?,?,1)", [$version, $title, $message]);

            $mobileNote = '';
            if ($versionCode > 0) {
                // This is the part that actually drives the mobile app's
                // "Update Available — Update Now" popup (checked via
                // ?action=app_version against BuildConfig.VERSION_CODE).
                // Bumping it here — same click, same form — means every
                // organization's users get the real force-update popup,
                // not just the "what's new" banner.
                $currentCode = (int)($db->fetchValue("SELECT config_value FROM app_config WHERE config_key='latest_version_code'") ?: 0);
                if ($versionCode <= $currentCode) {
                    setFlash('error', "Announcement posted, but app_version_code ($versionCode) must be higher than the current one ($currentCode) — the mobile update popup was NOT triggered. Re-push with a higher number if this release needs users to update their app.");
                    header('Location: ' . BASE_URL . '/modules/companies/index.php'); exit;
                }
                foreach ([
                    'latest_version_code' => (string)$versionCode,
                    'latest_version_name' => $version,
                    'update_message'      => $message,
                    'update_url'          => $updateUrl,
                ] as $k => $v) {
                    $db->execute(
                        "INSERT INTO app_config (config_key,config_value) VALUES (?,?)
                         ON DUPLICATE KEY UPDATE config_value=VALUES(config_value)",
                        [$k, $v]
                    );
                }
                $mobileNote = " The mobile app's Update Now popup will also fire for every organization's users (their installed build is older than version code $versionCode).";
            }
            setFlash('success', "Update v$version posted. Every organization will see it on their next dashboard load (web) and API call (mobile).$mobileNote");
        }
    } elseif ($action === 'deactivate_update') {
        $db->execute("UPDATE product_updates SET is_active=0 WHERE id=?", [$id]);
        setFlash('success', 'Update withdrawn.');
    } elseif ($action === 'create_feature') {
        // Add a new feature to the catalog. Left OFF for everyone by
        // default (unless the vendor explicitly checks "default enabled")
        // — the whole point is usually "give this to ONE org only",
        // which is done separately below via toggle_org_feature.
        $key  = strtolower(preg_replace('/[^a-zA-Z0-9_]/', '_', post('feature_key')));
        $name = post('feature_name');
        $desc = post('feature_description');
        $defaultOn = post('feature_default') ? 1 : 0;
        if (!$key || !$name) {
            setFlash('error', 'Feature key and name are both required.');
        } else {
            $exists = $db->fetchOne("SELECT id FROM feature_flags WHERE feature_key=?", [$key]);
            if ($exists) {
                setFlash('error', "A feature with key '$key' already exists.");
            } else {
                $db->execute(
                    "INSERT INTO feature_flags (feature_key,name,description,is_default_enabled) VALUES (?,?,?,?)",
                    [$key, $name, $desc, $defaultOn]
                );
                setFlash('success', "Feature '$name' created" . ($defaultOn ? ' (on by default for every organization).' : ' — now turn it on for whichever organization(s) should get it.'));
            }
        }
    } elseif ($action === 'delete_feature') {
        $db->execute("DELETE FROM organization_features WHERE feature_key=(SELECT feature_key FROM feature_flags WHERE id=?)", [$id]);
        $db->execute("DELETE FROM feature_flags WHERE id=?", [$id]);
        setFlash('success', 'Feature flag deleted.');
    } elseif ($action === 'toggle_org_feature') {
        // Flip ONE organization's access to ONE feature, e.g. turn a new
        // module on for Company A only, leaving Company B/C untouched.
        $orgId      = postInt('org_id');
        $featureKey = post('feature_key');
        $enable     = postInt('enable');
        $db->execute(
            "INSERT INTO organization_features (organization_id,feature_key,is_enabled) VALUES (?,?,?)
             ON DUPLICATE KEY UPDATE is_enabled=VALUES(is_enabled)",
            [$orgId, $featureKey, $enable]
        );
        // no flash — this is a matrix of small toggles, a full-page
        // banner for every click would be noisy.
    }
    header('Location: ' . BASE_URL . '/modules/companies/index.php'); exit;
}

$organizations = $db->fetchAll("SELECT * FROM organizations ORDER BY name");
foreach ($organizations as &$o) {
    $u = getLicenseUsage($db, $o['id']);
    $o['used']       = $u['used'];
    $o['total_cost'] = $o['licensed_users'] * $o['cost_per_user'];
    $o['companies'] = $db->fetchAll(
        "SELECT c.*, (SELECT COUNT(*) FROM users u WHERE u.company_id=c.id AND u.is_active=1) AS used
           FROM companies c WHERE c.organization_id=? ORDER BY c.name",
        [$o['id']]
    );
}
unset($o);

$updates = $db->fetchAll("SELECT * FROM product_updates ORDER BY id DESC LIMIT 10");

// Current live mobile version code, shown next to the Push Product Update
// form so the vendor knows what number to beat. Null if migration_app_config.sql
// hasn't been run yet — the form below handles that case too.
$curCode = null;
try {
    $curCode = $db->fetchValue("SELECT config_value FROM app_config WHERE config_key='latest_version_code'");
} catch (Throwable $e) {
    $curCode = null;
}

// Feature flags matrix: every feature x every organization's on/off state.
// Wrapped in try/catch so this page doesn't die if migration_feature_flags.sql
// hasn't been run yet — it just shows an empty state with instructions instead.
$features = [];
$orgFeatureMap = [];
$featureMigrationMissing = false;
try {
    $features = $db->fetchAll("SELECT * FROM feature_flags ORDER BY name");
    $orgFeatureRows = $db->fetchAll("SELECT organization_id, feature_key, is_enabled FROM organization_features");
    foreach ($orgFeatureRows as $r) {
        $orgFeatureMap[$r['organization_id']][$r['feature_key']] = (int)$r['is_enabled'];
    }
} catch (Throwable $e) {
    $featureMigrationMissing = true;
}

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">

  <!-- Create Organization -->
  <div class="col-md-4">
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-building-plus me-2"></i>New Organization</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="create_organization">
        <div class="mb-2">
          <label class="pc-label">Organization Name <span class="text-danger">*</span></label>
          <input type="text" name="name" class="form-control form-control-sm" required placeholder="e.g. ABC Company">
        </div>
        <div class="mb-2">
          <label class="pc-label">Licensed Users <span class="text-danger">*</span></label>
          <input type="number" name="licensed_users" class="form-control form-control-sm" min="1" value="100" required>
        </div>
        <div class="mb-2">
          <label class="pc-label">Cost per User (₹/month) <span class="text-danger">*</span></label>
          <input type="number" name="cost_per_user" class="form-control form-control-sm" min="0" step="0.01" value="0" required>
        </div>
        <div class="mb-2">
          <label class="pc-label">Contact Name</label>
          <input type="text" name="contact_name" class="form-control form-control-sm">
        </div>
        <div class="mb-2">
          <label class="pc-label">Contact Phone</label>
          <input type="text" name="contact_phone" class="form-control form-control-sm">
        </div>
        <div class="mb-2">
          <label class="pc-label">Contact Email</label>
          <input type="email" name="contact_email" class="form-control form-control-sm">
        </div>
        <div class="mb-2">
          <label class="pc-label">Notes</label>
          <textarea name="notes" class="form-control form-control-sm" rows="2"></textarea>
        </div>

        <div class="pc-section-divider">First Admin Login</div>
        <div class="alert alert-info py-1 px-2 small mb-2">
          <i class="ti ti-info-circle me-1"></i>This is the org's very first login — they can't create it themselves. They'll use it to create everyone else.
        </div>
        <div class="mb-2">
          <label class="pc-label">Admin Username <span class="text-danger">*</span></label>
          <input type="text" name="admin_username" class="form-control form-control-sm" required placeholder="e.g. abc_admin">
        </div>
        <div class="mb-3">
          <label class="pc-label">Temporary Password (leave blank to auto-generate)</label>
          <input type="text" name="admin_password" class="form-control form-control-sm" placeholder="Auto-generated if left blank">
        </div>

        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-plus me-1"></i>Create Organization</button>
      </form>
      <div class="alert alert-info py-1 px-2 small mt-2 mb-0">
        <i class="ti ti-info-circle me-1"></i>This creates the org + one default company inside it. The organization's own admin can add more companies later (My Companies) — all of them share this one license pool.
      </div>
    </div>

    <!-- Post Product Update -->
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-sparkles me-2"></i>Push Product Update</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="post_update">
        <div class="mb-2">
          <label class="pc-label">Version <span class="text-danger">*</span></label>
          <input type="text" name="version" class="form-control form-control-sm" required placeholder="e.g. 2.4.0">
        </div>
        <div class="mb-2">
          <label class="pc-label">Title <span class="text-danger">*</span></label>
          <input type="text" name="title" class="form-control form-control-sm" required placeholder="e.g. New leave approval flow">
        </div>
        <div class="mb-3">
          <label class="pc-label">Message <span class="text-danger">*</span></label>
          <textarea name="message" class="form-control form-control-sm" rows="3" required placeholder="What changed, in one or two lines"></textarea>
        </div>
        <hr class="my-2">
        <div class="small text-muted mb-1">
          <i class="ti ti-device-mobile me-1"></i>Optional — fill these in ONLY if this release needs users to actually download a new APK. If filled, every organization's mobile users get the real "Update Now" popup, not just the announcement above.
          <?php if ($curCode !== null): ?>
            <div class="mt-1">Current live app version code: <strong><?= (int)$curCode ?></strong> — next push must use a higher number.</div>
          <?php else: ?>
            <div class="mt-1 text-danger">app_config table not found — run migration_app_config.sql first if you want to use this.</div>
          <?php endif; ?>
        </div>
        <div class="mb-2">
          <label class="pc-label">App Version Code</label>
          <input type="number" name="app_version_code" class="form-control form-control-sm" placeholder="e.g. 4 (must be higher than current)">
        </div>
        <div class="mb-3">
          <label class="pc-label">APK Download URL</label>
          <input type="text" name="app_update_url" class="form-control form-control-sm" placeholder="https://.../app-latest.apk">
        </div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-send me-1"></i>Push to All Organizations</button>
      </form>
      <div class="alert alert-warning py-1 px-2 small mt-2 mb-0">
        <i class="ti ti-info-circle me-1"></i>Announcement popup shows on web dashboards and via <code>get_latest_update</code>/<code>dashboard</code> (mobile). If an App Version Code is set, the mobile app's own <code>app_version</code> check also fires, popping the real "Update Now" dialog on every organization's users' phones.
      </div>
    </div>

    <!-- New Feature Flag -->
    <div class="pc-card mt-3">
      <div class="pc-card-title"><i class="ti ti-toggle-right me-2"></i>New Feature Flag</div>
      <?php if ($featureMigrationMissing): ?>
        <div class="alert alert-danger py-2 px-2 small mb-0">
          Feature flags aren't set up yet — run <code>migration_feature_flags.sql</code> against your database, then reload this page.
        </div>
      <?php else: ?>
        <form method="POST">
          <?=csrfField()?><input type="hidden" name="action" value="create_feature">
          <div class="mb-2">
            <label class="pc-label">Feature Key <span class="text-danger">*</span></label>
            <input type="text" name="feature_key" class="form-control form-control-sm" required placeholder="e.g. new_expense_module">
          </div>
          <div class="mb-2">
            <label class="pc-label">Display Name <span class="text-danger">*</span></label>
            <input type="text" name="feature_name" class="form-control form-control-sm" required placeholder="e.g. New Expense Module">
          </div>
          <div class="mb-2">
            <label class="pc-label">Description</label>
            <textarea name="feature_description" class="form-control form-control-sm" rows="2"></textarea>
          </div>
          <div class="form-check mb-2">
            <input type="checkbox" name="feature_default" value="1" class="form-check-input" id="featDefault">
            <label class="form-check-label small" for="featDefault">On by default for every organization (rare — usually leave unchecked and switch it on for just the org(s) that asked)</label>
          </div>
          <button class="btn btn-pc btn-sm w-100"><i class="ti ti-plus me-1"></i>Create Feature Flag</button>
        </form>
      <?php endif; ?>
      <div class="alert alert-info py-1 px-2 small mt-2 mb-0">
        <i class="ti ti-info-circle me-1"></i>After creating it, use the grid on the right to switch it on for one organization (e.g. Company A) without affecting any other organization. Gate the feature in code with <code>hasFeature('your_key')</code> or <code>requireFeature('your_key')</code>.
      </div>
    </div>
  </div>

  <!-- Organizations list -->
  <div class="col-md-8">
    <div class="pc-card mb-3">
      <div class="pc-card-title">Organizations (<?=count($organizations)?>)</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Organization</th><th>Contact</th><th>License Usage (all companies combined)</th><th>Pricing</th><th>Status</th><th>Action</th></tr></thead>
          <tbody>
          <?php foreach ($organizations as $o): ?>
          <tr>
            <td class="fw-semibold">
              <?=clean($o['name'])?>
              <?php if (count($o['companies']) > 1): ?>
              <div class="small text-muted mt-1">
                <?php foreach ($o['companies'] as $c): ?>
                  <div><?=clean($c['name'])?> — <?=$c['used']?> user(s)</div>
                <?php endforeach; ?>
              </div>
              <?php elseif ($o['companies']): ?>
                <div class="small text-muted">Company: <?=clean($o['companies'][0]['name'])?></div>
              <?php endif; ?>
            </td>
            <td class="small text-muted"><?=clean($o['contact_name']??'')?><br><?=clean($o['contact_phone']??'')?></td>
            <td style="min-width:170px">
              <div class="d-flex align-items-center gap-2">
                <div class="pc-progress flex-fill" style="height:8px">
                  <div class="pc-progress-fill" style="width:<?=$o['licensed_users']>0?min(100,round($o['used']/$o['licensed_users']*100)):0?>%;background:<?=$o['used']>=$o['licensed_users']?'var(--pc-red)':'var(--pc-green)'?>"></div>
                </div>
                <span class="small fw-semibold"><?=$o['used']?>/<?=$o['licensed_users']?></span>
              </div>
            </td>
            <td style="min-width:190px">
              <div class="small mb-1">₹<?=number_format($o['cost_per_user'],2)?>/user → <b>₹<?=number_format($o['total_cost'],2)?></b> total</div>
              <form method="POST" class="d-flex gap-1">
                <?=csrfField()?><input type="hidden" name="action" value="update_license"><input type="hidden" name="id" value="<?=$o['id']?>">
                <input type="number" name="licensed_users" value="<?=$o['licensed_users']?>" min="1" class="form-control form-control-sm" style="width:60px" title="Licensed users">
                <input type="number" name="cost_per_user" value="<?=$o['cost_per_user']?>" min="0" step="0.01" class="form-control form-control-sm" style="width:80px" title="Cost per user">
                <button class="btn btn-xs btn-outline-primary py-0 px-2">Update</button>
              </form>
            </td>
            <td><?=statusBadge($o['status'])?></td>
            <td>
              <div class="d-flex gap-1">
                <form method="POST">
                  <?=csrfField()?><input type="hidden" name="action" value="toggle_status"><input type="hidden" name="id" value="<?=$o['id']?>">
                  <button class="btn btn-xs <?=$o['status']==='active'?'btn-outline-warning':'btn-outline-success'?> py-0 px-2" onclick="return confirm('<?=$o['status']==='active'?'Suspend':'Activate'?> <?=clean($o['name'])?>?')">
                    <?=$o['status']==='active'?'Suspend':'Activate'?>
                  </button>
                </form>
                <form method="POST">
                  <?=csrfField()?><input type="hidden" name="action" value="delete_organization"><input type="hidden" name="id" value="<?=$o['id']?>">
                  <button class="btn btn-xs btn-outline-danger py-0 px-2" onclick="return confirm('Permanently delete <?=clean($o['name'])?> and all its companies? This only works if it has no employees left.')">
                    Delete
                  </button>
                </form>
              </div>
              <details class="mt-1">
                <summary class="small text-primary" style="cursor:pointer">Create/Reset Admin Login</summary>
                <form method="POST" class="mt-1 p-2 border rounded" style="min-width:220px">
                  <?=csrfField()?><input type="hidden" name="action" value="reset_admin_login"><input type="hidden" name="id" value="<?=$o['id']?>">
                  <input type="text" name="admin_username" class="form-control form-control-sm mb-1" placeholder="Username" required>
                  <input type="text" name="admin_password" class="form-control form-control-sm mb-1" placeholder="Temp password (blank = auto)">
                  <button class="btn btn-xs btn-outline-primary py-0 px-2 w-100">Save Login</button>
                </form>
              </details>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (!$organizations): ?><tr><td colspan="6" class="text-center text-muted py-3">No organizations yet</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <div class="pc-card">
      <div class="pc-card-title">Recent Product Updates</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Version</th><th>Title</th><th>Message</th><th>Status</th><th>Action</th></tr></thead>
          <tbody>
          <?php foreach ($updates as $u): ?>
          <tr>
            <td>v<?=clean($u['version'])?></td>
            <td class="fw-semibold"><?=clean($u['title'])?></td>
            <td class="small"><?=clean($u['message'])?></td>
            <td><?=$u['is_active']?statusBadge('active'):statusBadge('inactive')?></td>
            <td>
              <?php if ($u['is_active']): ?>
              <form method="POST" onsubmit="return confirm('Withdraw this update banner?')">
                <?=csrfField()?><input type="hidden" name="action" value="deactivate_update"><input type="hidden" name="id" value="<?=$u['id']?>">
                <button class="btn btn-xs btn-outline-secondary py-0 px-2">Withdraw</button>
              </form>
              <?php else: ?>—<?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (!$updates): ?><tr><td colspan="5" class="text-center text-muted py-3">No updates posted yet</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Feature Flags matrix: which organization gets which feature -->
    <div class="pc-card mt-3">
      <div class="pc-card-title"><i class="ti ti-adjustments me-2"></i>Feature Flags — Who Gets What</div>
      <?php if ($featureMigrationMissing): ?>
        <div class="alert alert-danger py-2 px-2 small mb-0">
          Run <code>migration_feature_flags.sql</code> to enable this section.
        </div>
      <?php elseif (!$features): ?>
        <div class="text-center text-muted py-3 small">No feature flags yet — create one on the left.</div>
      <?php else: ?>
        <div class="pc-table-wrap">
          <table class="pc-table">
            <thead>
              <tr>
                <th>Organization</th>
                <?php foreach ($features as $f): ?>
                  <th class="text-center" title="<?=clean($f['description'] ?? '')?>">
                    <?=clean($f['name'])?>
                    <form method="POST" class="d-inline" onsubmit="return confirm('Delete feature &quot;<?=clean($f['name'])?>&quot;? This removes it for every organization.')">
                      <?=csrfField()?><input type="hidden" name="action" value="delete_feature"><input type="hidden" name="id" value="<?=$f['id']?>">
                      <button class="btn btn-link p-0 ms-1 text-danger" style="font-size:10px" title="Delete this flag"><i class="ti ti-trash"></i></button>
                    </form>
                  </th>
                <?php endforeach; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($organizations as $o): ?>
              <tr>
                <td class="fw-semibold"><?=clean($o['name'])?></td>
                <?php foreach ($features as $f): ?>
                  <?php $isOn = $orgFeatureMap[$o['id']][$f['feature_key']] ?? (int)$f['is_default_enabled']; ?>
                  <td class="text-center">
                    <form method="POST">
                      <?=csrfField()?><input type="hidden" name="action" value="toggle_org_feature">
                      <input type="hidden" name="org_id" value="<?=$o['id']?>">
                      <input type="hidden" name="feature_key" value="<?=clean($f['feature_key'])?>">
                      <input type="hidden" name="enable" value="<?=$isOn ? 0 : 1?>">
                      <button class="btn btn-xs <?=$isOn ? 'btn-success' : 'btn-outline-secondary'?> py-0 px-2" title="<?=$isOn ? 'Enabled — click to turn off' : 'Disabled — click to turn on'?> for <?=clean($o['name'])?>">
                        <?=$isOn ? 'ON' : 'OFF'?>
                      </button>
                    </form>
                  </td>
                <?php endforeach; ?>
              </tr>
              <?php endforeach; ?>
              <?php if (!$organizations): ?><tr><td colspan="<?=count($features)+1?>" class="text-center text-muted py-3">No organizations yet</td></tr><?php endif; ?>
            </tbody>
          </table>
        </div>
        <div class="alert alert-info py-1 px-2 small mt-2 mb-0">
          <i class="ti ti-info-circle me-1"></i>Click ON/OFF to flip a feature for that one organization — every other organization is unaffected.
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>