<?php
// Standalone billing migration + seed — visits http://localhost/orchview2/migrate_billing.php
// DELETE this file after running.

function loadEnvVars(string $envFile): array {
    $vars = [];
    if (!file_exists($envFile)) return $vars;
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') continue;
        if (strpos($line, '=') === false) continue;
        [$key, $val] = explode('=', $line, 2);
        $key = trim($key);
        $val = trim($val);
        if ((($val[0] ?? '') === '"' || ($val[0] ?? '') === "'") && $val[0] === substr($val, -1)) {
            $val = substr($val, 1, -1);
        }
        $vars[$key] = $val;
    }
    return $vars;
}

$root = dirname(__DIR__);
$env  = loadEnvVars($root . '/.env');
if (empty($env)) $env = loadEnvVars($root . '/.env.example');

$host = $env['DB_HOST'] ?? 'localhost';
$db   = $env['DB_NAME'] ?? 'orchview2';
$user = $env['DB_USER'] ?? 'root';
$pass = $env['DB_PASSWORD'] ?? '';
$debug= ($env['APP_DEBUG'] ?? 'false') === 'true';

function e(?string $s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$output = [];
try {
    $pdo = new PDO("mysql:host={$host};dbname={$db};charset=utf8mb4", $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);

    $tid = $pdo->query("SELECT tenant_id FROM tenants WHERE deleted_at IS NULL ORDER BY tenant_id LIMIT 1")->fetchColumn();
    if (!$tid) { $output[] = "ERROR: No tenants found."; goto render; }

    // ── ADD BRANDING COLUMNS TO TENANTS ──────────────────────────────
    $cols = $pdo->query("SHOW COLUMNS FROM tenants LIKE 'brand_color_1'")->fetchAll();
    if (empty($cols)) {
        $pdo->exec("ALTER TABLE tenants ADD COLUMN brand_color_1 VARCHAR(7) NULL DEFAULT '#0b2545' AFTER status");
        $output[] = "✓ Added brand_color_1 to tenants";
    } else { $output[] = "- brand_color_1 already exists"; }

    $cols = $pdo->query("SHOW COLUMNS FROM tenants LIKE 'brand_color_2'")->fetchAll();
    if (empty($cols)) {
        $pdo->exec("ALTER TABLE tenants ADD COLUMN brand_color_2 VARCHAR(7) NULL DEFAULT '#1a4d8c' AFTER brand_color_1");
        $output[] = "✓ Added brand_color_2 to tenants";
    } else { $output[] = "- brand_color_2 already exists"; }

    // ── CREATE TABLES ─────────────────────────────────────────────────
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS customers (
            customer_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            tenant_id INT UNSIGNED NOT NULL, name VARCHAR(200) NOT NULL, contact_person VARCHAR(200) NULL,
            email VARCHAR(200) NULL, phone VARCHAR(60) NULL, address TEXT NULL, tax_id VARCHAR(80) NULL,
            notes TEXT NULL, status VARCHAR(20) NOT NULL DEFAULT 'active',
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, deleted_at DATETIME NULL,
            INDEX idx_cust_ts (tenant_id, status), INDEX idx_cust_tn (tenant_id, name),
            FOREIGN KEY (tenant_id) REFERENCES tenants(tenant_id) ON DELETE RESTRICT ON UPDATE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    "); $output[] = "✓ customers";

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS products_services (
            item_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            tenant_id INT UNSIGNED NOT NULL, type VARCHAR(20) NOT NULL, name VARCHAR(200) NOT NULL,
            sku VARCHAR(80) NULL, description TEXT NULL, unit VARCHAR(30) NOT NULL DEFAULT 'ea',
            unit_cost DECIMAL(12,2) NULL, unit_price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            taxable TINYINT(1) NOT NULL DEFAULT 1, tax_rate DECIMAL(5,2) NOT NULL DEFAULT 0.00,
            category VARCHAR(100) NULL, is_active TINYINT(1) NOT NULL DEFAULT 1,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, deleted_at DATETIME NULL,
            INDEX idx_ps_tt (tenant_id, type), INDEX idx_ps_tc (tenant_id, category), INDEX idx_ps_ta (tenant_id, is_active),
            FOREIGN KEY (tenant_id) REFERENCES tenants(tenant_id) ON DELETE RESTRICT ON UPDATE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    "); $output[] = "✓ products_services";

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS quotes (
            quote_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            tenant_id INT UNSIGNED NOT NULL, quote_number VARCHAR(40) NOT NULL, customer_id INT UNSIGNED NOT NULL,
            status VARCHAR(20) NOT NULL DEFAULT 'draft', subtotal DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            discount_percent DECIMAL(5,2) NOT NULL DEFAULT 0.00, discount_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            tax_total DECIMAL(12,2) NOT NULL DEFAULT 0.00, grand_total DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            valid_until DATE NULL, notes TEXT NULL, terms TEXT NULL, created_by INT UNSIGNED NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, deleted_at DATETIME NULL,
            INDEX idx_q_ts (tenant_id, status), UNIQUE INDEX idx_q_tn (tenant_id, quote_number), INDEX idx_q_c (customer_id),
            FOREIGN KEY (tenant_id) REFERENCES tenants(tenant_id) ON DELETE RESTRICT ON UPDATE CASCADE,
            FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE RESTRICT ON UPDATE CASCADE,
            FOREIGN KEY (created_by) REFERENCES users(user_id) ON DELETE SET NULL ON UPDATE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    "); $output[] = "✓ quotes";

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS quote_items (
            quote_item_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            quote_id INT UNSIGNED NOT NULL, item_id INT UNSIGNED NULL, description VARCHAR(300) NOT NULL,
            quantity DECIMAL(10,2) NOT NULL DEFAULT 1.00, unit_price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            discount_percent DECIMAL(5,2) NOT NULL DEFAULT 0.00, line_total DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            sort_order INT NOT NULL DEFAULT 0, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_qi_qs (quote_id, sort_order),
            FOREIGN KEY (quote_id) REFERENCES quotes(quote_id) ON DELETE CASCADE ON UPDATE CASCADE,
            FOREIGN KEY (item_id) REFERENCES products_services(item_id) ON DELETE SET NULL ON UPDATE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    "); $output[] = "✓ quote_items";

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS invoices (
            invoice_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            tenant_id INT UNSIGNED NOT NULL, quote_id INT UNSIGNED NULL, customer_id INT UNSIGNED NOT NULL,
            invoice_number VARCHAR(40) NOT NULL, status VARCHAR(20) NOT NULL DEFAULT 'draft',
            subtotal DECIMAL(12,2) NOT NULL DEFAULT 0.00, discount_percent DECIMAL(5,2) NOT NULL DEFAULT 0.00,
            discount_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00, tax_total DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            grand_total DECIMAL(12,2) NOT NULL DEFAULT 0.00, amount_paid DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            balance_due DECIMAL(12,2) NOT NULL DEFAULT 0.00, due_date DATE NULL,
            notes TEXT NULL, terms TEXT NULL, created_by INT UNSIGNED NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, deleted_at DATETIME NULL,
            INDEX idx_inv_ts (tenant_id, status), UNIQUE INDEX idx_inv_tn (tenant_id, invoice_number),
            INDEX idx_inv_td (tenant_id, due_date), INDEX idx_inv_c (customer_id), INDEX idx_inv_q (quote_id),
            FOREIGN KEY (tenant_id) REFERENCES tenants(tenant_id) ON DELETE RESTRICT ON UPDATE CASCADE,
            FOREIGN KEY (quote_id) REFERENCES quotes(quote_id) ON DELETE SET NULL ON UPDATE CASCADE,
            FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE RESTRICT ON UPDATE CASCADE,
            FOREIGN KEY (created_by) REFERENCES users(user_id) ON DELETE SET NULL ON UPDATE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    "); $output[] = "✓ invoices";

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS invoice_items (
            invoice_item_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            invoice_id INT UNSIGNED NOT NULL, item_id INT UNSIGNED NULL, description VARCHAR(300) NOT NULL,
            quantity DECIMAL(10,2) NOT NULL DEFAULT 1.00, unit_price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            discount_percent DECIMAL(5,2) NOT NULL DEFAULT 0.00, line_total DECIMAL(12,2) NOT NULL DEFAULT 0.00,
            sort_order INT NOT NULL DEFAULT 0, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_ii_is (invoice_id, sort_order),
            FOREIGN KEY (invoice_id) REFERENCES invoices(invoice_id) ON DELETE CASCADE ON UPDATE CASCADE,
            FOREIGN KEY (item_id) REFERENCES products_services(item_id) ON DELETE SET NULL ON UPDATE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    "); $output[] = "✓ invoice_items";

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS payments (
            payment_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            tenant_id INT UNSIGNED NOT NULL, invoice_id INT UNSIGNED NOT NULL,
            amount DECIMAL(12,2) NOT NULL, payment_method VARCHAR(30) NOT NULL DEFAULT 'bank_transfer',
            reference_number VARCHAR(100) NULL, payment_date DATE NOT NULL, notes TEXT NULL,
            created_by INT UNSIGNED NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_pmt_td (tenant_id, payment_date), INDEX idx_pmt_i (invoice_id),
            FOREIGN KEY (tenant_id) REFERENCES tenants(tenant_id) ON DELETE RESTRICT ON UPDATE CASCADE,
            FOREIGN KEY (invoice_id) REFERENCES invoices(invoice_id) ON DELETE CASCADE ON UPDATE CASCADE,
            FOREIGN KEY (created_by) REFERENCES users(user_id) ON DELETE SET NULL ON UPDATE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    "); $output[] = "✓ payments";

    // ── SEED PRODUCTS & SERVICES (Tanzania-focused) ──────────────────
    $existing = (int) $pdo->query("SELECT COUNT(*) FROM products_services WHERE tenant_id = " . (int)$tid)->fetchColumn();
    if ($existing > 0) {
        $output[] = "→ Seed skipped — already {$existing} items.";
    } else {
        $items = [
            // SERVICES (25)
            ['service', 'Annual Plant Inspection', 'SRV-INSP-001', 'Statutory annual inspection of plant equipment & machinery (TBS/EWURA compliant)', 'ea', null, 2500.00, 1, 18.00, 'Inspection'],
            ['service', 'Quarterly Preventative Maintenance', 'SRV-PM-001', 'Quarterly PM for rotating equipment — pumps, compressors, fans', 'ea', null, 1800.00, 1, 18.00, 'Maintenance'],
            ['service', 'Vibration Analysis', 'SRV-VIB-001', 'Vibration monitoring & analysis for critical rotating assets', 'ea', null, 850.00, 1, 18.00, 'Condition Monitoring'],
            ['service', 'Thermography Survey', 'SRV-THM-001', 'Infrared thermography of electrical panels & switchgear', 'ea', null, 1200.00, 1, 18.00, 'Condition Monitoring'],
            ['service', 'Oil Analysis & Lubrication', 'SRV-OIL-001', 'Oil sampling, lab analysis & lubrication for gearboxes', 'ea', null, 450.00, 1, 18.00, 'Condition Monitoring'],
            ['service', 'Pressure Vessel Inspection (TBS)', 'SRV-PVI-001', 'NDT inspection of pressure vessels — TBS certified', 'ea', null, 3200.00, 1, 18.00, 'Inspection'],
            ['service', 'Ultrasonic Thickness Testing', 'SRV-UTT-001', 'UT gauging of pipelines & storage tanks', 'ea', null, 1500.00, 1, 18.00, 'Inspection'],
            ['service', 'Calibration Service', 'SRV-CAL-001', 'On-site calibration of pressure, temp & flow instruments', 'hr', null, 180.00, 1, 18.00, 'Calibration'],
            ['service', 'Emergency Breakdown Repair', 'SRV-BRK-001', '24/7 emergency call-out breakdown repair service', 'hr', null, 250.00, 1, 18.00, 'Repair'],
            ['service', 'Welding & Fabrication', 'SRV-WLD-001', 'On-site welding, cutting & steel fabrication', 'hr', null, 200.00, 1, 18.00, 'Repair'],
            ['service', 'Rigging & Lifting Supervision', 'SRV-RIG-001', 'Certified rigging & lifting operation supervision', 'hr', null, 220.00, 1, 18.00, 'HSE'],
            ['service', 'Confined Space Entry Support', 'SRV-CSE-001', 'Confined space gas testing, standby & rescue team', 'hr', null, 300.00, 1, 18.00, 'HSE'],
            ['service', 'Technical Consulting (Senior Eng.)', 'SRV-CONS-001', 'Senior mech/process engineering consulting — daily rate', 'hr', null, 280.00, 1, 18.00, 'Engineering'],
            ['service', '3D Laser Scanning & Modelling', 'SRV-3DS-001', '3D laser scan of plant & as-built CAD modelling', 'ea', null, 5000.00, 1, 18.00, 'Engineering'],
            ['service', 'Training — Equipment Operator', 'SRV-TRN-001', 'On-site operator training for plant equipment (1-day)', 'ea', null, 950.00, 1, 18.00, 'Training'],
            // Tanzania-specific additions
            ['service', 'Generator Maintenance & Overhaul', 'SRV-GEN-001', 'Diesel generator major & minor service — CAT, Cummins, Perkins, FG Wilson', 'ea', null, 4500.00, 1, 18.00, 'Power Generation'],
            ['service', 'Generator Load Bank Testing', 'SRV-GEN-002', 'Load bank testing & commissioning of standby generators', 'ea', null, 2200.00, 1, 18.00, 'Power Generation'],
            ['service', 'Electrical Maintenance — LV Switchgear', 'SRV-ELEC-001', 'Inspection, testing & servicing of 400V LV switchgear & MCC panels', 'ea', null, 1800.00, 1, 18.00, 'Electrical'],
            ['service', 'Electrical Maintenance — MV Switchgear 11kV', 'SRV-ELEC-002', '11kV MV switchgear maintenance, vacuum CB testing & protection relay testing', 'ea', null, 3500.00, 1, 18.00, 'Electrical'],
            ['service', 'Transformer Oil Testing & Maintenance', 'SRV-ELEC-003', 'Transformer oil sampling, DGA, BDV testing & top-up — Tanesco approved', 'ea', null, 1200.00, 1, 18.00, 'Electrical'],
            ['service', 'Solar PV System Inspection & Cleaning', 'SRV-SOL-001', 'PV panel inspection, IV curve trace, cleaning & inverter diagnostics', 'ea', null, 950.00, 1, 18.00, 'Renewable Energy'],
            ['service', 'Air Compressor Service', 'SRV-COMP-001', 'Screw/recip compressor service — filters, oil, belts, aftercooler cleaning', 'ea', null, 650.00, 1, 18.00, 'Maintenance'],
            ['service', 'HVAC / Chiller Maintenance', 'SRV-HVAC-001', 'Chiller & cooling tower service — refrigerant check, coil cleaning, pump service', 'ea', null, 1100.00, 1, 18.00, 'Facilities'],
            ['service', 'Fire Suppression System Testing', 'SRV-FIRE-001', 'FM200 / CO₂ / wet chemical system hydro test & refill — Fire Dept certified', 'ea', null, 2800.00, 1, 18.00, 'HSE'],
            ['service', 'Water Treatment & Chemical Dosing', 'SRV-WTR-001', 'Boiler/cooling water chemical treatment, legionella testing & dosing pump setup', 'ea', null, 750.00, 1, 18.00, 'Facilities'],
            // PRODUCTS / SPARE PARTS (15)
            ['product', 'Mechanical Seal Kit (Centrifugal Pump)', 'PRT-SEAL-001', 'Standard mechanical seal kit — carbon/ceramic, EPDM elastomer', 'set', 320.00, 550.00, 1, 18.00, 'Spare Parts'],
            ['product', 'Bearing — Deep Groove Ball 6309-2RS', 'PRT-BRG-001', 'SKF/NTN deep groove ball bearing 6309-2RS sealed', 'ea', 85.00, 150.00, 1, 18.00, 'Spare Parts'],
            ['product', 'Bearing — Spherical Roller 22220EK', 'PRT-BRG-002', 'Spherical roller bearing tapered bore — heavy-duty shafts', 'ea', 450.00, 780.00, 1, 18.00, 'Spare Parts'],
            ['product', 'V-Belt Set — SPB Section (matched)', 'PRT-BLT-001', 'Matched set 4× SPB V-belts for industrial drives', 'set', 180.00, 320.00, 1, 18.00, 'Spare Parts'],
            ['product', 'Hydraulic Hose Assembly 1/2" R2', 'PRT-HOS-001', '1/2" R2 two-wire braided hose with JIC fittings', 'ea', 55.00, 95.00, 1, 18.00, 'Spare Parts'],
            ['product', 'Filter Element — Oil (10 micron)', 'PRT-FLT-001', '10-micron hydraulic/gear oil filter — cellulose', 'ea', 28.00, 48.00, 1, 18.00, 'Spare Parts'],
            ['product', 'Gasket — Spiral Wound 6" Class 150', 'PRT-GSK-001', 'SS316/graphite spiral wound gasket ASME B16.20', 'ea', 12.00, 22.00, 1, 18.00, 'Spare Parts'],
            ['product', 'Pressure Gauge 0-160 bar (glycerine)', 'PRT-GAU-001', '0–160 bar glycerine-filled gauge, 100mm dial, 1/2" BSP', 'ea', 42.00, 75.00, 1, 18.00, 'Instrumentation'],
            ['product', 'RTD Temperature Sensor PT100', 'PRT-RTD-001', 'PT100 RTD probe with 4-20mA transmitter, 6mm × 250mm', 'ea', 65.00, 110.00, 1, 18.00, 'Instrumentation'],
            ['product', 'Safety Relief Valve 1" Class 300', 'PRT-SRV-001', '1" spring-loaded SRV, cast steel, set pressure tested', 'ea', 380.00, 650.00, 1, 18.00, 'Spare Parts'],
            ['product', 'Lubricating Oil — ISO VG 68 (20L pail)', 'PRT-OIL-001', 'Premium ISO VG 68 mineral gear/turbine oil — 20L', 'pkt', 55.00, 95.00, 1, 18.00, 'Consumables'],
            ['product', 'Pipe — Sch 40 Carbon Steel 2" × 6m', 'PRT-PIP-001', 'CS seamless pipe 2" NB × SCH40 × 6 metres', 'ea', 120.00, 210.00, 1, 18.00, 'Spare Parts'],
            ['product', 'Flange — Weld Neck 2" Class 150 RF', 'PRT-FLG-001', 'CS weld neck flange 2" Class 150 raised face', 'ea', 18.00, 32.00, 1, 18.00, 'Spare Parts'],
            ['product', 'Electric Motor 15kW 4-Pole IE3', 'PRT-MOT-001', '15kW 4-pole TEFC squirrel cage, IE3, B3 foot mount', 'ea', 1800.00, 2900.00, 1, 18.00, 'Spare Parts'],
            ['product', 'LED Flood Light 200W IP65', 'PRT-LED-001', '200W LED flood light, 5000K daylight, IP65, die-cast aluminium', 'ea', 95.00, 165.00, 1, 18.00, 'Consumables'],
        ];

        $stmt = $pdo->prepare("INSERT INTO products_services (tenant_id, type, name, sku, description, unit, unit_cost, unit_price, taxable, tax_rate, category, is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?,1)");
        $count = 0;
        foreach ($items as $row) {
            $stmt->execute([$tid, $row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $row[7], $row[8], $row[9]]);
            $count++;
        }
        $output[] = "✓ Seeded {$count} products & services";
    }

    // ── SEED CUSTOMERS ────────────────────────────────────────────────
    $custCount = (int) $pdo->query("SELECT COUNT(*) FROM customers WHERE tenant_id = " . (int)$tid)->fetchColumn();
    if ($custCount > 0) {
        $output[] = "→ Customers skipped — already {$custCount} records.";
    } else {
        $customers = [
            ['Tanzania Breweries Ltd', 'James Mwakyusa', 'james.mwakyusa@tbl.co.tz', '+255 754 100 200', 'Plot 1, Nyerere Road, Dar es Salaam', '110-123456'],
            ['TPC Sugar Company Ltd', 'Anna Kileo', 'anna.kileo@tpc.co.tz', '+255 787 300 400', 'Moshi, Kilimanjaro Region', '109-234567'],
            ['Twiga Cement (Heidelberg)', 'David Shayo', 'd.shayo@twigacement.co.tz', '+255 712 500 600', 'Wazo Hill, Dar es Salaam', '101-345678'],
            ['Songas Ubungo Power Plant', 'Fatma Abdallah', 'fatma@songas.co.tz', '+255 768 700 800', 'Ubungo, Dar es Salaam', '107-456789'],
            ['Lake Oil Tanzania Ltd', 'Peter Mushi', 'peter@lakeoil.co.tz', '+255 715 900 100', 'Mafinga, Iringa Region', '104-567890'],
        ];
        $stmt = $pdo->prepare("INSERT INTO customers (tenant_id, name, contact_person, email, phone, address, tax_id, status) VALUES (?,?,?,?,?,?,?,'active')");
        foreach ($customers as $c) $stmt->execute([$tid, $c[0], $c[1], $c[2], $c[3], $c[4], $c[5]]);
        $output[] = "✓ Seeded 5 sample customers";
    }

    $output[] = ""; $output[] = "✓ ALL DONE. DELETE this file after confirming.";

} catch (\Throwable $e) {
    $output[] = "ERROR: " . $e->getMessage();
    if ($debug) $output[] = $e->getTraceAsString();
}

render:
?><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Billing Migration</title>
<style>body{font-family:system-ui,sans-serif;background:#0b2545;color:#e2e8f0;padding:2rem}h2{color:#22c55e}.err{color:#ef4444}</style></head>
<body><h2>Billing Migration & Seed</h2><pre><?php foreach ($output as $line) echo e($line)."\n"; ?></pre></body></html>