<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/functions.php';

// Session timeout
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 900)) {
    session_unset();
    session_destroy();
    header("Location: ../auth/login.php");
    exit;
}
$_SESSION['last_activity'] = time();

// Fetch users with site name
$stmt = $pdo->query("
  SELECT users.*, sites.site_name 
  FROM users 
  LEFT JOIN sites ON users.site_id = sites.id 
  ORDER BY users.id DESC
");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch active sites for dropdown
$siteStmt = $pdo->query("SELECT id, site_name FROM sites WHERE status = 'active' ORDER BY site_name");
$sites = $siteStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Manage Users | CFS System OS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
  <style>
    body { font-size: 0.9rem; }
    table#userTable th, table#userTable td { font-size: 0.85rem; vertical-align: middle; }
    .form-control { font-size: 0.85rem; padding: 0.3rem 0.5rem; }
    .btn { font-size: 0.8rem; padding: 0.25rem 0.5rem; }
    .modal-title { font-size: 1rem; }
    .modal-body input, .modal-body select { font-size: 0.85rem; }
  </style>
</head>
<body class="hold-transition sidebar-mini">

  <?php include '../includes/topbar.php'; ?>
  <?php include '../includes/sidebar.php'; ?>

<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid d-flex justify-content-between align-items-center">
            <h4 class="mb-0">🤵 Manage Users</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
                <i class="fas fa-plus-circle"></i> Add New User
            </button>
        </div>
    </div>

    <div class="content">    
      <div class="card-body table-responsive">
        <table id="userTable" class="table table-bordered table-striped text-sm">
        <thead class="table-dark">
          <tr>
            <th>ID</th>
            <th>Photo</th>
            <th>Username</th>
            <th>Role</th>
            <th>Email</th>
            <th>Contact</th>
            <th>Site</th>
            <th>Employment</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($users as $user): ?>
          <tr>
            <td><?= htmlspecialchars($user['id']) ?></td>
            <td>
              <?php if (!empty($user['profile_image'])): ?>
                <img src="../uploads/users/<?= htmlspecialchars($user['profile_image']) ?>" alt="Profile" style="width:40px; height:40px; object-fit:cover; border-radius:50%;">
              <?php else: ?>
                <span class="text-muted">No Image</span>
              <?php endif; ?>
            </td>
            <td><?= htmlspecialchars($user['username']) ?></td>
            <td><?= htmlspecialchars(ucfirst($user['role'])) ?></td>
            <td><?= htmlspecialchars($user['email']) ?></td>
            <td><?= htmlspecialchars($user['contact'] ?? '') ?></td>
            <td><?= htmlspecialchars($user['site_name'] ?? '') ?></td>
            <td><?= htmlspecialchars($user['employment_status'] ?? '') ?></td>
            <td><?= htmlspecialchars($user['status'] ?? '') ?></td>
            <td>
              <button class="btn btn-sm btn-warning editUserBtn"
                      data-id="<?= $user['id'] ?>"
                      data-username="<?= htmlspecialchars($user['username']) ?>"
                      data-role="<?= htmlspecialchars($user['role']) ?>"
                      data-email="<?= htmlspecialchars($user['email']) ?>"
                      data-contact="<?= htmlspecialchars($user['contact'] ?? '') ?>"
                      data-site_id="<?= htmlspecialchars($user['site_id'] ?? '') ?>"
                      data-employment="<?= htmlspecialchars($user['employment_status'] ?? '') ?>"
                      data-status="<?= htmlspecialchars($user['status'] ?? '') ?>"
                      data-bs-toggle="modal" data-bs-target="#editUserModal">
                <i class="fas fa-edit"></i> Edit
              </button>
              <a href="delete_user.php?id=<?= $user['id'] ?>&csrf_token=<?= generateCSRFToken('delete_user'); ?>"
                 class="btn btn-sm btn-danger"
                 onclick="return confirm('Are you sure?')">
                <i class="fas fa-trash"></i> Delete
              </a>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
</div>

  
  <?php include '../includes/toast.php'; ?>

  <!-- Add User Modal -->
  <div class="modal fade" id="addUserModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <form method="POST" action="add_user.php" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?= generateCSRFToken('add_user'); ?>">
        <div class="modal-content">
          <div class="modal-header bg-primary text-white">
            <h5 class="modal-title">Add New User</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <input type="text" name="username" class="form-control mb-2" placeholder="Username" required>
            <input type="email" name="email" class="form-control mb-2" placeholder="Email" required>
            <input type="text" name="contact" class="form-control mb-2" placeholder="Contact">
            <select name="site_id" class="form-control mb-2">
              <option value="">Select Site</option>
              <?php foreach ($sites as $site): ?>
                <option value="<?= $site['id'] ?>"><?= htmlspecialchars($site['site_name']) ?></option>
              <?php endforeach; ?>
            </select>
            <select name="employment_status" class="form-control mb-2" required>
            <option value="Full-Time">Full-Time</option>
            <option value="Part-Time">Part-Time</option>
            <option value="Ad-Hoc">Ad-Hoc</option>
            </select>
            <select name="status" class="form-control mb-2" required>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
            <select name="role" class="form-control mb-2" required>
              <option value="admin">Admin</option>
              <option value="controller">Controller</option>
              <option value="HR">HR</option>
              <option value="supervisor">Supervisor</option>
              <option value="officer">Officer</option>
            </select>
            <input type="password" name="password" class="form-control mb-2" placeholder="Password" required>
            <input type="file" name="profile_image" class="form-control mb-2">
          </div>
          <div class="modal-footer">
            <button type="submit" class="btn btn-success">Add User</button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- Edit User Modal -->
  <div class="modal fade" id="editUserModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <form method="POST" action="update_user.php" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?= generateCSRFToken('edit_user'); ?>">
        <input type="hidden" name="id" id="editUserId">
        <div class="modal-content">
          <div class="modal-header bg-warning text-dark">
            <h5 class="modal-title">Edit User</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <input type="text" name="username" id="editUsername" class="form-control mb-2" required>
            <input type="email" name="email" id="editEmail" class="form-control mb-2" required>
            <input type="text" name="contact" id="editContact" class="form-control mb-2">
            <select name="site_id" id="editSiteId" class="form-control mb-2">
              <option value="">Select Site</option>
              <?php foreach ($sites as $site): ?>
                <option value="<?= $site['id'] ?>"><?= htmlspecialchars($site['site_name']) ?></option>
              <?php endforeach; ?>
            </select>
            <select name="employment_status" id="editEmployment" class="form-control mb-2" required>
              <option value="Full-Time">Full-Time</option>
              <option value="Ad-Hoc">Ad-Hoc</option>
            </select>
            <select name="status" id="editStatus" class="form-control mb-2" required>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
            <select name="role" id="editRole" class="form-control mb-2" required>
              <option value="admin">Admin</option>
              <option value="controller">Controller</option>
              <option value="HR">HR</option>
              <option value="supervisor">Supervisor</option>
              <option value="officer">Officer</option>
            </select>
            <input type="password" name="password" class="form-control mb-2" placeholder="(Leave blank to keep current)">
            <input type="file" name="profile_image" class="form-control mb-2">
            <small class="text-muted">Leave blank to keep current image.</small>
          </div>
          <div class="modal-footer">
            <button type="submit" class="btn btn-warning">Update User</button>
          </div>
        </div>
      </form>
    </div>
  </div>


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

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>


<script>
   $('#userTable').DataTable({
        dom: 'Bfrtip',
        buttons: ['csv', 'print'],
        order: [[2, 'desc']],
        pageLength: 10
    });


    $(document).on('click', '.editUserBtn', function() {
      $('#editUserId').val($(this).data('id'));
      $('#editUsername').val($(this).data('username'));
      $('#editEmail').val($(this).data('email'));
      $('#editContact').val($(this).data('contact'));
      $('#editSiteId').val($(this).data('site_id'));
      $('#editEmployment').val($(this).data('employment'));
      $('#editStatus').val($(this).data('status'));
      $('#editRole').val($(this).data('role'));
    });
  
</script>
</body>
</html>
