<?php
session_start();
if ($_SESSION['unohs'] == null) {
    header("location:index.php?msg=unauthorized");
    exit;
}
include("conn.php");

// ✅ DELETE LOGIC
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $deleteId = intval($_GET['delete']);

    mysqli_query($conn, "DELETE FROM admin_roles WHERE admin_id = '$deleteId'");
    mysqli_query($conn, "DELETE FROM nirvahaka_shonu WHERE unohs = '$deleteId'");

    echo '<script>alert("Admin Deleted Successfully"); window.location.href = "' . $_SERVER['PHP_SELF'] . '";</script>';
    exit;
}

// ✅ ADD ADMIN LOGIC
if (isset($_POST['serial']) && isset($_POST['maxusers'])) {
    $serial   = mysqli_real_escape_string($conn, $_POST['serial']);
    $password = mysqli_real_escape_string($conn, $_POST['maxusers']);

    // Check for duplicate admin
    $chk = mysqli_query($conn, "SELECT 1 FROM nirvahaka_shonu WHERE nirvahaka_hesaru='$serial'");
    if (mysqli_num_rows($chk) > 0) {
        echo '<script>alert("Duplicate Username");</script>';
        exit;
    }

    $status = 1;

    // Insert basic admin info
    $sql = "INSERT INTO nirvahaka_shonu (hesaru, nirvahaka_hesaru, guptapada, sthiti)
            VALUES ('$serial', '$serial', '" . md5($password) . "', '$status')";
    $insertAdmin = mysqli_query($conn, $sql);

    if ($insertAdmin) {
        $adminId = mysqli_insert_id($conn);

        // ✅ Insert selected roles & subroles into admin_roles
        $roles    = isset($_POST['roles']) ? $_POST['roles'] : [];
        $subroles = isset($_POST['subroles']) ? $_POST['subroles'] : [];

        foreach ($roles as $module => $val) {
            $safeModule = mysqli_real_escape_string($conn, $module);
            mysqli_query($conn, "INSERT INTO admin_roles (admin_id, module, submodule, allowed, created_at) 
                                 VALUES ('$adminId', '$safeModule', '', 1, NOW())");

            if (isset($subroles[$module])) {
                foreach ($subroles[$module] as $submodule => $subVal) {
                    $safeSub = mysqli_real_escape_string($conn, $submodule);
                    mysqli_query($conn, "INSERT INTO admin_roles (admin_id, module, submodule, allowed, created_at) 
                                         VALUES ('$adminId', '$safeModule', '$safeSub', 1, NOW())");
                }
            }
        }

        echo '<script>alert("Admin Added Successfully!"); window.location.href="' . $_SERVER['PHP_SELF'] . '";</script>';
    } else {
        echo '<script>alert("Admin Add Failed!");</script>';
    }
}
?>
<?php include 'header.php'; ?>


<div class="main-panel">
  <div class="content-wrapper">
    <div class="row">
      <div class="col-sm-12 mb-4 mb-xl-0">
        <h4 class="font-weight-bold text-dark">Add Admin</h4>
      </div>
    </div> 
    <div class="row">
      <form action="#" id="redform" method="post" autocomplete="off">
        <input name="serial" type="text" placeholder="Enter User Name" required class="flex-grow-1 cool-input" style="height: 40px;" />
        <br><br>

        <input name="maxusers" type="text" placeholder="Enter Password" required class="flex-grow-1 cool-input" style="height: 40px;" />
        <br><br>

        <?php
        // ✅ FETCH modules and submodules from database
        $res = mysqli_query($conn, "SELECT module, submodule FROM navigation_structure ORDER BY module");
        $modules = [];
        while ($row = mysqli_fetch_assoc($res)) {
            $modules[$row['module']][] = $row['submodule'];
        }

        // ✅ GENERATE checkboxes
        foreach ($modules as $module => $submodules) {
            $moduleId = strtolower(str_replace(' ', '', $module));
            echo "<input type='checkbox' id='$moduleId' name='roles[$module]' value='1' onclick=\"toggleSubroles('$moduleId')\">
            <label for='$moduleId'>" . ucfirst($module) . "</label>
            <div id='subroles-$moduleId' style='display:none; margin-left:20px;'>";
            
            foreach ($submodules as $sub) {
                if ($sub !== null) {
                    echo "<input type='checkbox' name='subroles[$module][$sub]' value='1'> $sub<br>";
                }
            }
            echo "</div><br><br>";
        }
        ?>

        <small style="color: #c0392b; font-size: 13px;">
        ⚠️ Note: If you want to give Admin Manager access, make sure to select all its sub-permissions (like Add Admin, Admin Password, etc.) <b>before</b> enabling this main Admin access. It only works when full access is granted.
        </small>
        <br><br>

        <button type="submit" class="btn btn-primary cool-button mr-2">Add</button>
      </form>
    </div>
  






   <!-- ✅ ADMIN TABLE -->
<div class="row mt-5">
  <div class="col-sm-12">
    <h4 class="font-weight-bold text-dark">All Admins</h4>
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <thead class="thead-dark">
          <tr>
            <th>ID</th>
            <th>Username</th>
            <?php
            // ✅ Get all module names dynamically
            $modulesRes = mysqli_query($conn, "SELECT DISTINCT module FROM navigation_structure");
            $moduleNames = [];
            while ($mRow = mysqli_fetch_assoc($modulesRes)) {
              $moduleNames[] = $mRow['module'];
              echo "<th>" . ucfirst($mRow['module']) . "</th>";
            }
            ?>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          <?php
          $getAdmins = mysqli_query($conn, "SELECT * FROM nirvahaka_shonu ORDER BY unohs DESC");
          while ($row = mysqli_fetch_assoc($getAdmins)) {
            echo "<tr>
              <td>{$row['unohs']}</td>
              <td>{$row['nirvahaka_hesaru']}</td>";

            // ✅ Show dynamic module access from admin_roles
            foreach ($moduleNames as $module) {
              $checkAccess = mysqli_query($conn, "SELECT allowed FROM admin_roles WHERE admin_id = '{$row['unohs']}' AND module = '{$module}' AND allowed = 1 LIMIT 1");
              echo "<td>" . (mysqli_num_rows($checkAccess) > 0 ? '✅' : '❌') . "</td>";
            }

            // ✅ Action column
            echo "<td>";
            if ($row['unohs'] == 59) {
              echo "<span class='badge badge-secondary'>🔒 Locked</span>";
            } else {
              echo "<a href='?delete={$row['unohs']}' onclick=\"return confirm('Are you sure you want to delete this admin?')\" class='btn btn-danger btn-sm'>🗑️ Delete</a>";
            }
            echo "</td>
            </tr>";
          }
          ?>
        </tbody>
      </table>
    </div>
  </div>
</div>


        <!--<footer class="footer">
          <div class="d-sm-flex justify-content-center justify-content-sm-between">
            <span class="text-muted d-block text-center text-sm-left d-sm-inline-block">Copyright © 51gameplay.online 2024</span>
          </div>
        </footer>-->
      </div>
    </div>
</body>



<script>
function toggleSubroles(module) {
  const checkbox = document.getElementById(module + 'manager') || document.getElementById(module);
  const container = document.getElementById('subroles-' + module);
  if (!checkbox || !container) return;

  if (checkbox.checked) {
    fetch('get_subroles.php?module=' + module)
      .then(res => res.text())
      .then(html => {
        container.innerHTML = html;
        container.style.display = 'block';
      });
  } else {
    container.innerHTML = '';
    container.style.display = 'none';
  }
}
</script>


</html>