beginTransaction(); // 1. Clear corrupted data tables $db->exec("SET FOREIGN_KEY_CHECKS = 0"); $db->exec("TRUNCATE TABLE user_company_assignments"); $db->exec("TRUNCATE TABLE invoices"); $db->exec("TRUNCATE TABLE companies"); $db->exec("SET FOREIGN_KEY_CHECKS = 1"); echo "[OK] Cleared companies, invoices, and assignments.\n"; // 2. Ensure Super Admin does not have a tenant_id (if your schema allows NULL, else set to empty string) // Actually, schema.sql says tenant_id CHAR(36) NOT NULL. // This is a flaw in schema.sql for Super Admins. We will leave users alone for now. // 3. Fix the admin's tenant_id to match the first available tenant $stmt = $db->query("SELECT id FROM tenants LIMIT 1"); $tenantId = $stmt->fetchColumn(); if ($tenantId) { $db->exec("UPDATE users SET tenant_id = '$tenantId' WHERE role != 'super_admin'"); echo "[OK] Linked all non-super-admin users to Tenant ID: $tenantId\n"; } $db->commit(); echo "--- Reset Complete ---\n"; } catch (\Exception $e) { $db->rollBack(); echo "[ERROR] Reset failed: " . $e->getMessage() . "\n"; }