<?php
session_start();
include '../includes/db.php';

$msg = ['uid' => '', 'uid_type' => '', 'new' => '', 'new_type' => '', 'pwd' => '', 'pwd_type' => ''];

// CSRF tokens
foreach (['csrf_uid', 'csrf_new', 'csrf_pwd'] as $t) {
    if (empty($_SESSION[$t])) $_SESSION[$t] = bin2hex(random_bytes(32));
}

// ─────────────────────────────────────────────────────────────────────────────
// ACTION 1: Change Existing User ID
// ─────────────────────────────────────────────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'change_uid') {
    if (!isset($_POST['csrf_uid']) || !hash_equals($_SESSION['csrf_uid'], $_POST['csrf_uid'])) {
        $msg['uid'] = "Invalid request."; $msg['uid_type'] = "danger";
    } else {
        $old_uid = trim($_POST['old_uid'] ?? '');
        $new_uid = trim($_POST['new_uid'] ?? '');

        if (empty($old_uid) || empty($new_uid)) {
            $msg['uid'] = "Sabhi fields bharna zaroori hai."; $msg['uid_type'] = "danger";
        } elseif (!preg_match('/^[a-zA-Z0-9_]{3,30}$/', $new_uid)) {
            $msg['uid'] = "User ID: sirf letters, numbers, underscore. Min 3, Max 30 chars."; $msg['uid_type'] = "danger";
        } else {
            // Old ID exist karta hai?
            $chk = $conn->prepare("SELECT id FROM admin_users WHERE username = ?");
            $chk->bind_param("s", $old_uid); $chk->execute(); $chk->store_result();
            if ($chk->num_rows === 0) {
                $msg['uid'] = "Old User ID nahi mila. Dobara check karein."; $msg['uid_type'] = "danger";
                $chk->close();
            } else {
                $chk->close();
                // New ID already exist?
                $dup = $conn->prepare("SELECT id FROM admin_users WHERE username = ?");
                $dup->bind_param("s", $new_uid); $dup->execute(); $dup->store_result();
                if ($dup->num_rows > 0) {
                    $msg['uid'] = "Yeh User ID already exist karta hai."; $msg['uid_type'] = "danger";
                    $dup->close();
                } else {
                    $dup->close();
                    $upd = $conn->prepare("UPDATE admin_users SET username = ? WHERE username = ?");
                    $upd->bind_param("ss", $new_uid, $old_uid);
                    if ($upd->execute()) {
                        $msg['uid'] = "✅ User ID change ho gaya! <strong>" . htmlspecialchars($old_uid) . "</strong> → <strong>" . htmlspecialchars($new_uid) . "</strong>";
                        $msg['uid_type'] = "success";
                        $_SESSION['csrf_uid'] = bin2hex(random_bytes(32));
                    } else {
                        $msg['uid'] = "Error. Try again."; $msg['uid_type'] = "danger";
                    }
                    $upd->close();
                }
            }
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// ACTION 2: Create New Admin User
// ─────────────────────────────────────────────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'create_new') {
    if (!isset($_POST['csrf_new']) || !hash_equals($_SESSION['csrf_new'], $_POST['csrf_new'])) {
        $msg['new'] = "Invalid request."; $msg['new_type'] = "danger";
    } else {
        $new_uid  = trim($_POST['create_uid']  ?? '');
        $new_email= trim($_POST['create_email']?? '');
        $new_pwd  = $_POST['create_pwd']        ?? '';
        $con_pwd  = $_POST['create_pwd_confirm']?? '';

        if (empty($new_uid) || empty($new_pwd)) {
            $msg['new'] = "User ID aur Password zaroori hain."; $msg['new_type'] = "danger";
        } elseif (!preg_match('/^[a-zA-Z0-9_]{3,30}$/', $new_uid)) {
            $msg['new'] = "User ID: sirf letters, numbers, underscore. Min 3, Max 30 chars."; $msg['new_type'] = "danger";
        } elseif (strlen($new_pwd) < 6) {
            $msg['new'] = "Password kam se kam 6 characters ka hona chahiye."; $msg['new_type'] = "danger";
        } elseif ($new_pwd !== $con_pwd) {
            $msg['new'] = "Dono passwords match nahi karte."; $msg['new_type'] = "danger";
        } else {
            // ID already taken?
            $dup = $conn->prepare("SELECT id FROM admin_users WHERE username = ?");
            $dup->bind_param("s", $new_uid); $dup->execute(); $dup->store_result();
            if ($dup->num_rows > 0) {
                $msg['new'] = "Yeh User ID already exist karta hai. Alag choose karein."; $msg['new_type'] = "danger";
                $dup->close();
            } else {
                $dup->close();
                $hashed = password_hash($new_pwd, PASSWORD_DEFAULT);
                $ins = $conn->prepare("INSERT INTO admin_users (username, password, email) VALUES (?, ?, ?)");
                $email_val = !empty($new_email) ? $new_email : null;
                $ins->bind_param("sss", $new_uid, $hashed, $email_val);
                if ($ins->execute()) {
                    $msg['new'] = "✅ Naya Admin User create ho gaya! User ID: <strong>" . htmlspecialchars($new_uid) . "</strong>";
                    $msg['new_type'] = "success";
                    $_SESSION['csrf_new'] = bin2hex(random_bytes(32));
                } else {
                    $msg['new'] = "Error. Try again."; $msg['new_type'] = "danger";
                }
                $ins->close();
            }
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// ACTION 3: Change Password
// ─────────────────────────────────────────────────────────────────────────────
if (isset($_POST['action']) && $_POST['action'] === 'change_pwd') {
    if (!isset($_POST['csrf_pwd']) || !hash_equals($_SESSION['csrf_pwd'], $_POST['csrf_pwd'])) {
        $msg['pwd'] = "Invalid request."; $msg['pwd_type'] = "danger";
    } else {
        $uid     = trim($_POST['pwd_uid']     ?? '');
        $new_pwd = $_POST['pwd_new']           ?? '';
        $con_pwd = $_POST['pwd_confirm']       ?? '';

        if (empty($uid)) {
            $msg['pwd'] = "User ID daalna zaroori hai."; $msg['pwd_type'] = "danger";
        } elseif (strlen($new_pwd) < 6) {
            $msg['pwd'] = "Password kam se kam 6 characters hona chahiye."; $msg['pwd_type'] = "danger";
        } elseif ($new_pwd !== $con_pwd) {
            $msg['pwd'] = "Dono passwords match nahi karte."; $msg['pwd_type'] = "danger";
        } else {
            $chk = $conn->prepare("SELECT id FROM admin_users WHERE username = ?");
            $chk->bind_param("s", $uid); $chk->execute(); $chk->store_result();
            if ($chk->num_rows === 0) {
                $msg['pwd'] = "Invalid User ID."; $msg['pwd_type'] = "danger";
                $chk->close();
            } else {
                $chk->bind_result($mid); $chk->fetch(); $chk->close();
                $hashed = password_hash($new_pwd, PASSWORD_DEFAULT);
                $upd = $conn->prepare("UPDATE admin_users SET password = ? WHERE id = ?");
                $upd->bind_param("si", $hashed, $mid);
                if ($upd->execute()) {
                    $msg['pwd'] = "✅ Password change ho gaya!"; $msg['pwd_type'] = "success";
                    $_SESSION['csrf_pwd'] = bin2hex(random_bytes(32));
                } else {
                    $msg['pwd'] = "Error. Try again."; $msg['pwd_type'] = "danger";
                }
                $upd->close();
            }
        }
    }
}

// Current admin users list
$users_res = $conn->query("SELECT id, username, email FROM admin_users ORDER BY id ASC");
$admin_users = [];
while ($row = $users_res->fetch_assoc()) $admin_users[] = $row;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Admin Credentials – Balimeen</title>
    <link rel="shortcut icon" href="/bm/BM LOGO.jpg" type="image/jpeg">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background: linear-gradient(135deg, #e0f0ff, #c9d6ff); min-height: 100vh; padding: 30px 15px; }
        .wrapper { max-width: 520px; margin: auto; }
        .page-title { text-align: center; font-weight: 800; font-size: 1.4rem; color: #005a8e; margin-bottom: 1.5rem; }
        .card-section {
            background: deepskyblue;
            border-radius: 24px;
            padding: 1.8rem;
            margin-bottom: 1.4rem;
            box-shadow: 0 6px 20px rgba(0,0,0,0.12);
        }
        .card-section h5 { color: #fff; font-weight: 700; font-size: 1.05rem; margin-bottom: 1rem; }
        .card-section .form-label { color: #fff; font-size: 13px; font-weight: 600; margin-bottom: 4px; }
        .hint { font-size: 11px; color: rgba(255,255,255,0.8); margin-top: 3px; }
        .password-wrapper { position: relative; }
        .password-wrapper .eye-btn { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; color: #555; cursor: pointer; padding: 0; }
        .password-wrapper input { padding-right: 38px; }
        .users-table { background: rgba(255,255,255,0.9); border-radius: 12px; padding: 10px 14px; }
        .users-table th { font-size: 12px; color: #005a8e; }
        .users-table td { font-size: 13px; }
        .nav-links { text-align: center; margin-top: 0.5rem; font-size: 13px; }
        .nav-links a { color: #005a8e; text-decoration: underline; margin: 0 8px; }
    </style>
</head>
<body>
<div class="wrapper">
    <div class="page-title"><i class="fa fa-user-cog me-2"></i>Manage Admin Credentials</div>

    <!-- Current Users -->
    <div class="card-section">
        <h5><i class="fa fa-users me-2"></i>Current Admin Users</h5>
        <div class="users-table">
            <table class="table table-sm mb-0">
                <thead><tr><th>#</th><th>User ID</th><th>Email</th></tr></thead>
                <tbody>
                <?php foreach ($admin_users as $u): ?>
                    <tr>
                        <td><?php echo $u['id']; ?></td>
                        <td><strong><?php echo htmlspecialchars($u['username']); ?></strong></td>
                        <td><?php echo htmlspecialchars($u['email'] ?? '—'); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- ── Section 1: Change Existing User ID ── -->
    <div class="card-section">
        <h5><i class="fa fa-exchange-alt me-2"></i>Change Existing User ID</h5>
        <p style="color:rgba(255,255,255,0.85);font-size:12px;">Old User ID ko naye ID se replace karo (same account)</p>

        <?php if ($msg['uid']): ?>
            <div class="alert alert-<?php echo $msg['uid_type']; ?> py-2"><?php echo $msg['uid']; ?></div>
        <?php endif; ?>

        <form method="POST" autocomplete="off">
            <input type="hidden" name="action"   value="change_uid">
            <input type="hidden" name="csrf_uid" value="<?php echo htmlspecialchars($_SESSION['csrf_uid']); ?>">
            <div class="mb-2">
                <label class="form-label">Old User ID (current)</label>
                <input type="text" class="form-control" name="old_uid" placeholder="e.g. admin" required autocomplete="off"
                       value="<?php echo (isset($_POST['old_uid']) && $msg['uid_type']==='danger') ? htmlspecialchars($_POST['old_uid']) : ''; ?>">
            </div>
            <div class="mb-3">
                <label class="form-label">New User ID</label>
                <input type="text" class="form-control" name="new_uid" placeholder="e.g. balimeen_admin" required autocomplete="off"
                       value="<?php echo (isset($_POST['new_uid']) && $msg['uid_type']==='danger') ? htmlspecialchars($_POST['new_uid']) : ''; ?>">
                <div class="hint">Letters, numbers, underscore only. Min 3 chars.</div>
            </div>
            <button type="submit" class="btn btn-primary w-100"><i class="fa fa-save me-1"></i>Update User ID</button>
        </form>
    </div>

    <!-- ── Section 2: Create New Admin User ── -->
    <div class="card-section">
        <h5><i class="fa fa-user-plus me-2"></i>Create New Admin User</h5>
        <p style="color:rgba(255,255,255,0.85);font-size:12px;">Bilkul naya admin account banao custom User ID se</p>

        <?php if ($msg['new']): ?>
            <div class="alert alert-<?php echo $msg['new_type']; ?> py-2"><?php echo $msg['new']; ?></div>
        <?php endif; ?>

        <form method="POST" autocomplete="off">
            <input type="hidden" name="action"    value="create_new">
            <input type="hidden" name="csrf_new"  value="<?php echo htmlspecialchars($_SESSION['csrf_new']); ?>">
            <div class="mb-2">
                <label class="form-label">New User ID</label>
                <input type="text" class="form-control" name="create_uid" placeholder="Custom User ID" required autocomplete="off"
                       value="<?php echo (isset($_POST['create_uid']) && $msg['new_type']==='danger') ? htmlspecialchars($_POST['create_uid']) : ''; ?>">
                <div class="hint">Letters, numbers, underscore only. Min 3 chars.</div>
            </div>
            <div class="mb-2">
                <label class="form-label">Email (optional)</label>
                <input type="email" class="form-control" name="create_email" placeholder="user@example.com" autocomplete="off"
                       value="<?php echo (isset($_POST['create_email']) && $msg['new_type']==='danger') ? htmlspecialchars($_POST['create_email']) : ''; ?>">
            </div>
            <div class="mb-2">
                <label class="form-label">Password</label>
                <div class="password-wrapper">
                    <input type="password" class="form-control" id="cpwd1" name="create_pwd" placeholder="Min 6 characters" required>
                    <button type="button" class="eye-btn" onclick="tp('cpwd1','ce1')"><i class="fa fa-eye" id="ce1"></i></button>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Confirm Password</label>
                <div class="password-wrapper">
                    <input type="password" class="form-control" id="cpwd2" name="create_pwd_confirm" placeholder="Password dobara" required>
                    <button type="button" class="eye-btn" onclick="tp('cpwd2','ce2')"><i class="fa fa-eye" id="ce2"></i></button>
                </div>
            </div>
            <button type="submit" class="btn btn-success w-100"><i class="fa fa-user-plus me-1"></i>Create New User</button>
        </form>
    </div>

    <!-- ── Section 3: Change Password ── -->
    <div class="card-section">
        <h5><i class="fa fa-key me-2"></i>Change Password</h5>

        <?php if ($msg['pwd']): ?>
            <div class="alert alert-<?php echo $msg['pwd_type']; ?> py-2"><?php echo $msg['pwd']; ?></div>
        <?php endif; ?>

        <form method="POST" autocomplete="off">
            <input type="hidden" name="action"   value="change_pwd">
            <input type="hidden" name="csrf_pwd" value="<?php echo htmlspecialchars($_SESSION['csrf_pwd']); ?>">
            <div class="mb-2">
                <label class="form-label">User ID</label>
                <input type="text" class="form-control" name="pwd_uid" placeholder="Jis user ka password change karna hai" required autocomplete="off"
                       value="<?php echo (isset($_POST['pwd_uid']) && $msg['pwd_type']==='danger') ? htmlspecialchars($_POST['pwd_uid']) : ''; ?>">
            </div>
            <div class="mb-2">
                <label class="form-label">Naya Password</label>
                <div class="password-wrapper">
                    <input type="password" class="form-control" id="p1" name="pwd_new" placeholder="Min 6 characters" required>
                    <button type="button" class="eye-btn" onclick="tp('p1','pe1')"><i class="fa fa-eye" id="pe1"></i></button>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Confirm Password</label>
                <div class="password-wrapper">
                    <input type="password" class="form-control" id="p2" name="pwd_confirm" placeholder="Password dobara" required>
                    <button type="button" class="eye-btn" onclick="tp('p2','pe2')"><i class="fa fa-eye" id="pe2"></i></button>
                </div>
            </div>
            <button type="submit" class="btn btn-primary w-100"><i class="fa fa-save me-1"></i>Save Password</button>
        </form>
    </div>

    <div class="nav-links">
        <a href="dashboard.php"><i class="fa fa-tachometer-alt me-1"></i>Dashboard</a>
        <a href="login.php"><i class="fa fa-sign-in-alt me-1"></i>Login</a>
    </div>
</div>

<script>
function tp(fid, iid) {
    var f = document.getElementById(fid), i = document.getElementById(iid);
    f.type = f.type === 'password' ? 'text' : 'password';
    i.classList.toggle('fa-eye'); i.classList.toggle('fa-eye-slash');
}
</script>
</body>
</html>
