<?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 = [];

function loadStatements(string $file): array {
    $sql = file_get_contents($file);
    // Strip whole-line comments first (line-by-line, so a comment line never
    // eats into the SQL that follows it), THEN split what's left on ';'.
    $cleanLines = array_filter(
        explode("\n", $sql),
        function ($line) { return strpos(trim($line), '--') !== 0; }
    );
    $cleanSql = implode("\n", $cleanLines);
    return array_values(array_filter(array_map('trim', explode(';', $cleanSql)), function ($s) {
        return $s !== '';
    }));
}

function runStatementsResilient(PDO $pdo, array $statements, array &$warnings): void {
    foreach ($statements as $stmt) {
        try {
            $pdo->exec($stmt);
        } catch (Exception $e) {
            // A statement failing here is expected on a second run for a few
            // "drop the old index" / "add the new index" style statements -
            // record it as a warning but keep going with the rest.
            $warnings[] = substr(preg_replace('/\s+/', ' ', $stmt), 0, 80) . '... -> ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $licenseSessionStatements = loadStatements(__DIR__ . '/../migration_tenant_add_license_session.sql');
    $accountsFullStatements    = loadStatements(__DIR__ . '/../migration_tenant_add_accounts_module.sql');
    $accountsLimitedStatements = loadStatements(__DIR__ . '/../migration_tenant_add_accounts_module_limited.sql');

    foreach ($companies as $c) {
        $warnings = [];
        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]
            );

            runStatementsResilient($tenantPdo, $licenseSessionStatements, $warnings);

            // Accounts & Finance module tables - pick the right set for this
            // company's edition (Full Edition also gets Item Configuration tables).
            $accountsStatements = $c['edition'] === 'limited' ? $accountsLimitedStatements : $accountsFullStatements;
            runStatementsResilient($tenantPdo, $accountsStatements, $warnings);

            // 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']]);

            $msg = 'Migrated successfully (license/session + accounts module).';
            if ($warnings) {
                $msg .= ' ' . count($warnings) . ' statement(s) skipped (usually normal on a re-run): ' . implode(' | ', $warnings);
            }
            $results[] = ['company' => $c['company_name'], 'ok' => true, 'msg' => $msg];
        } catch (Exception $e) {
            $results[] = ['company' => $c['company_name'], 'ok' => false, 'msg' => 'Could not connect / fatal error: ' . $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 Database Migrations on All Companies</h2>
    <p><a href="dashboard.php">&larr; Back to companies list</a></p>

    <?php if (!$results): ?>
        <p>This will run, against all <?= count($companies) ?> existing company databases:</p>
        <ul>
            <li><code>migration_tenant_add_license_session.sql</code> — license + single-device-login columns</li>
            <li><code>migration_tenant_add_accounts_module.sql</code> (Full Edition) or <code>migration_tenant_add_accounts_module_limited.sql</code> (Limited Edition) — Accounts &amp; Finance module tables (Bank Accounts, Expenses, Salaries, Journal Entries)</li>
        </ul>
        <p>All of these only add tables/columns — none of your existing data is touched, and it's 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>