<?php
/**
 * JUSTSALE POS — Finish Update / Database Schema Sync
 * Supports all versions from 0.0.0 up to the current SYSTEM_VERSION.
 * SECURITY: Delete this file from your server after a successful migration.
 *
 * NOTE: We do NOT include api/db.php here because it loads license_check_middleware.php
 * which calls exit() and kills the migration mid-run. We replicate the connection
 * logic directly to stay completely independent of the middleware chain.
 */

ob_start();
session_start();

// ── Auth guard ───────────────────────────────────────────────────────────────
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'Admin') {
    ob_end_clean();
    header('Location: login');
    exit;
}

// ── Direct DB connection (mirrors api/db.php host-detection, no middleware) ──
define('SYSTEM_VERSION', '3.0.0');

$_isLocal = false;
if (PHP_SAPI === 'cli' || !isset($_SERVER['SERVER_NAME'])) {
    $_isLocal = true;
} else {
    $_srv = $_SERVER['SERVER_NAME'];
    if ($_srv === 'localhost' || $_srv === '127.0.0.1'
        || strpos($_srv, '192.168.') === 0
        || strpos($_srv, '10.')       === 0
        || strpos($_srv, '172.')      === 0) {
        $_isLocal = true;
    }
}

if ($_isLocal) {
    $_dbHost = 'localhost';
    $_dbName = 'justsale_pos';
    $_dbUser = 'root';
    $_dbPass = '';
} else {
    $_dbHost = 'localhost';
    $_dbName = 'u709820750_justsale_sync';
    $_dbUser = 'u709820750_justsale_sync';
    $_dbPass = 'Bib@2012aa++';
}

$dbname = $_dbName; // keep $dbname available for helpers

try {
    $pdo = new PDO("mysql:host={$_dbHost};dbname={$_dbName};charset=utf8", $_dbUser, $_dbPass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    ob_end_clean();
    die('<div style="font-family:sans-serif;padding:40px;color:#ef4444"><h2>Database Connection Failed</h2><p>' . htmlspecialchars($e->getMessage()) . '</p></div>');
}

$adminName = $_SESSION['fullname'] ?? $_SESSION['username'] ?? 'Admin';

// ── Helper: check if a column exists ─────────────────────────────────────────
function columnExists(PDO $pdo, string $table, string $column): bool {
    global $dbname;
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?");
    $stmt->execute([$dbname, $table, $column]);
    return (bool) $stmt->fetchColumn();
}

// ── Helper: check if an index exists ─────────────────────────────────────────
function indexExists(PDO $pdo, string $table, string $indexName): bool {
    $stmt = $pdo->prepare("SHOW INDEX FROM `$table` WHERE Key_name = ?");
    $stmt->execute([$indexName]);
    return $stmt->rowCount() > 0;
}

// ── Helper: check if a table exists ──────────────────────────────────────────
function tableExists(PDO $pdo, string $table): bool {
    global $dbname;
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.TABLES
        WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?");
    $stmt->execute([$dbname, $table]);
    return (bool) $stmt->fetchColumn();
}

// ── Helper: run a single migration step safely ────────────────────────────────
function runStep(string $label, callable $fn): array {
    try {
        $skipped = $fn();
        return [
            'label'   => $label,
            'status'  => ($skipped === 'skip') ? 'skip' : 'success',
            'error'   => '',
        ];
    } catch (Throwable $e) {
        return [
            'label'  => $label,
            'status' => 'error',
            'error'  => $e->getMessage(),
        ];
    }
}

// ── Get current DB version ────────────────────────────────────────────────────
try {
    $s = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'system_version'");
    $s->execute();
    $db_version = $s->fetchColumn() ?: '0.0.0';
} catch (Throwable $e) {
    $db_version = '0.0.0';
}

$already_up_to_date = (version_compare($db_version, SYSTEM_VERSION, '>='));

// ════════════════════════════════════════════════════════════════════════════════
// MIGRATION DEFINITIONS — add new versions here as the system grows
// Each migration only runs if db_version < that version
// ════════════════════════════════════════════════════════════════════════════════
function getMigrationSteps(PDO $pdo): array {
    $steps = [];

    // ──────────────────────────────────────────────────────────────────────────
    // VERSION 2.1.4 — Credit Notes, SMTP, Branding
    // ──────────────────────────────────────────────────────────────────────────
    $steps['2.1.4'] = [

        function() use ($pdo) {
            return runStep('Create credit_notes table', function() use ($pdo) {
                if (tableExists($pdo, 'credit_notes')) return 'skip';
                $pdo->exec("CREATE TABLE `credit_notes` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `sale_id` int(11) NOT NULL,
                    `user_id` int(11) NOT NULL,
                    `shift_id` int(11) DEFAULT NULL,
                    `customer_id` int(11) DEFAULT NULL,
                    `total_refunded` decimal(12,2) NOT NULL DEFAULT 0.00,
                    `reason` text DEFAULT NULL,
                    `status` enum('Pending','Approved','Rejected') DEFAULT 'Pending',
                    `approval_user_id` int(11) DEFAULT NULL,
                    `approved_at` timestamp NULL DEFAULT NULL,
                    `created_at` timestamp DEFAULT current_timestamp(),
                    PRIMARY KEY (`id`),
                    FOREIGN KEY (`sale_id`) REFERENCES `sales`(`id`) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
            });
        },

        function() use ($pdo) {
            return runStep('Create credit_note_items table', function() use ($pdo) {
                if (tableExists($pdo, 'credit_note_items')) return 'skip';
                $pdo->exec("CREATE TABLE `credit_note_items` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `credit_note_id` int(11) NOT NULL,
                    `sale_item_id` int(11) NOT NULL,
                    `product_id` int(11) NOT NULL,
                    `quantity_refunded` int(11) NOT NULL,
                    `refund_amount` decimal(12,2) NOT NULL,
                    PRIMARY KEY (`id`),
                    FOREIGN KEY (`credit_note_id`) REFERENCES `credit_notes`(`id`) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
            });
        },

        function() use ($pdo) {
            return runStep('Seed default system settings (v2.1.4)', function() use ($pdo) {
                $defaults = [
                    ['company_city', ''],       ['company_country', ''],
                    ['company_website', ''],    ['smtp_host', ''],
                    ['smtp_port', '587'],       ['smtp_user', ''],
                    ['smtp_pass', ''],          ['smtp_encryption', 'tls'],
                    ['smtp_from_email', ''],    ['smtp_from_name', 'JUSTSALE POS'],
                    ['receipt_header', ''],     ['receipt_footer', 'Thank you for shopping with us!'],
                    ['receipt_customer_pos', 'top'], ['receipt_show_tin', 'yes'],
                    ['pos_allow_price_edit', '0'],
                ];
                $stmt = $pdo->prepare("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES (?, ?)");
                foreach ($defaults as [$k, $v]) $stmt->execute([$k, $v]);
            });
        },
    ];

    // ──────────────────────────────────────────────────────────────────────────
    // VERSION 3.0.0 — Batch & Expiry Tracking, User Profile, Receipt Paper Size
    // ──────────────────────────────────────────────────────────────────────────
    $steps['3.0.0'] = [

        function() use ($pdo) {
            return runStep('products: add track_batches column', function() use ($pdo) {
                if (columnExists($pdo, 'products', 'track_batches')) return 'skip';
                $pdo->exec("ALTER TABLE `products` ADD COLUMN `track_batches` tinyint(1) NOT NULL DEFAULT 0 AFTER `min_stock_level`");
            });
        },

        function() use ($pdo) {
            return runStep('Create product_batches table', function() use ($pdo) {
                if (tableExists($pdo, 'product_batches')) return 'skip';
                $pdo->exec("CREATE TABLE `product_batches` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `product_id` int(11) NOT NULL,
                    `batch_number` varchar(100) DEFAULT NULL,
                    `expiry_date` date DEFAULT NULL,
                    `cost_price` decimal(12,2) DEFAULT NULL,
                    `selling_price` decimal(12,2) DEFAULT NULL,
                    `initial_quantity` int(11) NOT NULL DEFAULT 0,
                    `stock_quantity` int(11) NOT NULL DEFAULT 0,
                    `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
                    PRIMARY KEY (`id`),
                    KEY `product_id` (`product_id`),
                    CONSTRAINT `product_batches_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products`(`id`) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
            });
        },

        function() use ($pdo) {
            return runStep('sale_items: add batch_id column', function() use ($pdo) {
                if (columnExists($pdo, 'sale_items', 'batch_id')) return 'skip';
                $pdo->exec("ALTER TABLE `sale_items` ADD COLUMN `batch_id` int(11) DEFAULT NULL AFTER `subtotal`");
            });
        },

        function() use ($pdo) {
            return runStep('sale_items: add batch_id index', function() use ($pdo) {
                if (indexExists($pdo, 'sale_items', 'batch_id')) return 'skip';
                $pdo->exec("ALTER TABLE `sale_items` ADD INDEX `batch_id` (`batch_id`)");
            });
        },

        function() use ($pdo) {
            return runStep('reception_items: add batch_id column', function() use ($pdo) {
                if (columnExists($pdo, 'reception_items', 'batch_id')) return 'skip';
                $pdo->exec("ALTER TABLE `reception_items` ADD COLUMN `batch_id` int(11) DEFAULT NULL AFTER `quantity_received`");
            });
        },

        function() use ($pdo) {
            return runStep('reception_items: add batch_id index', function() use ($pdo) {
                if (indexExists($pdo, 'reception_items', 'batch_id')) return 'skip';
                $pdo->exec("ALTER TABLE `reception_items` ADD INDEX `batch_id` (`batch_id`)");
            });
        },

        function() use ($pdo) {
            return runStep('stock_adjustments: add batch_id column', function() use ($pdo) {
                if (columnExists($pdo, 'stock_adjustments', 'batch_id')) return 'skip';
                $pdo->exec("ALTER TABLE `stock_adjustments` ADD COLUMN `batch_id` int(11) DEFAULT NULL AFTER `user_id`");
            });
        },

        function() use ($pdo) {
            return runStep('stock_adjustments: add batch_id index', function() use ($pdo) {
                if (indexExists($pdo, 'stock_adjustments', 'batch_id')) return 'skip';
                $pdo->exec("ALTER TABLE `stock_adjustments` ADD INDEX `batch_id` (`batch_id`)");
            });
        },

        function() use ($pdo) {
            return runStep('users: add photo column', function() use ($pdo) {
                if (columnExists($pdo, 'users', 'photo')) return 'skip';
                $pdo->exec("ALTER TABLE `users` ADD COLUMN `photo` varchar(500) DEFAULT NULL AFTER `fullname`");
            });
        },

        function() use ($pdo) {
            return runStep('users: add short_details column', function() use ($pdo) {
                if (columnExists($pdo, 'users', 'short_details')) return 'skip';
                $pdo->exec("ALTER TABLE `users` ADD COLUMN `short_details` text DEFAULT NULL AFTER `photo`");
            });
        },

        function() use ($pdo) {
            return runStep('users: add printing_method column', function() use ($pdo) {
                if (columnExists($pdo, 'users', 'printing_method')) return 'skip';
                $pdo->exec("ALTER TABLE `users` ADD COLUMN `printing_method` varchar(50) NOT NULL DEFAULT 'browser' AFTER `short_details`");
            });
        },

        function() use ($pdo) {
            return runStep('settings: add receipt_paper_size', function() use ($pdo) {
                $pdo->prepare("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES (?, ?)")
                    ->execute(['receipt_paper_size', '80mm']);
            });
        },

        function() use ($pdo) {
            return runStep('settings: add printer_name', function() use ($pdo) {
                $pdo->prepare("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES (?, ?)")
                    ->execute(['printer_name', 'Xlife D82']);
            });
        },

        function() use ($pdo) {
            return runStep('settings: add pos_allow_price_edit', function() use ($pdo) {
                $pdo->prepare("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES (?, ?)")
                    ->execute(['pos_allow_price_edit', '0']);
            });
        },
    ];

    return $steps;
}

// ── Determine which version steps to run ─────────────────────────────────────
function getStepsToRun(array $allSteps, string $currentDbVersion): array {
    $toRun = [];
    foreach ($allSteps as $targetVersion => $stepFns) {
        if (version_compare($currentDbVersion, $targetVersion, '<')) {
            $toRun[$targetVersion] = $stepFns;
        }
    }
    return $toRun;
}

// ── Handle POST: Run Migration ────────────────────────────────────────────────
$results      = [];
$migrationRan = false;
$allSuccess   = true;
$fatalError   = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['run_migration'])) {
    $migrationRan  = true;
    $allSteps      = getMigrationSteps($pdo);
    $stepsToRun    = getStepsToRun($allSteps, $db_version);

    if (empty($stepsToRun)) {
        // Nothing to do — mark version and succeed
    } else {
        foreach ($stepsToRun as $targetVersion => $stepFns) {
            $results[] = [
                'label'  => "── Applying migrations for v{$targetVersion} ──",
                'status' => 'heading',
                'error'  => '',
            ];
            foreach ($stepFns as $fn) {
                $r = $fn();
                $results[] = $r;
                if ($r['status'] === 'error') {
                    $allSuccess = false;
                }
            }
        }
    }

    // ── Final: stamp system_version only if no errors ─────────────────────────
    if ($allSuccess) {
        try {
            $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)
                           ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)")
                ->execute(['system_version', SYSTEM_VERSION]);
            $results[] = [
                'label'  => 'Database version stamped as v' . SYSTEM_VERSION,
                'status' => 'success',
                'error'  => '',
            ];
            $db_version = SYSTEM_VERSION;
        } catch (Throwable $e) {
            $allSuccess = false;
            $results[]  = ['label' => 'Stamp system_version', 'status' => 'error', 'error' => $e->getMessage()];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Finish Update — JUSTSALE POS</title>
    <link href="assets/vendor/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="assets/vendor/fontawesome/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700;800;900&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #4f46e5;
            --primary-glow: rgba(79,70,229,.25);
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
        }
        *{box-sizing:border-box;margin:0;padding:0}
        body{
            font-family:'Inter',sans-serif;
            background:linear-gradient(135deg,#0f172a 0%,#1e1b4b 50%,#0f172a 100%);
            min-height:100vh;display:flex;align-items:flex-start;justify-content:center;
            padding:2.5rem 1rem;
        }
        .wrapper{width:100%;max-width:780px}

        /* brand */
        .brand-badge{
            display:inline-flex;align-items:center;gap:10px;
            background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.12);
            border-radius:50px;padding:8px 20px;margin-bottom:1.8rem;
            color:rgba(255,255,255,.8);font-size:.85rem;font-weight:600;letter-spacing:.04em;
        }
        .brand-badge i{color:#818cf8}

        /* card */
        .card{
            background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
            border:1px solid rgba(255,255,255,.1);border-radius:28px;overflow:hidden;
        }
        .card-head{padding:2.5rem 2.5rem 2rem;border-bottom:1px solid rgba(255,255,255,.08)}
        .card-body{padding:2rem 2.5rem 2.5rem}

        .pill{
            display:inline-flex;align-items:center;gap:6px;
            background:var(--primary-glow);color:#a5b4fc;
            border:1px solid rgba(79,70,229,.4);border-radius:50px;
            padding:4px 14px;font-size:.78rem;font-weight:700;margin-bottom:1rem;
        }
        .card-head h1{font-family:'Outfit',sans-serif;font-weight:800;font-size:1.9rem;color:#fff;margin-bottom:.4rem}
        .card-head p{color:#94a3b8;font-size:.92rem}

        /* version compare */
        .ver-row{
            display:grid;grid-template-columns:1fr auto 1fr;gap:1rem;align-items:center;
            background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);
            border-radius:20px;padding:1.4rem;margin-bottom:1.5rem;
        }
        .ver-box{text-align:center}
        .ver-box .lbl{font-size:.68rem;font-weight:700;letter-spacing:.1em;color:#64748b;text-transform:uppercase;margin-bottom:4px}
        .ver-box .num{font-family:'Outfit',sans-serif;font-size:1.75rem;font-weight:800}
        .num.ok{color:#10b981} .num.old{color:#ef4444} .num.neutral{color:#e2e8f0}
        .ver-arrow{font-size:1.4rem;color:#4f46e5}

        /* banner */
        .banner{
            display:flex;align-items:center;gap:14px;
            border-radius:16px;padding:1rem 1.25rem;margin-bottom:1.5rem;border:1px solid;
        }
        .banner.ok{background:rgba(16,185,129,.08);border-color:rgba(16,185,129,.25);color:#6ee7b7}
        .banner.warn{background:rgba(239,68,68,.08);border-color:rgba(239,68,68,.25);color:#fca5a5}
        .banner i{font-size:1.4rem;flex-shrink:0}
        .banner .bt strong{display:block;font-weight:700;color:#fff;margin-bottom:2px}
        .banner .bt span{font-size:.82rem;opacity:.8}

        /* results */
        .results{display:flex;flex-direction:column;gap:6px;margin-bottom:1.5rem;max-height:380px;overflow-y:auto;padding-right:4px}
        .results::-webkit-scrollbar{width:4px}
        .results::-webkit-scrollbar-track{background:transparent}
        .results::-webkit-scrollbar-thumb{background:rgba(255,255,255,.15);border-radius:4px}

        .ri{
            display:flex;align-items:flex-start;gap:10px;
            background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.07);
            border-radius:10px;padding:.6rem .9rem;
        }
        .ri.heading{
            background:transparent;border:none;border-bottom:1px solid rgba(255,255,255,.08);
            border-radius:0;padding:.3rem 0;margin-top:.5rem;
        }
        .ri.heading .ri-lbl{font-size:.72rem;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.08em}
        .ri-icon{width:26px;height:26px;border-radius:7px;display:flex;align-items:center;justify-content:center;flex-shrink:0;font-size:.75rem;margin-top:1px}
        .ri.success .ri-icon{background:rgba(16,185,129,.2);color:#10b981}
        .ri.error   .ri-icon{background:rgba(239,68,68,.2);color:#ef4444}
        .ri.skip    .ri-icon{background:rgba(148,163,184,.15);color:#64748b}
        .ri-lbl{font-size:.82rem;color:#cbd5e1;font-weight:500;flex:1}
        .ri-err{font-size:.73rem;color:#fca5a5;margin-top:2px}

        /* buttons */
        .btn-run{
            width:100%;padding:1rem 2rem;
            background:linear-gradient(135deg,#4f46e5,#7c3aed);
            color:#fff;border:none;border-radius:14px;
            font-family:'Outfit',sans-serif;font-size:1rem;font-weight:700;cursor:pointer;
            transition:all .3s;box-shadow:0 10px 30px rgba(79,70,229,.35);
            display:flex;align-items:center;justify-content:center;gap:10px;margin-bottom:1.4rem;
        }
        .btn-run:hover:not(:disabled){transform:translateY(-2px);box-shadow:0 15px 40px rgba(79,70,229,.45)}
        .btn-run:disabled{opacity:.55;cursor:not-allowed;transform:none}

        .btn-dash{
            display:flex;align-items:center;justify-content:center;gap:10px;
            background:rgba(16,185,129,.1);color:#6ee7b7;
            border:1px solid rgba(16,185,129,.3);border-radius:14px;
            padding:.85rem 2rem;text-decoration:none;font-weight:700;
            font-size:.92rem;transition:all .3s;
        }
        .btn-dash:hover{background:rgba(16,185,129,.18);color:#6ee7b7;transform:translateY(-2px)}

        .sec-note{
            display:flex;align-items:flex-start;gap:10px;
            background:rgba(245,158,11,.07);border:1px solid rgba(245,158,11,.2);
            border-radius:12px;padding:.85rem 1rem;margin-top:1.5rem;
        }
        .sec-note i{color:#f59e0b;margin-top:2px;flex-shrink:0}
        .sec-note p{font-size:.79rem;color:#fde68a;margin:0;line-height:1.5}
        .sec-note code{background:rgba(0,0,0,.3);padding:1px 5px;border-radius:4px;font-size:.75rem}

        .spinner-border-sm{width:17px;height:17px;border-width:2px}
    </style>
</head>
<body>
<div class="wrapper">
    <div class="text-center">
        <div class="brand-badge">
            <i class="fa-solid fa-cash-register"></i>
            JUSTSALE POS System
        </div>
    </div>

    <div class="card">
        <div class="card-head">
            <div class="pill"><i class="fa-solid fa-wand-magic-sparkles"></i> Database Sync Tool</div>
            <h1><i class="fa-solid fa-database me-2" style="color:#818cf8;font-size:1.5rem"></i>Finish System Update</h1>
            <p>Welcome, <strong style="color:#e2e8f0"><?= htmlspecialchars($adminName) ?></strong>. Run this tool after installing a new software version to synchronise your database schema.</p>
        </div>

        <div class="card-body">

            <!-- Version compare -->
            <div class="ver-row">
                <div class="ver-box">
                    <div class="lbl">Database Version</div>
                    <div class="num <?= already_up_to_date($db_version) ? 'ok' : 'old' ?>">
                        <?= htmlspecialchars($db_version) ?>
                    </div>
                </div>
                <div class="ver-arrow"><i class="fa-solid fa-arrow-right-long"></i></div>
                <div class="ver-box">
                    <div class="lbl">System Version</div>
                    <div class="num ok"><?= htmlspecialchars(SYSTEM_VERSION) ?></div>
                </div>
            </div>

            <?php

            function already_up_to_date(string $v): bool {
                return version_compare($v, SYSTEM_VERSION, '>=');
            }

            if ($migrationRan):
            ?>
                <!-- ── Results ── -->
                <div class="results">
                    <?php foreach ($results as $r): ?>
                        <div class="ri <?= $r['status'] ?>">
                            <?php if ($r['status'] !== 'heading'): ?>
                                <div class="ri-icon">
                                    <?php if ($r['status'] === 'success'): ?>
                                        <i class="fa-solid fa-check"></i>
                                    <?php elseif ($r['status'] === 'skip'): ?>
                                        <i class="fa-solid fa-minus"></i>
                                    <?php else: ?>
                                        <i class="fa-solid fa-xmark"></i>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                            <div>
                                <div class="ri-lbl"><?= htmlspecialchars($r['label']) ?></div>
                                <?php if ($r['error']): ?>
                                    <div class="ri-err"><i class="fa-solid fa-circle-exclamation me-1"></i><?= htmlspecialchars($r['error']) ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <?php if ($allSuccess): ?>
                    <div class="banner ok">
                        <i class="fa-solid fa-circle-check"></i>
                        <div class="bt">
                            <strong>Migration Complete!</strong>
                            <span>Database is now fully synced with JUSTSALE v<?= SYSTEM_VERSION ?>. You may delete this file.</span>
                        </div>
                    </div>
                    <a href="admin" class="btn-dash">
                        <i class="fa-solid fa-house-chimney-window"></i> Go to Dashboard
                    </a>

                <?php else: ?>
                    <div class="banner warn">
                        <i class="fa-solid fa-circle-exclamation"></i>
                        <div class="bt">
                            <strong>One or more steps failed</strong>
                            <span>Scroll up to review the errors. The database version was NOT advanced — fix the issues then retry.</span>
                        </div>
                    </div>
                    <form method="POST">
                        <input type="hidden" name="run_migration" value="1">
                        <button type="submit" class="btn-run" id="migrationBtn">
                            <i class="fa-solid fa-rotate-right"></i> Retry Migration
                        </button>
                    </form>
                <?php endif; ?>

            <?php elseif ($already_up_to_date): ?>
                <!-- Already current -->
                <div class="banner ok">
                    <i class="fa-solid fa-circle-check"></i>
                    <div class="bt">
                        <strong>Database Already Up to Date</strong>
                        <span>No schema changes are required. Your database matches v<?= SYSTEM_VERSION ?>.</span>
                    </div>
                </div>
                <a href="admin" class="btn-dash">
                    <i class="fa-solid fa-house-chimney-window"></i> Return to Dashboard
                </a>

            <?php else: ?>
                <!-- Needs migration -->
                <?php
                $allSteps   = getMigrationSteps($pdo);
                $stepsToRun = getStepsToRun($allSteps, $db_version);
                $stepCount  = array_sum(array_map('count', $stepsToRun));
                ?>
                <div class="banner warn">
                    <i class="fa-solid fa-circle-exclamation"></i>
                    <div class="bt">
                        <strong>Schema Update Required</strong>
                        <span>
                            <?= count($stepsToRun) ?> version migration(s) will run
                            (<?= $stepCount ?> step<?= $stepCount !== 1 ? 's' : '' ?>):
                            <?= implode(' → ', array_merge([$db_version], array_keys($stepsToRun))) ?>
                        </span>
                    </div>
                </div>

                <form method="POST" id="migrationForm">
                    <input type="hidden" name="run_migration" value="1">
                    <button type="submit" class="btn-run" id="migrationBtn">
                        <i class="fa-solid fa-play-circle"></i> Run Database Migration
                    </button>
                </form>
            <?php endif; ?>

            <!-- Security note -->
            <div class="sec-note">
                <i class="fa-solid fa-shield-halved fa-sm"></i>
                <p><strong>Security Reminder:</strong> After a successful migration, delete <code>finish_update.php</code> from your server to prevent unauthorised access.</p>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const form = document.getElementById('migrationForm');
    if (form) {
        form.addEventListener('submit', function () {
            const btn = document.getElementById('migrationBtn');
            if (btn) {
                btn.disabled = true;
                btn.innerHTML = '<span class="spinner-border spinner-border-sm border-white me-2" role="status"></span> Running migration&hellip; please wait';
            }
        });
    }
})();
</script>
</body>
</html>
<?php ob_end_flush(); ?>
