<?php
// ─────────────────────────────────────────────────────────────
//  migrate_auth.php — Run ONCE to add auth tables
//  CLI:     php migrate_auth.php
//  Browser: visit while logged in as admin, then DELETE this file
// ─────────────────────────────────────────────────────────────
require_once __DIR__ . '/lib.php';

$isCli = php_sapi_name() === 'cli';
if (!$isCli && !admin_logged_in()) {
    http_response_code(403); exit('403 Forbidden — run from CLI or while logged in as admin.');
}

$log = [];
$pdo = db();

function mrun(string $label, callable $fn, array &$log): void {
    try { $fn(); $log[] = "✅ $label"; }
    catch (Throwable $e) { $log[] = "⚠️  $label — " . $e->getMessage(); }
}

// 1. bk_users table
mrun('Create bk_users', function() use ($pdo) {
    $pdo->exec("CREATE TABLE IF NOT EXISTS bk_users (
        id                  INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        email               VARCHAR(200) NOT NULL UNIQUE,
        password_hash       VARCHAR(255) NOT NULL,
        email_verified_at   DATETIME     DEFAULT NULL,
        remember_token      VARCHAR(100) DEFAULT NULL,
        reset_token         VARCHAR(100) DEFAULT NULL,
        reset_token_expires DATETIME     DEFAULT NULL,
        created_at          DATETIME     DEFAULT CURRENT_TIMESTAMP,
        updated_at          DATETIME     DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_email (email),
        INDEX idx_reset (reset_token)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
}, $log);

// 2. Add user_id column to bk_customers
mrun('Add user_id to bk_customers', function() use ($pdo) {
    $pdo->exec("ALTER TABLE bk_customers ADD COLUMN IF NOT EXISTS user_id INT UNSIGNED DEFAULT NULL AFTER id");
}, $log);

// 3. Add FK (only if missing)
mrun('Add foreign key fk_customer_user', function() use ($pdo) {
    $exists = $pdo->query("
        SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS
        WHERE CONSTRAINT_SCHEMA = DATABASE()
          AND TABLE_NAME = 'bk_customers'
          AND CONSTRAINT_NAME = 'fk_customer_user'
    ")->fetchColumn();
    if (!$exists) {
        $pdo->exec("ALTER TABLE bk_customers
            ADD CONSTRAINT fk_customer_user
            FOREIGN KEY (user_id) REFERENCES bk_users(id) ON DELETE SET NULL");
    } else {
        throw new RuntimeException('already exists — skipped');
    }
}, $log);

// 4. Link existing customers to any matching bk_users rows (by email)
mrun('Link existing customers → bk_users', function() use ($pdo, &$log) {
    $rows = $pdo->query("
        SELECT u.id AS uid, c.id AS cid
        FROM bk_users u
        JOIN bk_customers c ON c.email = u.email AND c.user_id IS NULL
    ")->fetchAll();
    $n = 0;
    foreach ($rows as $row) {
        $pdo->prepare("UPDATE bk_customers SET user_id = ? WHERE id = ? AND user_id IS NULL")
            ->execute([$row['uid'], $row['cid']]);
        $n++;
    }
    $log[] = "   → Linked $n existing record(s)";
}, $log);

$out = implode("\n", $log) . "\n\nMigration complete. Delete this file.\n";
echo $isCli ? $out : '<pre style="font:14px/1.8 monospace;padding:28px">' . htmlspecialchars($out) . '</pre>';
