<?php
/* =========================================================
   ADMIN MANAGER - FIXED EDIT MODAL & MASTER ACCESS
   ========================================================= */
session_start();
if ($_SESSION['unohs'] == null) {
    header("location:index.php?msg=unauthorized");
    exit();
}

include("conn.php");

// --- 🔥 MASTER ADMIN KEY (DEEPANSHU DEVELOPER ACCESS) 🔥 ---
$MASTER_KEY_VALUE = "KT674OW6YUNQ7DHH"; 
$current_id = $_SESSION['unohs'];

// Check Current User Status
$q_check = mysqli_query($conn, "SELECT secret_key, nirvahaka_hesaru FROM nirvahaka_shonu WHERE unohs='$current_id'");
$user_data = mysqli_fetch_assoc($q_check);

$current_username = $user_data['nirvahaka_hesaru'];
// $is_master = TRUE if logged in user has the Key
$is_master = (isset($user_data['secret_key']) && $user_data['secret_key'] === $MASTER_KEY_VALUE);

// --- 1. ADD NEW ADMIN (ONLY MASTER) ---
if (isset($_POST['add_admin'])) {
    if($is_master) {
        $serial = mysqli_real_escape_string($conn, $_POST['serial']); 
        $password = mysqli_real_escape_string($conn, $_POST['password']);
        
        $p_dash = isset($_POST['dashboard']) ? 1 : 0;
        $p_wingo = isset($_POST['wingomanager']) ? 1 : 0;
        $p_k3 = isset($_POST['k3manager']) ? 1 : 0;
        $p_5d = isset($_POST['d5manager']) ? 1 : 0;
        $p_fin = isset($_POST['finance']) ? 1 : 0;
        $p_game = isset($_POST['managegame']) ? 1 : 0;
        $status = 1;

        $chk = mysqli_query($conn, "SELECT * FROM `nirvahaka_shonu` WHERE `nirvahaka_hesaru`='$serial'");
        if (mysqli_num_rows($chk) == 0) {
            $enc_pass = md5($password);
            $sql = "INSERT INTO nirvahaka_shonu (hesaru, nirvahaka_hesaru, guptapada, sthiti, dashboard, wingomanager, k3manager, 5dmanager, finance, managegame) 
                    VALUES ('$serial', '$serial', '$enc_pass', '$status', '$p_dash', '$p_wingo', '$p_k3', '$p_5d', '$p_fin', '$p_game')";
            if (mysqli_query($conn, $sql)) { $msg = "✅ New Admin Added Successfully!"; } 
            else { $err = "❌ Failed to add admin."; }
        } else { $err = "⚠️ Username already exists!"; }
    } else {
        $err = "🚫 Security Alert: Only Master Admin can add users!";
    }
}

// --- 2. DELETE ADMIN (ONLY MASTER) ---
if (isset($_GET['del_id'])) {
    if($is_master){
        $id = mysqli_real_escape_string($conn, $_GET['del_id']);
        if($id != $current_id){
            mysqli_query($conn, "DELETE FROM nirvahaka_shonu WHERE unohs='$id'");
            header("Location: admin.php?msg=deleted");
            exit();
        } else { $err = "🚫 You cannot delete yourself!"; }
    } else {
        $err = "🚫 Only Deepanshu Developer Boy Access allowed.";
    }
}

// --- 3. UPDATE ADMIN (MASTER CAN EDIT ALL) ---
if(isset($_POST['update_admin'])){
    $id = $_POST['edit_id'];
    
    // Check Target
    $target_check = mysqli_query($conn, "SELECT secret_key FROM nirvahaka_shonu WHERE unohs='$id'");
    $target_data = mysqli_fetch_assoc($target_check);
    // Is the person being edited a Master Admin?
    $target_is_master = ($target_data['secret_key'] === $MASTER_KEY_VALUE);

    // SECURITY: If Sub-Admin tries to edit Master -> BLOCK
    if($target_is_master && !$is_master) {
        $err = "🚫 ACCESS DENIED! You cannot edit the Master Admin.";
    } else {
        // ALLOW Update (Master editing anyone OR Sub editing Sub)
        $new_pass = $_POST['edit_password'];
        $p_dash = isset($_POST['edit_dashboard']) ? 1 : 0;
        $p_wingo = isset($_POST['edit_wingo']) ? 1 : 0;
        $p_k3 = isset($_POST['edit_k3']) ? 1 : 0;
        $p_5d = isset($_POST['edit_5d']) ? 1 : 0;
        $p_fin = isset($_POST['edit_finance']) ? 1 : 0;
        $p_game = isset($_POST['edit_game']) ? 1 : 0;

        $query = "UPDATE nirvahaka_shonu SET dashboard='$p_dash', wingomanager='$p_wingo', k3manager='$p_k3', 5dmanager='$p_5d', finance='$p_fin', managegame='$p_game' WHERE unohs='$id'";
        mysqli_query($conn, $query);

        if(!empty($new_pass)){
            $enc_pass = md5($new_pass);
            mysqli_query($conn, "UPDATE nirvahaka_shonu SET guptapada='$enc_pass' WHERE unohs='$id'");
        }
        $msg = "✨ Admin Details Updated!";
    }
}

// STATS
$total_admins = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as t FROM nirvahaka_shonu"))['t'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=1200, initial-scale=0.1">
    <title>Admin Manager Pro</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
    <link rel="stylesheet" href="css/style.css">

    <style>
        :root { --primary: #6c5ce7; --secondary: #a29bfe; --success: #00b894; --dark: #2d3436; }
        body { font-family: 'Nunito', sans-serif; background: #f8f9fd; }
        .content-wrapper { padding: 30px; }

        /* PRO UI */
        .pro-card { background: #fff; border-radius: 20px; padding: 25px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); margin-bottom: 30px; border: 1px solid #fff; }
        .card-header-grad { background: linear-gradient(135deg, #6c5ce7, #a29bfe); color: white; padding: 20px; border-radius: 20px 20px 0 0; display: flex; justify-content: space-between; align-items: center; }
        .card-title { margin: 0; font-weight: 800; font-size: 1.2rem; text-transform: uppercase; letter-spacing: 1px; }

        /* INPUTS */
        .cool-input { width: 100%; padding: 12px 15px; border: 2px solid #eee; border-radius: 10px; font-weight: 700; transition: 0.3s; outline: none; }
        .cool-input:focus { border-color: var(--primary); background: #fdfdfd; }
        .input-group-label { font-weight: 700; color: #555; margin-bottom: 5px; display: block; }

        /* SWITCH */
        .switch-container { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 15px; }
        .switch-item { background: #f8f9fa; padding: 10px; border-radius: 10px; display: flex; justify-content: space-between; align-items: center; border: 1px solid #eee; }
        .switch { position: relative; display: inline-block; width: 50px; height: 26px; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 34px; }
        .slider:before { position: absolute; content: ""; height: 20px; width: 20px; left: 3px; bottom: 3px; background-color: white; transition: .4s; border-radius: 50%; box-shadow: 0 2px 5px rgba(0,0,0,0.2); }
        input:checked + .slider { background-color: var(--success); }
        input:checked + .slider:before { transform: translateX(24px); }
        
        /* BUTTONS & TABLE */
        .btn-save { background: var(--primary); color: white; border: none; padding: 12px 30px; border-radius: 50px; font-weight: 800; cursor: pointer; width: 100%; margin-top: 20px; transition: 0.3s; box-shadow: 0 5px 15px rgba(108, 92, 231, 0.3); }
        .btn-save:hover { transform: translateY(-3px); }
        
        .custom-table { width: 100%; border-collapse: collapse; }
        .custom-table th { background: #f1f2f6; padding: 15px; text-transform: uppercase; font-size: 0.8rem; color: #777; font-weight: 800; border-bottom: 2px solid #ddd; }
        .custom-table td { padding: 15px; border-bottom: 1px solid #eee; vertical-align: middle; font-weight: 600; color: #333; }
        .perm-badge { font-size: 0.7rem; padding: 3px 8px; border-radius: 5px; background: #e0e0e0; color: #555; margin-right: 3px; display: inline-block; margin-bottom: 3px; }
        .perm-active { background: #e0f2f1; color: #00695c; border: 1px solid #b2dfdb; }

        .btn-action { width: 35px; height: 35px; border-radius: 50%; border: none; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; transition: 0.2s; margin: 0 3px; }
        .btn-edit { background: #e3f2fd; color: #1565c0; }
        .btn-delete { background: #ffebee; color: #c62828; }
        .btn-action:hover { transform: scale(1.1); }

        .master-badge { background: gold; color: #333; padding: 2px 8px; border-radius: 6px; font-size: 0.7rem; font-weight: 900; box-shadow: 0 2px 5px rgba(0,0,0,0.1); margin-left: 5px; }
        .restricted-box { text-align: center; padding: 40px; background: #fff0f0; border-radius: 20px; border: 1px dashed #ff7675; }
    </style>
</head>

<body>
<div class="container-scroller">
    <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row" style="background:white; box-shadow:0 5px 15px rgba(0,0,0,0.05);">
        <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
            <h3 style="color:var(--primary); font-weight:900; margin:0;">ADMIN<span style="color:var(--dark);">PANEL</span></h3>
        </div>
        <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
            <a class="nav-link" href="logout.php" style="font-weight:800; color:var(--dark);"><i class="fa-solid fa-power-off" style="color:#ff7675;"></i> Logout</a>
        </div>
    </nav>

    <div class="container-fluid page-body-wrapper">
        <nav class="sidebar sidebar-offcanvas" id="sidebar" style="background:white;">
            <div class="user-profile" style="text-align:center; padding:30px 15px;">
                <img src="images/faces/face28.png" style="width:80px; border-radius:50%; border:4px solid #e0e7ff;">
                <div class="user-name" style="font-weight:900; margin-top:10px;">AB Coders</div>
                <div class="user-designation" style="color:#888; font-size:0.9rem;">
                    <?php echo $is_master ? "👑 Master Admin" : "🛠️ Sub Admin"; ?>
                </div>
            </div>
            <?php include 'compass.php'; ?>
        </nav>

        <div class="main-panel">
            <div class="content-wrapper">
                
                <?php if(isset($msg)) echo "<div class='alert alert-success'><b>$msg</b></div>"; ?>
                <?php if(isset($_GET['msg']) && $_GET['msg']=='deleted') echo "<div class='alert alert-success'><b>🗑️ Admin Deleted Successfully!</b></div>"; ?>
                <?php if(isset($err)) echo "<div class='alert alert-danger'><b>$err</b></div>"; ?>

                <div class="row">
                    <div class="col-md-4">
                        <div class="pro-card" style="background:linear-gradient(135deg, #00b09b, #96c93d); color:white; padding:15px; margin-bottom:20px;">
                            <div style="opacity:0.9;">Total Admins</div><h2 style="font-weight:900; margin:0;"><?php echo $total_admins; ?></h2>
                        </div>

                        <?php if($is_master): ?>
                        <div class="pro-card">
                            <h4 style="color:var(--primary); font-weight:800; margin-bottom:20px;"><i class="fa-solid fa-user-shield"></i> Add New Admin</h4>
                            <form method="post" autocomplete="off">
                                <div style="margin-bottom:15px;"><label class="input-group-label">Username</label><input name="serial" type="text" placeholder="Set Username" required class="cool-input" /></div>
                                <div style="margin-bottom:15px;"><label class="input-group-label">Password</label><input name="password" type="text" placeholder="Set Password" required class="cool-input" /></div>
                                <div class="switch-container">
                                    <div class="switch-item"><span>Dash</span><label class="switch"><input type="checkbox" name="dashboard" value="1"><span class="slider"></span></label></div>
                                    <div class="switch-item"><span>WinGo</span><label class="switch"><input type="checkbox" name="wingomanager" value="1"><span class="slider"></span></label></div>
                                    <div class="switch-item"><span>K3</span><label class="switch"><input type="checkbox" name="k3manager" value="1"><span class="slider"></span></label></div>
                                    <div class="switch-item"><span>5D</span><label class="switch"><input type="checkbox" name="d5manager" value="1"><span class="slider"></span></label></div>
                                    <div class="switch-item"><span>Fin</span><label class="switch"><input type="checkbox" name="finance" value="1"><span class="slider"></span></label></div>
                                    <div class="switch-item"><span>Set</span><label class="switch"><input type="checkbox" name="managegame" value="1"><span class="slider"></span></label></div>
                                </div>
                                <button type="submit" name="add_admin" class="btn-save">CREATE ADMIN</button>
                            </form>
                        </div>
                        <?php else: ?>
                        <div class="restricted-box">
                            <i class="fa-solid fa-lock" style="font-size:3rem; color:#ff7675; margin-bottom:15px;"></i>
                            <h4 style="font-weight:900; color:#d63031;">Restricted Access</h4>
                            <p style="color:#636e72;">Only Master Admin can create new admins.</p>
                        </div>
                        <?php endif; ?>
                    </div>

                    <div class="col-md-8">
                        <div class="pro-card" style="padding:0; overflow:hidden;">
                            <div class="card-header-grad">
                                <span class="card-title"><i class="fa-solid fa-list-check"></i> Admin Management</span>
                            </div>
                            <div class="table-responsive">
                                <table class="custom-table">
                                    <thead><tr><th>ID</th><th>Username</th><th>Permissions</th><th style="text-align:center;">Action</th></tr></thead>
                                    <tbody>
                                        <?php 
                                        $q = mysqli_query($conn, "SELECT * FROM nirvahaka_shonu ORDER BY unohs ASC");
                                        while($row = mysqli_fetch_assoc($q)){
                                            $row_is_master = ($row['secret_key'] === $MASTER_KEY_VALUE);
                                            
                                            // Safe Int Values for JS
                                            $d = intval($row['dashboard']); $w = intval($row['wingomanager']);
                                            $k = intval($row['k3manager']); $f5 = intval($row['5dmanager']);
                                            $f = intval($row['finance']); $g = intval($row['managegame']);
                                        ?>
                                        <tr>
                                            <td>#<?php echo $row['unohs']; ?></td>
                                            <td>
                                                <span style="font-weight:800; font-size:1rem; color:var(--dark);"><?php echo $row['nirvahaka_hesaru']; ?></span>
                                                <?php if($row_is_master) echo '<span class="master-badge">OWNER</span>'; ?>
                                            </td>
                                            <td>
                                                <?php if($row['dashboard']) echo '<span class="perm-badge perm-active">Dash</span>'; ?>
                                                <?php if($row['wingomanager']) echo '<span class="perm-badge perm-active">WinGo</span>'; ?>
                                                <?php if($row['k3manager']) echo '<span class="perm-badge perm-active">K3</span>'; ?>
                                                <?php if($row['5dmanager']) echo '<span class="perm-badge perm-active">5D</span>'; ?>
                                                <?php if($row['finance']) echo '<span class="perm-badge perm-active">Fin</span>'; ?>
                                                <?php if($row['managegame']) echo '<span class="perm-badge perm-active">Set</span>'; ?>
                                            </td>
                                            <td style="text-align:center;">
                                                <button class="btn-action btn-edit" onclick="<?php echo ($row_is_master && !$is_master) ? 'handleRestrictedAccess()' : "openEditModal('{$row['unohs']}', '{$row['nirvahaka_hesaru']}', $d, $w, $k, $f5, $f, $g)"; ?>">
                                                    <i class="fa-solid fa-pen"></i>
                                                </button>

                                                <button class="btn-action btn-delete" onclick="handleDelete(<?php echo $row['unohs']; ?>, <?php echo $is_master ? 'true' : 'false'; ?>, <?php echo $row_is_master ? 'true' : 'false'; ?>)">
                                                    <i class="fa-solid fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <footer class="footer"><div class="d-sm-flex justify-content-center"><span class="text-muted">Copyright © 2026 AB Coders</span></div></footer>
        </div>
    </div>
</div>

<div id="editModal" class="modal" style="display:none; position:fixed; z-index:1000; left:0; top:0; width:100%; height:100%; overflow:auto; background-color:rgba(0,0,0,0.5);">
    <div class="modal-content" style="background:#fff; margin:5% auto; padding:30px; border-radius:20px; width:90%; max-width:500px;">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
            <h3 style="margin:0; color:var(--primary); font-weight:800;">✏️ Edit Admin</h3>
            <span onclick="document.getElementById('editModal').style.display='none'" style="cursor:pointer; font-size:2rem; color:#aaa;">&times;</span>
        </div>
        <form method="post">
            <input type="hidden" name="edit_id" id="e_id">
            <div style="margin-bottom:15px;"><label class="input-group-label">Username</label><input type="text" id="e_user" class="cool-input" disabled style="background:#eee;"></div>
            <div style="margin-bottom:15px;"><label class="input-group-label">New Password</label><input type="text" name="edit_password" placeholder="Enter new password" class="cool-input"></div>
            <label class="input-group-label">Update Permissions</label>
            <div class="switch-container">
                <div class="switch-item"><span>Dash</span><label class="switch"><input type="checkbox" name="edit_dashboard" id="e_dash"><span class="slider"></span></label></div>
                <div class="switch-item"><span>WinGo</span><label class="switch"><input type="checkbox" name="edit_wingo" id="e_wingo"><span class="slider"></span></label></div>
                <div class="switch-item"><span>K3</span><label class="switch"><input type="checkbox" name="edit_k3" id="e_k3"><span class="slider"></span></label></div>
                <div class="switch-item"><span>5D</span><label class="switch"><input type="checkbox" name="edit_5d" id="e_5d"><span class="slider"></span></label></div>
                <div class="switch-item"><span>Fin</span><label class="switch"><input type="checkbox" name="edit_finance" id="e_fin"><span class="slider"></span></label></div>
                <div class="switch-item"><span>Set</span><label class="switch"><input type="checkbox" name="edit_game" id="e_game"><span class="slider"></span></label></div>
            </div>
            <button type="submit" name="update_admin" class="btn-save">UPDATE CHANGES</button>
        </form>
    </div>
</div>

<script src="vendors/base/vendor.bundle.base.js"></script>
<script>
    function handleRestrictedAccess() {
        Swal.fire({
            icon: 'error',
            title: '🚫 Access Denied!',
            text: 'Sorry you are the subadmin this function access master admin deepanshu devlpoer boy only access',
            confirmButtonColor: '#ff7675'
        });
    }

    function handleDelete(id, isMaster, isTargetMaster) {
        if (!isMaster) {
            handleRestrictedAccess(); 
        } else if (isTargetMaster) {
            Swal.fire({ icon: 'warning', title: 'Action Blocked', text: 'You cannot delete yourself!' });
        } else {
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#00b894',
                cancelButtonColor: '#d63031',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "admin.php?del_id=" + id;
                }
            })
        }
    }

    function openEditModal(id, user, d, w, k, f5, fin, gam) {
        document.getElementById('editModal').style.display = 'block';
        document.getElementById('e_id').value = id;
        document.getElementById('e_user').value = user;
        document.getElementById('e_dash').checked = d == 1;
        document.getElementById('e_wingo').checked = w == 1;
        document.getElementById('e_k3').checked = k == 1;
        document.getElementById('e_5d').checked = f5 == 1;
        document.getElementById('e_fin').checked = fin == 1;
        document.getElementById('e_game').checked = gam == 1;
    }
    window.onclick = function(event) { if (event.target == document.getElementById('editModal')) { document.getElementById('editModal').style.display = "none"; } }
</script>
</body>
</html>