<?php
session_start();
if (!isset($_SESSION['role_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');

$user_role = $_SESSION['role_id'];
$user_store_id = $_SESSION['store_id'] ?? 0;

// Helper: log errors
function logError($conn, $message) {
    $uid = $_SESSION['user_id'] ?? null;
    $stmt = $conn->prepare("INSERT INTO error_log (message, user_id) VALUES (?, ?)");
    $stmt->bind_param("si", $message, $uid);
    $stmt->execute();
    $stmt->close();
}

// Capture toast messages
$successMsg = $_GET['success'] ?? '';
$errorMsg = $_GET['error'] ?? '';
if ($errorMsg) logError($conn, $errorMsg);

// Pagination settings
$limit = 15;
$page = max(1, intval($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

// Filters & Sorting
$filterRole = intval($_GET['role_id'] ?? 0);
$filterStore = intval($_GET['store_id'] ?? 0);
$sortBy = in_array($_GET['sort'] ?? '', ['username','email','role_name','store_name','last_logged_in']) ? $_GET['sort'] : 'username';
$sortDir = ($_GET['dir'] ?? '') === 'desc' ? 'DESC' : 'ASC';

// Adjust filters based on role
$conds = [];
$params = []; $types = '';
if ($user_role == 2) {
    $conds[] = 'u.store_id = ?';
    $params[] = $user_store_id;
    $types .= 'i';
} elseif ($filterStore) {
    $conds[] = 'u.store_id = ?';
    $params[] = $filterStore;
    $types .= 'i';
}
if ($filterRole) {
    $conds[] = 'u.role_id = ?';
    $params[] = $filterRole;
    $types .= 'i';
}

$where = $conds ? 'WHERE ' . implode(' AND ', $conds) : '';

// Count total
$totalSql = "SELECT COUNT(*) FROM users u $where";
$stmt = $conn->prepare($totalSql);
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$stmt->bind_result($totalRows);
$stmt->fetch();
$stmt->close();
$totalPages = ceil($totalRows / $limit);

// Fetch users
$params[] = $limit;
$params[] = $offset;
$bindTypes = $types . "ii";
$sql = "
    SELECT u.*, r.role_name, s.store_name
    FROM users u
    JOIN roles r ON u.role_id = r.id
    JOIN stores s ON u.store_id = s.id
    $where
    ORDER BY $sortBy $sortDir
    LIMIT ? OFFSET ?
";
$stmt = $conn->prepare($sql);
$stmt->bind_param($bindTypes, ...$params);
$stmt->execute();
$users = $stmt->get_result();
$stmt->close();

// Fetch filter dropdowns
$roles = $conn->query("SELECT id, role_name FROM roles ORDER BY role_name");
$stores = $conn->query("SELECT id, store_name FROM stores ORDER BY store_name");
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>User Management – Digital POS</title>
<link rel="stylesheet" href="../../css/dashboard.css"/>
<style>
        body, html {
            margin: 0; padding: 0;
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
            min-height: 100vh;
            overflow-x: hidden;
        }
        .overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: -1;
        }
        .content {
            margin: 100px auto 40px auto;
            padding: 30px 40px;
            max-width: 1200px;
            backdrop-filter: blur(15px);
            background: rgba(255, 255, 255, 0.08);
            border-radius: 20px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
        }
        .alert {
            margin-bottom: 20px;
            padding: 12px 18px;
            border-radius: 10px;
            text-align: center;
            font-weight: bold;
        }
        .alert.success { background-color: #2e7d32cc; color: #d0f0c0; }
        .alert.error { background-color: #ff4444cc; color: #ffecec; }
        h2 {
            text-align: center;
            margin-bottom: 30px;
            font-size: 1.8rem;
        }
        .user-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            flex-wrap: wrap;
            gap: 12px;
        }
        .user-controls input[type="text"] {
            padding: 10px;
            width: 280px;
            border-radius: 10px;
            border: none;
            outline: none;
            background: rgba(255,255,255,0.1);
            color: white;
            box-shadow: inset 0 0 5px rgba(255,255,255,0.2);
        }
        .add-user {
            background: #ff6f00;
            color: white;
            padding: 10px 18px;
            border: none;
            border-radius: 25px;
            font-weight: bold;
            cursor: pointer;
            transition: background 0.3s;
        }
        .add-user:hover {
            background: #e65c00;
        }
        .user-table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(0,0,0,0.3);
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 0 12px rgba(0,0,0,0.6);
        }
        .user-table th, .user-table td {
            padding: 14px 16px;
            text-align: left;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            font-size: 0.95rem;
        }
        .user-table th {
            background: rgba(255,111,0,0.9);
        }
        .user-table img {
            width: 40px;
            height: 40px;
            object-fit: cover;
            border-radius: 50%;
            border: 2px solid rgba(255,111,0,0.7);
        }
        .actions button {
            margin-right: 5px;
            padding: 6px 12px;
            font-size: 13px;
            cursor: pointer;
            border: none;
            border-radius: 6px;
            transition: background 0.3s ease;
        }
        .actions .edit {
            background-color: #66b2ff;
            color: white;
        }
        .actions .edit:hover {
            background-color: #3399ff;
        }
        .actions .delete {
            background-color: #ff4d4d;
            color: white;
        }
        .actions .delete:hover {
            background-color: #e60000;
        }
        .actions .reset {
            background-color: #ffa500;
            color: white;
        }
        .actions .reset:hover {
            background-color: #e69500;
        }
        @media (max-width: 768px) {
            .user-controls {
                flex-direction: column;
                align-items: flex-start;
            }
            .user-controls input[type="text"] {
                width: 100%;
            }
            .user-table th, .user-table td {
                font-size: 13px;
                padding: 10px;
            }
            .user-table img {
                width: 30px;
                height: 30px;
            }
        }

        #toast {
            visibility: hidden;
            min-width: 250px;
            margin-left: -125px;
            background-color: #333;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 16px;
            position: fixed;
            z-index: 9999;
            left: 50%;
            bottom: 30px;
            font-size: 16px;
            opacity: 0;
            transition: opacity 0.5s ease, bottom 0.5s ease;
        }

        #toast.show {
            visibility: visible;
            opacity: 1;
            bottom: 50px;
        }

        .export-btn {
            background: #00b894;
            padding: 10px 16px;
            border: none;
            color: white;
            border-radius: 6px;
            cursor: pointer;
            font-weight: bold;
        }

        .pagination {
            margin-top: 20px;
            text-align: center;
        }

        .pagination button {
            background: #ff6f00;
            border: none;
            color: white;
            padding: 8px 14px;
            margin: 2px;
            border-radius: 6px;
            cursor: pointer;
        }

        .pagination button.active {
            background: #e65c00;
            font-weight: bold;
        }
.actions .idcard {
    background-color: #ff9800;
    color: white;
}
.actions .idcard:hover {
    background-color: #e68a00;
}

/* Additional toast styles */
    #toast {
      position: fixed; top: 20px; right: 20px;
      min-width: 240px;
      padding: 12px 20px;
      border-radius: 8px;
      font-weight: bold;
      box-shadow: 0 4px 8px rgba(0,0,0,0.4);
      display: none;
      z-index: 999;
    }
    #toast.success { background: #4caf50; color: white; }
    #toast.error { background: #f44336; color: white; }
    /* Sort icons */
    th.sortable { cursor: pointer; }
    th.sortable:after { content: ' ↕'; font-size: .8em; color: #ddd; }
    th.sortable.asc:after { content: ' ↑'; }
    th.sortable.desc:after { content: ' ↓'; }
</style>
</head>
<body>
<div id="toast"></div>
<div class="content">
  <h2>User Management</h2>

  <div class="user-controls">
    <div>
      <select id="filterRole" <?= $user_role == 2 ? 'disabled' : '' ?>>
        <option value="0">All Roles</option>
        <?php while ($r = $roles->fetch_assoc()): ?>
          <option value="<?= $r['id'] ?>" <?= $filterRole == $r['id'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($r['role_name']) ?>
          </option>
        <?php endwhile; ?>
      </select>

      <?php if ($user_role == 1): ?>
        <select id="filterStore">
          <option value="0">All Stores</option>
          <?php while ($s = $stores->fetch_assoc()): ?>
            <option value="<?= $s['id'] ?>" <?= $filterStore == $s['id'] ? 'selected' : '' ?>>
              <?= htmlspecialchars($s['store_name']) ?>
            </option>
          <?php endwhile; ?>
        </select>
      <?php else: ?>
        <input type="hidden" id="filterStore" value="<?= $user_store_id ?>">
        <span><strong>Store:</strong> <?= htmlspecialchars($stores->fetch_assoc()['store_name'] ?? '') ?></span>
      <?php endif; ?>

      <button onclick="applyFilters()" <?= $user_role == 2 ? 'disabled' : '' ?>>Apply Filters</button>
    </div>

    <?php if ($user_role == 1): ?>
      <div>
        <button onclick="location.href='add_user.php'">Add New User</button>
        <button onclick="location.href='export_users_pdf.php?<?= http_build_query($_GET) ?>'">Export PDF</button>
      </div>
    <?php endif; ?>
  </div>

  <table class="user-table">
    <thead>
      <tr>
        <?php
        $columns = ['id'=>'ID','username'=>'Username','email'=>'Email','role_name'=>'Role','store_name'=>'Store','last_logged_in'=>'Last Login'];
        foreach ($columns as $col => $label):
          $dirToggle = ($sortBy==$col && strtoupper($sortDir)=='ASC') ? 'desc' : 'asc';
          $cls = 'sortable' . ($sortBy==$col ? ' ' . strtolower($sortDir) : '');
        ?>
        <th class="<?= $cls ?>" data-col="<?= $col ?>" data-dir="<?= $dirToggle ?>"><?= $label ?></th>
        <?php endforeach; ?>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <?php if ($users->num_rows): while ($u = $users->fetch_assoc()): ?>
      <tr>
        <td><?= $u['id'] ?></td>
        <td><?= htmlspecialchars($u['username']) ?></td>
        <td><?= htmlspecialchars($u['email']) ?></td>
        <td><?= htmlspecialchars($u['role_name']) ?></td>
        <td><?= htmlspecialchars($u['store_name']) ?></td>
        <td><?= $u['last_logged_in'] ? date("d M Y H:i", strtotime($u['last_logged_in'])) : '-' ?></td>
        <td class="actions">
          <?php if ($user_role == 1): ?>
            <button onclick="location.href='edit_user.php?id=<?= $u['id'] ?>'">Edit</button>
            <button onclick="deleteUser(<?= $u['id'] ?>)">Delete</button>
            <button onclick="resetPassword(<?= $u['id'] ?>)">Reset</button>
            <button onclick="getIdCard(<?= $u['id'] ?>)">Get ID</button>
          <?php else: ?>
            <span style="color: #aaa;">View Only</span>
          <?php endif; ?>
        </td>
      </tr>
      <?php endwhile; else: ?>
      <tr><td colspan="7" style="text-align:center;">No users found.</td></tr>
      <?php endif; ?>
    </tbody>
  </table>

  <div class="pagination">
    <?php for ($p=1; $p <= $totalPages; $p++): ?>
      <a href="?<?= http_build_query(array_merge($_GET, ['page'=>$p])) ?>"
         style="<?= $p==$page ? 'font-weight:bold;text-decoration:underline;' : '' ?>">
        <?= $p ?>
      </a>
    <?php endfor; ?>
  </div>
</div>

<?php include('../../includes/footer.php'); ?>

<script>
// Toast
function showToast(msg, type='success') {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.className = type;
  t.style.display = 'block';
  setTimeout(()=> t.style.display='none', 3000);
}
<?php if ($successMsg): ?> showToast("<?= addslashes($successMsg) ?>",'success'); <?php endif; ?>
<?php if ($errorMsg): ?> showToast("<?= addslashes($errorMsg) ?>",'error'); <?php endif; ?>

// Sorting
document.querySelectorAll('th.sortable').forEach(th => {
  th.addEventListener('click', () => {
    const col = th.dataset.col, dir = th.dataset.dir;
    const ps = new URLSearchParams(window.location.search);
    ps.set('sort', col);
    ps.set('dir', dir);
    ps.set('page', 1);
    window.location.search = ps.toString();
  });
});

// Filters
function applyFilters(){
  const ps = new URLSearchParams(window.location.search);
  ps.set('role_id', document.getElementById('filterRole').value);
  ps.set('store_id', document.getElementById('filterStore').value);
  ps.set('page',1);
  window.location.search = ps.toString();
}

// AJAX actions (only for admin)
async function deleteUser(id) {
  if (!confirm('Delete this user?')) return;
  const r = await fetch('delete_user.php', {
    method: 'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body: `id=${id}`
  });
  const d = await r.json();
  d.success ? showToast(d.message,'success') : showToast(d.message||'Action failed','error');
}

async function resetPassword(id) {
  if (!confirm('Reset password?')) return;
  const r = await fetch('reset_password.php', {
    method: 'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({id})
  });
  const d = await r.json();
  d.success ? showToast(d.message,'success') : showToast(d.message||'Action failed','error');
}

function getIdCard(id) {
  window.open(`user_id_card.php?id=${id}`, '_blank');
}
</script>
</body>
</html>
