<?php
declare(strict_types=1);

/**
 * Adds Phase 4 commerce + customer portal tables to an existing crm database.
 * Fresh installs already include this in schema.sql.
 * Run: C:\xampp\php\php.exe sql/migrate_phase4.php
 */
$base = dirname(__DIR__);
require $base . '/app/init.php';

$db = App\Core\Database::instance();
$pdo = $db->pdo();

function phase4TableExists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :t'
    );
    $stmt->execute(['t' => $table]);
    return (int) $stmt->fetchColumn() > 0;
}

$sqlFile = $base . '/sql/schema.sql';
$raw = (string) file_get_contents($sqlFile);
$start = strpos($raw, 'CREATE TABLE IF NOT EXISTS tenant_commerce');
if ($start === false) {
    fwrite(STDERR, "Phase 4 tables missing from schema.sql\n");
    exit(1);
}
$chunk = substr($raw, $start);
$chunk = preg_replace('/SET FOREIGN_KEY_CHECKS = 1;\s*$/', '', $chunk) ?? $chunk;

$pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
foreach (explode(';', $chunk) as $statement) {
    $statement = trim($statement);
    if ($statement === '' || str_starts_with($statement, '--')) {
        continue;
    }
    $pdo->exec($statement);
}
$pdo->exec('SET FOREIGN_KEY_CHECKS = 1');

if (phase4TableExists($pdo, 'quotes')) {
    $count = (int) $pdo->query('SELECT COUNT(*) FROM quotes')->fetchColumn();
    if ($count === 0) {
        $hash = password_hash('Welcome1!', PASSWORD_DEFAULT);
        require $base . '/sql/seed_phase4.php';
    }
}

echo "Phase 4 migrate finished.\n";
