<?php
/**
 * TenantIndex
 * Keeps the master DB's `tenant_user_index` table in sync whenever a
 * company admin creates, edits, or removes an employee login inside
 * their own company database. This index is what login.php uses to
 * figure out which company database an email belongs to.
 */
require_once __DIR__ . '/../config/master_database.php';

function tenantIndexAdd(string $email): void
{
    global $pdoMaster;
    if (empty($_SESSION['tenant_id'])) return;
    $stmt = $pdoMaster->prepare(
        "INSERT INTO tenant_user_index (email, tenant_id) VALUES (?, ?)
         ON DUPLICATE KEY UPDATE tenant_id = VALUES(tenant_id)"
    );
    $stmt->execute([$email, $_SESSION['tenant_id']]);
}

function tenantIndexUpdateEmail(string $oldEmail, string $newEmail): void
{
    global $pdoMaster;
    if ($oldEmail === $newEmail) return;
    if (empty($_SESSION['tenant_id'])) return;
    $pdoMaster->prepare("DELETE FROM tenant_user_index WHERE email = ?")->execute([$oldEmail]);
    tenantIndexAdd($newEmail);
}

function tenantIndexRemove(string $email): void
{
    global $pdoMaster;
    $pdoMaster->prepare("DELETE FROM tenant_user_index WHERE email = ?")->execute([$email]);
}
