<?php
/**
 * ONE-TIME admin password fix — DELETE THIS FILE AFTER USE.
 * Visit: http://localhost/QR_profile/QR-profile/public/fix_admin.php
 */

// ── Adjust these if your DB credentials differ ──────────────────
$host   = 'localhost';
$user   = 'root';
$pass   = 'root';
$dbname = 'qr_profile_db';
// ────────────────────────────────────────────────────────────────

$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
    die('<h3 style="color:red">DB Connect Error: ' . htmlspecialchars($conn->connect_error) . '</h3>
         <p>Edit $host/$user/$pass/$dbname at the top of this file.</p>');
}
$conn->set_charset('utf8mb4');

$email    = 'admin@qrprofile.com';
$password = 'Admin@123';
$hash     = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

// Check if admin_users table exists
$tbl = $conn->query("SHOW TABLES LIKE 'admin_users'");
if (!$tbl || $tbl->num_rows === 0) {
    echo '<h3 style="color:orange">⚠️ Table <code>admin_users</code> does not exist yet.</h3>
          <p>Please import <code>sql/schema.sql</code> into your database first via phpMyAdmin, then run this page again.</p>';
    exit;
}

// Check if admin exists
$stmt = $conn->prepare("SELECT id FROM admin_users WHERE email = ? LIMIT 1");
$stmt->bind_param('s', $email);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows > 0) {
    $row    = $res->fetch_assoc();
    $update = $conn->prepare("UPDATE admin_users SET password = ?, is_active = 1 WHERE id = ?");
    $update->bind_param('si', $hash, $row['id']);
    $update->execute();
    echo '<h3 style="color:green">✅ Password updated successfully!</h3>';
} else {
    $insert = $conn->prepare(
        "INSERT INTO admin_users (name, email, password, role, is_active) VALUES ('Super Admin', ?, ?, 'super_admin', 1)"
    );
    $insert->bind_param('ss', $email, $hash);
    $insert->execute();
    echo '<h3 style="color:green">✅ Admin user created!</h3>';
}

$conn->close();
?>
<p><strong>Email:</strong> admin@qrprofile.com</p>
<p><strong>Password:</strong> Admin@123</p>
<hr>
<p style="color:red; font-weight:bold">⚠️ DELETE <code>public/fix_admin.php</code> after you login!</p>
<p><a href="<?= 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/login' ?>">→ Go to Login</a></p>
