<?php
require_once __DIR__ . '/../config/master_database.php';
session_start();
if (empty($_SESSION['super_admin_id'])) { header('Location: login.php'); exit; }

$companies = $pdoMaster->query("SELECT * FROM tenants ORDER BY id ASC")->fetchAll();
$results = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $migrationSql = file_get_contents(__DIR__ . '/../migration_tenant_add_license_session.sql');
    // Strip comment-only lines, keep statements
    $statements = array_filter(array_map('trim', explode(';', $migrationSql)), function ($s) {
        return $s !== '' && strpos($s, '--') !== 0;
    });

    foreach ($companies as $c) {
        try {
            $tenantPdo = new PDO(
                "mysql:host=" . $c['db_host'] . ";dbname=" . $c['db_name'] . ";charset=utf8mb4",
                $c['db_user'], $c['db_pass'],
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
            foreach ($statements as $stmt) {
                if (trim($stmt) === '') continue;
                $tenantPdo->exec($stmt);
            }
            // Sync license_count from master into the tenant's own settings row too
            $tenantPdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'license_count'")
                ->execute([$c['license_count']]);
            $tenantPdo->prepare("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES ('license_count', ?)")
                ->execute([$c['license_count']]);
            $results[] = ['company' => $c['company_name'], 'ok' => true, 'msg' => 'Migrated successfully.'];
        } catch (Exception $e) {
            $results[] = ['company' => $c['company_name'], 'ok' => false, 'msg' => $e->getMessage()];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Run Migration - Super Admin</title>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../assets/css/style.css?v=5">
</head>
<body style="padding:40px;max-width:700px;margin:0 auto;">
    <h2 style="font-family:var(--font-display);">Run License/Single-Device-Login Migration</h2>
    <p><a href="dashboard.php">&larr; Back to companies list</a></p>

    <?php if (!$results): ?>
        <p>This will run <code>migration_tenant_add_license_session.sql</code> against all <?= count($companies) ?> existing company databases. It only adds columns/settings — it does not touch any existing data, and is safe to run more than once.</p>
        <form method="POST">
            <button type="submit" class="btn btn-primary">Run Now on All <?= count($companies) ?> Companies</button>
        </form>
    <?php else: ?>
        <ul>
        <?php foreach ($results as $r): ?>
            <li style="color:<?= $r['ok'] ? 'green' : 'red' ?>;">
                <strong><?= htmlspecialchars($r['company']) ?>:</strong> <?= htmlspecialchars($r['msg']) ?>
            </li>
        <?php endforeach; ?>
        </ul>
    <?php endif; ?>
</body>
</html>
