 <?php
require_once 'connection.php';  // Include the database connection
$conn = Database::connect(); 

// ===== Update allow toggle =====
if (isset($_POST['toggle_allow'])) {
    $id = intval($_POST['id']);
    $newStatus = intval($_POST['status']);
    $stmt = $conn->prepare("UPDATE signin SET allow = ? WHERE id = ?");
    $stmt->execute([$newStatus, $id]);
    exit('success');
}

// ===== Update user =====
if (isset($_POST['update_user'])) {
    $id = intval($_POST['user_id']);
    $fullname = $_POST['fullname'];
    $email = $_POST['email'];
    $password = !empty($_POST['new_password']) ? password_hash($_POST['new_password'], PASSWORD_DEFAULT) : null;
    $terms = isset($_POST['terms']) ? 1 : 0;

    if ($password) {
        $stmt = $conn->prepare("UPDATE signin SET fullname=?, email=?, password=?, terms=? WHERE id=?");
        $stmt->execute([$fullname, $email, $password, $terms, $id]);
    } else {
        $stmt = $conn->prepare("UPDATE signin SET fullname=?, email=?, terms=? WHERE id=?");
        $stmt->execute([$fullname, $email, $terms, $id]);
    }

    echo "<script>alert('User updated successfully');</script>";
}

// ===== Delete user =====
if (isset($_POST['delete_user'])) {
    $id = intval($_POST['id']);
    $stmt = $conn->prepare("DELETE FROM signin WHERE id=?");
    $stmt->execute([$id]);
    echo "<script>alert('User deleted');</script>";
}

// ===== Fetch Users =====
$filter = $_GET['filter'] ?? 'all';

if ($filter === 'user' || $filter === 'agent') {
    $stmt = $conn->prepare("SELECT * FROM signin WHERE filter = :filter ORDER BY id DESC");
    $stmt->execute([':filter' => $filter]);
} else {
    $stmt = $conn->query("SELECT * FROM signin ORDER BY id DESC");
}

$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ===== Fetch Jobs =====
$sql = "SELECT * FROM jobs ORDER BY id DESC";
$stmt = $conn->query($sql);
$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>




<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>All Users</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <link rel="stylesheet" href="./CSS/postjob.css" />

<style>
/* body { font-family: 'Segoe UI', sans-serif; background:#0b1120; color:#dbeafe; margin:20px; } */
.table-container {  border-radius:10px; padding:20px; }
.table-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:10px; }
.table-search input { border:none; padding:6px 10px; color:black; border-radius:6px; }
table { width:100%; border-collapse:collapse; color:black; }
th, td { padding:10px; border-bottom:1px solid #243b65; text-align:left; }
th { background: #4a90e2; color: white; }
.btn { border:none; padding:6px 12px; border-radius:6px; cursor:pointer; }
.btn-info { background:#2563eb; color:#fff; }
.btn-danger { background:#dc2626; color:#fff; }
.btn-secondary { background:#334155; color:#e2e8f0; }
  .btn-secondary:hover {
      background: #f35f04;
    }
.btn-primary { background:#1d4ed8; color:#fff; }
/* tr:hover { background:#1e293b; } */

/* MODAL STYLES */
.modal {
  position: fixed; inset: 0;
  display: none;
  align-items: center;
  justify-content: center;
  /* background: rgba(15, 23, 42, 0.75); */
  z-index: 9999;
  backdrop-filter: blur(2px);
}
.modal.open { display: flex; }
.modal-content {
  /* background: #0b1734; */
  border-radius: 10px;
  padding: 20px 24px;
  color: #dbeafe;
  width: 90%; max-width: 420px;
  /* box-shadow: 0 0 25px rgba(0,0,0,0.4); */
  position: relative;
  animation: popIn 0.25s ease-out;
}
@keyframes popIn {
  from { transform: scale(0.95); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}
.close-x {
  position: absolute;
  top: 8px; right: 12px;
  font-size: 22px;
  cursor: pointer;
  color: #9fb6d6;
}
.modal-footer { text-align:right; margin-top:12px; }
.switch {
  position: relative;
  display: inline-block;
  width: 42px;
  height: 22px;
}
.switch input { display: none; }
.slider {
  position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0;
  background-color: #334155;
  transition: .4s;
  border-radius: 22px;
}
.slider:before {
  position: absolute; content: "";
  height: 16px; width: 16px; left: 3px; bottom: 3px;
  background-color: white;
  transition: .4s; border-radius: 50%;
}
input:checked + .slider {
  background-color: #4CAF50;
}
input:checked + .slider:before {
  transform: translateX(20px);
}




.filter-menu {
  display: none;
  position: absolute;
  top: 40px;
  left: 0;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  z-index: 9999;
  min-width: 140px;
  padding: 4px 0;
}

.filter-menu button {
  width: 100%;
  border: none;
  background: none;
  padding: 8px 15px;
  text-align: left;
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

.filter-menu button:hover {
  background: #f5f5f5;
}
.app {
    display: grid;
    grid-template-columns: 280px auto;
    grid-template-rows: 72px auto;
    height: 100vh;
    /* overflow: ; */
}

.sidebar {
    grid-row: 1 / span 2;
    height: 100%;
    overflow-y: auto;
}

.header {
    grid-column: 2;
    height: 70px;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 10px 20px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.main {
    grid-column: 2;
    overflow-y: auto;
    padding: 20px;
    background: #f7f8fc;
    height: calc(100vh - 70px);
}


/* ---------------------------
   MODERN USER VIEW MODAL STYLE
---------------------------- */

#viewModal .modal-content {
    background: #ffffff;
    padding: 25px;
    border-radius: 16px;
    box-shadow: 0 8px 25px rgba(0,0,0,0.15);
    max-width: 520px;
    margin: auto;
    border: none;
}

#viewModal .modal-header {
    border-bottom: none;
    margin-bottom: 10px;
}

#viewModal .modal-title {
    font-size: 22px;
    font-weight: 700;
    color: #003A91;
}

#viewModal .modal-body {
    padding: 10px 5px 20px;
}

/* USER INFO STYLE */
#viewBody {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 14px 20px;
}

#viewBody p {
    margin: 0;
    padding: 10px 12px;
    background: #f7f9fc;
    border-radius: 10px;
    font-size: 15px;
    color: #1E2A39;
    border-left: 4px solid #0052CC;
    display: flex;
    flex-direction: column;
}

#viewBody strong {
    font-size: 13px;
    color: #003A91;
    margin-bottom: 3px;
}

/* Close BTN */
#viewModal .btn-close {
    background: transparent;
    opacity: 1;
    font-size: 18px;
}

/* Footer */
#viewModal .modal-footer {
    border-top: none;
    padding-top: 0;
}

/* ---------------------------
   RESPONSIVE
---------------------------- */
@media (max-width: 480px) {
    #viewBody {
        grid-template-columns: 1fr; /* 1 column on mobile */
    }
}




</style>
</head>
<body>

 <div class="app" id="app">
       <!-- Sidebar -->
        <?php include 'asidebar.php'; ?>
     <!-- Header -->
     <?php include 'header.php';?>
      <!-- MAin Content -->
    <main class="main">
    <div class="table-header">
    <h3 style="font-weight:600;">All Users</h3>
    <div class="table-actions">
      <div class="table-search">
        <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
        <input type="text" placeholder="Search users…" id="tableSearch">
      </div>
      <!-- FILTER BUTTON WITH DROPDOWN -->
<!-- ✅ Filter Button -->
<!-- Filter Button -->
<div class="filter-container" style="position: relative; display:inline-block;">
    <button id="filterBtn" class="btn btn-sm btn-secondary">
        <i class="fa-solid fa-filter"></i> Filter
    </button>

    <!-- Hidden dropdown for filter options -->
    <div id="filterOptions" class="dropdown-menu" style="display:none; position:absolute; top:35px; left:0; background:#fff; border:1px solid #ccc; border-radius:5px; padding:8px; min-width:120px; box-shadow:0 2px 6px rgba(0,0,0,0.1); z-index:100;">
        <a href="?filter=user" class="dropdown-item" style="display:block; padding:5px 10px; color:#333; text-decoration:none;">User</a>
        <a href="?filter=agent" class="dropdown-item" style="display:block; padding:5px 10px; color:#333; text-decoration:none;">Agent</a>
    </div>
</div>


      <!-- <button class="btn btn-sm btn-secondary"><i class="fa-solid fa-filter"></i> Filter</button> -->
      <button class="btn btn-sm btn-secondary"><i class="fa-solid fa-download"></i> Export</button>
    </div>
  </div>
        <!-- <?php if(isset($_GET['msg'])): ?>
            <p style="color:green;"><?= htmlspecialchars($_GET['msg']); ?></p>
        <?php endif; ?> -->

        <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Full Name</th>
                    <th>Email</th>
                    <th>Terms</th>
                    <th>Logins</th>
                    <th>Type</th>
                    <th>Allow</th>
                    <!-- <th>Email</th> -->
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if($users): $n=1; foreach($users as $u): ?>
                <tr>
                    <td><?= $n++; ?></td>
                    <td><?= htmlspecialchars($u['fullname']); ?></td>
                    <td><?= htmlspecialchars($u['email']); ?></td>
                    <td><?= htmlspecialchars($u['filter']); ?></td>
                    <td><?= $u['terms'] ? 'Yes' : 'No'; ?></td>
                    <td><?= intval($u['login_count']); ?></td>
                     <td>
                         <label class="switch">
              <input type="checkbox" <?= $u['allow'] ? 'checked' : ''; ?> onchange="toggleAllow(<?= $u['id']; ?>, this.checked)">
              <span class="slider"></span>
            </label>
                    </td>
                    <td>
            <button class="btn btn-info" onclick='viewUser(<?= json_encode($u); ?>)'><i class="fa-solid fa-eye"></i></button>
            <button class="btn btn-primary" onclick='editUser(<?= json_encode($u); ?>)'><i class="fa-solid fa-pen"></i></button>
            <form method="POST" style="display:inline;">
              <input type="hidden" name="id" value="<?= $u['id']; ?>">
              <button class="btn btn-danger" name="delete_user" onclick="return confirm('Delete this user?')"><i class="fa-solid fa-trash"></i></button>
            </form>
          </td>
                </tr>
            <?php endforeach; else: ?>
                <tr><td colspan="7" style="text-align:center;">No users found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
        </div>

<div class="modal" id="viewModal">
  <div class="modal-content">
    <span class="close-x" onclick="closeModal('viewModal')">&times;</span>
    <h3 style="color: black;">User Details</h3>
    <div id="viewBody"></div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('viewModal')">Close</button>
    </div>
  </div>
</div>






        <!-- EDIT MODAL -->
     <div class="modal" id="editModal">
  <div class="modal-content">
    <span class="close-x" onclick="closeModal('editModal')">&times;</span>
    <h3 style="color: black;">Edit User</h3>
    <form id="editForm" method="post">
      <input type="hidden" name="user_id" id="edit_id">
      <label style="color: black;">Full Name</label><br>
      <input type="text" name="fullname" id="edit_fullname" required style="width:100%;margin-bottom:8px;"><br>
      <label style="color: black;">Email</label><br>
      <input type="email" name="email" id="edit_email" required style="width:100%;margin-bottom:8px;"><br>
      <label style="color: black;">New Password (optional)</label><br>
      <input style="color: black;" type="password" name="new_password" id="edit_password" style="width:100%;margin-bottom:8px;"><br>
      <label style="color: black;"><input type="checkbox" name="terms" id="edit_terms"> Agreed to Terms</label><br>
      <div class="modal-footer">
        <button type="submit" name="update_user" class="btn btn-info">Update</button>
      </div>
    </form>
  </div>
</div>

        <!-- DELETE MODAL -->
        <div id="deleteModal" class="modal">
            <div class="modal-content">
                <span class="close" onclick="closeModal('deleteModal')">&times;</span>
                <h2>Confirm Delete</h2>
                <p>Are you sure you want to delete this job?</p>
                <button id="confirmDeleteBtn">Yes, Delete</button>
                <button onclick="closeModal('deleteModal')">Cancel</button>
            </div>
        </div>
    </main>













</div>

<!-- ===== VIEW MODAL ===== -->
<div class="modal" id="viewModal">
  <div class="modal-content">
    <span class="close-x" onclick="closeModal('viewModal')">&times;</span>
    <h3 style="color: black;">User Details</h3>
    <div id="viewBody"></div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('viewModal')">Close</button>
    </div>
  </div>
</div>

<!-- ===== EDIT MODAL ===== -->
<div class="modal" id="editModal">
  <div class="modal-content modal-card">
    <span class="close-x close-icon" onclick="closeModal('editModal')">&times;</span>
    <h3 class="modal-title">Edit User</h3>
    <form id="editForm" method="post" class="modal-form">
      <input type="hidden" name="user_id" id="edit_id">

      <label class="modal-label">Full Name</label>
      <input type="text" name="fullname" id="edit_fullname" required class="modal-input input-primary">

      <label class="modal-label">Email</label>
      <input type="email" name="email" id="edit_email" required class="modal-input input-primary">

      <label class="modal-label">New Password (optional)</label>
      <input type="password" name="new_password" id="edit_password" class="modal-input input-primary">

      <label class="modal-checkbox">
        <input type="checkbox" name="terms" id="edit_terms" class="input-checkbox"> Agreed to Terms
      </label>

      <div class="modal-footer">
        <button type="submit" name="update_user" class="btn btn-info primary-btn action-btn">Update</button>
        <button type="button" class="btn btn-secondary secondary-btn action-btn" onclick="closeModal('editModal')">Cancel</button>
      </div>
    </form>
  </div>
</div>


<script>
function openModal(id){ document.getElementById(id).classList.add('open'); }
function closeModal(id){ document.getElementById(id).classList.remove('open'); }

   const searchInput = document.getElementById('tableSearch');
    const table = document.querySelector('table tbody');

    searchInput.addEventListener('keyup', function() {
        const filter = searchInput.value.toLowerCase();
        const rows = table.querySelectorAll('tr');

        rows.forEach(row => {
            // Get the email column (7th column, index 6)
            const emailCell = row.cells[2];
            if (emailCell) {
                const emailText = emailCell.textContent.toLowerCase();
                row.style.display = emailText.includes(filter) ? '' : 'none';
            }
        });
    });

function viewUser(u){
  document.getElementById('viewBody').innerHTML = `
    <p><strong><i class="fa-solid fa-id-card"></i> ID</strong> ${u.id}</p>
    <p><strong><i class="fa-solid fa-user"></i> Name</strong> ${u.fullname}</p>
    <p><strong><i class="fa-solid fa-envelope"></i> Email</strong> ${u.email}</p>
    <p><strong><i class="fa-solid fa-file-contract"></i> Terms</strong> ${u.terms == 1 ? 'Agreed' : 'Not Agreed'}</p>
    <p><strong><i class="fa-solid fa-check-circle"></i> Allow</strong> ${u.allow == 1 ? 'Allowed' : 'Not Allowed'}</p>
    <p><strong><i class="fa-solid fa-right-to-bracket"></i> Login Count</strong> ${u.login_count}</p>
  `;
  openModal('viewModal');
}


function editUser(u){
  document.getElementById('edit_id').value = u.id;
  document.getElementById('edit_fullname').value = u.fullname;
  document.getElementById('edit_email').value = u.email;
  document.getElementById('edit_password').value = '';
  document.getElementById('edit_terms').checked = (u.terms == 1);
  openModal('editModal');
}

function toggleAllow(id, checked){
  const status = checked ? 1 : 0;
  fetch('', {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: `toggle_allow=1&id=${id}&status=${status}`
  }).then(res => res.text()).then(res => {
    if(res === 'success'){
      console.log('Allow status updated for user ID', id);
    }
  });
}




// Toggle dropdown visibility
document.getElementById("filterBtn").addEventListener("click", function (event) {
    event.preventDefault();
    const menu = document.getElementById("filterOptions");
    menu.style.display = menu.style.display === "none" ? "block" : "none";
});

// Hide dropdown when clicking outside
document.addEventListener("click", function (event) {
    const menu = document.getElementById("filterOptions");
    const btn = document.getElementById("filterBtn");
    if (!btn.contains(event.target) && !menu.contains(event.target)) {
        menu.style.display = "none";
    }
});

</script>

</body>
</html>
