<?php
// /elms/auth/super_fix.php  — DEV ONLY. DELETE AFTER RUNNING.
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
define('APP_ROOT', dirname(__DIR__)); // .../elms
require_once APP_ROOT.'/includes/db.php';

echo "<pre>";

// Show DB for sanity
$r = $mysqli->query("SELECT DATABASE() AS db")->fetch_assoc();
echo "Connected DB: {$r['db']}\n";

// Create table if missing (minimal)
$mysqli->query("
  CREATE TABLE IF NOT EXISTS elms_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100) NOT NULL UNIQUE,
    full_name VARCHAR(191) NOT NULL,
    role_slug VARCHAR(50) DEFAULT NULL,
    role_code VARCHAR(50) DEFAULT NULL,
    password_hash VARCHAR(255) NOT NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    last_login_at DATETIME NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

$user  = 'super';
$pass  = 'Super@123';
$hash  = password_hash($pass, PASSWORD_BCRYPT);

// Upsert the super admin
$st = $mysqli->prepare("
  INSERT INTO elms_users (username, full_name, role_slug, role_code, password_hash, is_active)
  VALUES (?, 'Super Admin', 'super_admin', 'super_admin', ?, 1)
  ON DUPLICATE KEY UPDATE
    role_slug=VALUES(role_slug),
    role_code=VALUES(role_code),
    password_hash=VALUES(password_hash),
    is_active=1
");
$st->bind_param('ss', $user, $hash);
$ok = $st->execute();
$st->close();

echo $ok ? "Seed/Update OK.\n" : "Seed failed: {$mysqli->error}\n";

// Show the row after change
$st = $mysqli->prepare("SELECT id, username, role_slug, role_code, is_active, LEFT(password_hash, 4) AS hash_prefix, LENGTH(password_hash) AS hash_len FROM elms_users WHERE username=?");
$st->bind_param('s',$user);
$st->execute();
$res = $st->get_result()->fetch_assoc();
$st->close();

echo "Row now:\n";
print_r($res);

echo "\nTry login at /elms/ (username: super, password: Super@123)\n";
echo "DELETE this file when done.\n";
