<?php
session_start();
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../config/send_email.php';

// Only admin can access
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../../auth/login.php");
    exit;
}

$username = $_SESSION['username'];
$role = $_SESSION['role'];

// CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Handle deletion
if (isset($_GET['delete_id'], $_GET['token']) && $_GET['token'] === $_SESSION['csrf_token']) {
    $delete_id = (int)$_GET['delete_id'];
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$delete_id]);
    $user_to_delete = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user_to_delete) {
        $del = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $del->execute([$delete_id]);

        // Notify systems
        $subject = "User Deleted: {$user_to_delete['username']}";
        $body = "<p>User <b>{$user_to_delete['full_name']}</b> (Username: {$user_to_delete['username']}) was deleted by {$username} (Admin).</p>";
        send_email('systems@digivortlimited.com', 'Systems Team', $subject, $body);

        $_SESSION['success'] = "User '{$user_to_delete['username']}' deleted successfully.";
        header("Location: ../users/");
        exit;
    }
}

// Pagination
$limit = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;

$total_stmt = $pdo->query("SELECT COUNT(*) FROM users");
$total_users = $total_stmt->fetchColumn();
$total_pages = ceil($total_users / $limit);

$stmt = $pdo->prepare("SELECT * FROM users ORDER BY created_at DESC LIMIT :limit OFFSET :offset");
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage Users - Custora CRM</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="../assets/img/custora_logo.png" type="image/png">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<style>
:root{
  --bg:#f4f7fa;--card-bg:rgba(173,216,230,0.35);
  --accent:#005f8d;--muted:#666;--text:#1b2430;--white:#fff;
}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:Inter,"Segoe UI",Roboto,Arial,sans-serif;background:var(--bg);color:var(--text);}
a{text-decoration:none;color:inherit;}
.app{display:flex;min-height:100vh;}
.sidebar{width:250px;background:skyblue;color:#003547;position:fixed;left:0;top:0;height:100vh;overflow:auto;z-index:100;transition:.3s;}
.sidebar .logo{text-align:center;margin:15px 0;}
.sidebar .logo img{width:180px;height:auto; margin-top:20px;}
.nav{margin-top:12px;padding-left:6px;}
.nav a{display:block;padding:10px 12px;color:#003547;border-radius:8px;margin-bottom:6px;font-weight:600;}
.nav a:hover{background:rgba(255,255,255,0.8);box-shadow:0 2px 6px rgba(0,0,0,0.06);}
.footer-note{text-align:center;font-size:13px;padding:10px;color:var(--muted);}
.main{margin-left:260px;padding:20px;width:100%;transition:margin-left .25s;}
.header{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;margin-bottom:10px;}
.header-left{display:flex;align-items:center;gap:10px;}
.hamburger{display:none;background:var(--accent);color:white;padding:9px 11px;border-radius:8px;cursor:pointer;}
.title{font-weight:700;font-size:1.1rem;color:#0b66d1;}
.controls{display:flex;align-items:center;gap:10px;}
button#darkToggle{padding:8px 10px;border:none;border-radius:8px;background:var(--card-bg);cursor:pointer;}
.message{padding:10px;border-radius:6px;margin:10px 0;}
.success{background:#d4edda;color:#155724;}
.error{background:#f8d7da;color:#721c24;}
.add{background:var(--accent);color:white;padding:10px 15px;border-radius:8px;margin-top:10px;display:inline-block;}
.add:hover{background:#1f6391;}
.table-wrapper{overflow-x:auto;box-shadow:0 3px 8px rgba(0,0,0,0.06);border-radius:12px;margin-top:10px;}
table{width:100%;border-collapse:collapse;background:white;min-width:700px;}
th,td{padding:12px 15px;text-align:left;border-bottom:1px solid #ddd;}
th{background:var(--accent);color:white;position:sticky;top:0;z-index:2;}
tr:hover{background:#f1f1f1;}
.actions a{padding:6px 10px;border-radius:5px;margin:2px;color:white;font-size:0.85rem;display:inline-block;}
.actions .edit{background:#007BFF;}
.actions .delete{background:red;}
.pagination{text-align:center;margin-top:15px;}
.pagination a{margin:0 5px;padding:8px 12px;color:#1f6391;border-radius:5px;}
.pagination a.active{background:var(--accent); color:white;}
.pagination a:hover{background:#1f6391; color: gold;}

/* Responsive */
@media(max-width:768px){
  .sidebar{transform:translateX(-280px);position:fixed;}
  .sidebar.active{transform:translateX(0);}
  .main{margin-left:0;padding:12px;}
  .hamburger{display:inline-block;}
  .actions a{display:block;width:100%;margin-bottom:4px;}
  .add{width:100%;text-align:center;}
}

/* Dark mode */
body.dark{--bg:#081014;--card-bg:rgba(255,255,255,0.04);--accent:#1fb6ff;--muted:#9aa6af;--text:#e6f2f6;--white:#0a0a0a;}
body.dark .sidebar{background:linear-gradient(180deg,#0b2b33,#072024);color:#bfeafc;}
body.dark .nav a{color:#bfeafc;}
body.dark .title{color:#072024;background:linear-gradient(90deg,#1fb6ff,#167dbf);padding:6px 10px;border-radius:8px;}
body.dark table{background:#071217;color:#cfeffb;}
</style>
</head>
<body>
<div class="app">
  <aside class="sidebar" id="sidebar">
    <div class="logo"><img src="../assets/img/custora_logo.png" alt="Custora Logo"></div>
    <nav class="nav">
      <a href="../"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
      <a href="../projects/"><i class="fas fa-project-diagram"></i> Manage Projects</a>
      <a href="../users/"><i class="fas fa-users-cog"></i> Manage Users</a>
      <a href="../issues/"><i class="fas fa-exclamation-circle"></i> All Issues</a>
      <a href="../profile/"><i class="fas fa-user"></i> My Profile</a>
      <a href="../../auth/logout.php" style="color:#b31b1b;"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </nav>
    <div class="footer-note">&copy; <?= date('Y') ?> Digital Vortex Technologies</div>
  </aside>

  <main class="main" id="main">
    <div class="header">
      <div class="header-left">
        <div class="hamburger" id="hamburger" onclick="toggleSidebar()">☰</div>
        <div class="title">Users</div>
      </div>
      <div class="controls">
        <div style="text-align:right;">
          <div style="font-size:0.95rem;color:var(--muted)">Welcome, <strong><?= htmlspecialchars($username) ?></strong></div>
          <div style="font-size:0.82rem;color:var(--muted)">Role: <?= htmlspecialchars($role) ?></div>
        </div>
        <button id="darkToggle" title="Toggle dark mode"><span id="darkLabel">Dark</span></button>
      </div>
    </div>

    <?php if (isset($_SESSION['success'])): ?>
      <div class="message success"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div>
    <?php endif; ?>

    <a href="create.php" class="add"><i class="fas fa-user-plus"></i> Add New User</a>

    <div class="table-wrapper">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Full Name</th>
            <th>Username</th>
            <th>Email</th>
            <th>Role</th>
            <th>Status</th>
            <th>Created At</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php if ($users): foreach ($users as $user): ?>
          <tr>
            <td><?= $user['id'] ?></td>
            <td><?= htmlspecialchars($user['full_name']) ?></td>
            <td><?= htmlspecialchars($user['username']) ?></td>
            <td><?= htmlspecialchars($user['email']) ?></td>
            <td><?= htmlspecialchars($user['role']) ?></td>
            <td><?= htmlspecialchars($user['status']) ?></td>
            <td><?= $user['created_at'] ?></td>
            <td class="actions">
              <a href="edit.php?id=<?= $user['id'] ?>" class="edit"><i class="fas fa-edit"></i> Edit</a>
              <a href="?delete_id=<?= $user['id'] ?>&token=<?= $_SESSION['csrf_token'] ?>" class="delete" onclick="return confirm('Are you sure you want to delete this user?');">
                <i class="fas fa-trash-alt"></i> Delete
              </a>
            </td>
          </tr>
        <?php endforeach; else: ?>
          <tr><td colspan="8">No users found.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>

    <?php if ($total_pages > 1): ?>
        <div class="pagination">
          <?php for ($i = 1; $i <= $total_pages; $i++): ?>
            <a href="?page=<?= $i ?>" class="<?= $i == $page ? 'active' : '' ?>"><?= $i ?></a>
          <?php endfor; ?>
        </div>
    <?php endif; ?>
  </main>
</div>

<script>
function toggleSidebar(){
  document.getElementById('sidebar').classList.toggle('active');
}
document.addEventListener('click',function(e){
  const sidebar=document.getElementById('sidebar'),hamburger=document.getElementById('hamburger');
  if(window.innerWidth<=768 && sidebar.classList.contains('active')){
    if(!sidebar.contains(e.target)&& e.target!==hamburger){sidebar.classList.remove('active');}
  }
});
(function(){
  const body=document.body,toggle=document.getElementById('darkToggle'),label=document.getElementById('darkLabel');
  if(localStorage.getItem('custora_dark')==='1'){body.classList.add('dark');label.textContent='Light';}
  toggle.addEventListener('click',()=>{
    body.classList.toggle('dark');
    localStorage.setItem('custora_dark',body.classList.contains('dark')?'1':'0');
    label.textContent=body.classList.contains('dark')?'Light':'Dark';
  });
})();
</script>
</body>
</html>