<?php
// =====================================================
// INSTALLER INVITE GENERATOR (TENANT BASED)
// Path: /core/installer/invites.php
// =====================================================

require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('manage_installers');

require_once __DIR__ . '/../config/database.php';

$companyId = $_SESSION['company_id'] ?? null;

if (!$companyId) {
    die("Tenant isolation error.");
}

$generatedLink = null;

/* ===============================
   GENERATE NEW INVITE
=================================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_invite'])) {

    $token = bin2hex(random_bytes(16));

    $stmt = $pdo->prepare("
        INSERT INTO installer_invites
        (company_id, token, expires_at, max_uses, uses_count, is_active, created_at)
        VALUES (?, ?, NULL, 999999, 0, 1, NOW())
    ");

    $stmt->execute([$companyId, $token]);

    $generatedLink = "https://edmsolutions.co.za/installers/apply.php?invite=" . $token;
}

/* ===============================
   FETCH EXISTING INVITES
=================================*/
$stmt = $pdo->prepare("
    SELECT id, token, uses_count, max_uses, is_active, created_at
    FROM installer_invites
    WHERE company_id = ?
    ORDER BY created_at DESC
");
$stmt->execute([$companyId]);
$invites = $stmt->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../includes/layout.php';
?>

<div class="page-header" style="display:flex;justify-content:space-between;align-items:center;">
    <div>
        <h2>Installer Invite Links</h2>
        <p class="page-subtitle">Generate and manage installer onboarding links</p>
    </div>

    <form method="POST">
        <button type="submit" name="generate_invite" class="btn btn-primary">
            + Generate Invite Link
        </button>
    </form>
</div>

<?php if ($generatedLink): ?>
    <div class="card-form" style="margin-bottom:20px;">
        <strong>Invite Link Generated:</strong>
        <input type="text" value="<?= htmlspecialchars($generatedLink) ?>" 
               style="width:100%;padding:10px;margin-top:10px;" readonly>
    </div>
<?php endif; ?>

<div class="table-wrap">
    <table>
        <thead>
            <tr>
                <th>Token</th>
                <th>Uses</th>
                <th>Status</th>
                <th>Created</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($invites as $invite): ?>
                <tr>
                    <td>
    <?= htmlspecialchars(substr($invite['token'],0,12)) ?>...
    <button onclick="copyInvite('<?= $invite['token'] ?>')"
            style="margin-left:10px;padding:4px 8px;font-size:12px;border:none;border-radius:6px;background:#f2531e;color:white;cursor:pointer;">
        Copy
    </button>
</td>
                    <td><?= $invite['uses_count'] ?> / <?= $invite['max_uses'] ?></td>
                    <td>
                        <?php if ($invite['is_active']): ?>
                            <span style="color:green;font-weight:600;">Active</span>
                        <?php else: ?>
                            <span style="color:red;font-weight:600;">Inactive</span>
                        <?php endif; ?>
                    </td>
                    <td><?= $invite['created_at'] ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php require_once __DIR__ . '/../includes/layout_footer.php'; ?>

<script>
function copyInvite(token) {
    const link = "https://edmsolutions.co.za/installers/apply.php?invite=" + token;
    navigator.clipboard.writeText(link).then(function() {
        alert("Invite link copied!");
    });
}
</script>