<?php
session_start();
include 'config.php';

// Allow only admin/superadmin
if (!isset($_SESSION['username']) || (!in_array($_SESSION['role'], ['admin','superadmin']))) {
    header("Location: index.php");
    exit();
}

// Handle new mapping submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['machine_uid'], $_POST['system_user_id'])) {
    $machine_uid = intval($_POST['machine_uid']);
    $system_user_id = $_POST['system_user_id'];

    // Insert or update
    $stmt = $conn->prepare("INSERT INTO user_mapping (machine_uid, system_user_id) VALUES (?, ?)
                            ON DUPLICATE KEY UPDATE system_user_id = VALUES(system_user_id)");
    $stmt->bind_param("is", $machine_uid, $system_user_id);
    $stmt->execute();
    header("Location: manage_mappings.php");
    exit();
}

// Handle delete
if (isset($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);
    $stmt = $conn->prepare("DELETE FROM user_mapping WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    $stmt->execute();
    header("Location: manage_mappings.php");
    exit();
}

// Fetch all mappings
$mappings = $conn->query("SELECT um.id, um.machine_uid, um.system_user_id, u.username 
                          FROM user_mapping um 
                          LEFT JOIN users u ON um.system_user_id = u.id
                          ORDER BY um.machine_uid ASC");

// Fetch employees for dropdown
$employees = $conn->query("SELECT id, username FROM users WHERE role='employee' AND status='active' ORDER BY username");
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Manage Biometric Mappings</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container my-5">
  <h2 class="text-center text-primary">Manage Biometric User Mappings</h2>

  <!-- Add New Mapping -->
  <div class="card mb-4">
    <div class="card-header bg-info text-white">Add / Update Mapping</div>
    <div class="card-body">
      <form method="post" class="row g-3">
        <div class="col-md-3">
          <label class="form-label">Biometric UID</label>
          <input type="number" name="machine_uid" class="form-control" required>
        </div>
        <div class="col-md-5">
          <label class="form-label">System User (Employee)</label>
          <select name="system_user_id" class="form-control" required>
            <option value="">-- Select Employee --</option>
            <?php while($emp = $employees->fetch_assoc()) { ?>
              <option value="<?= $emp['id'] ?>"><?= $emp['username'] ?> (<?= $emp['id'] ?>)</option>
            <?php } ?>
          </select>
        </div>
        <div class="col-md-2 d-flex align-items-end">
          <button type="submit" class="btn btn-success w-100">Save</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Existing Mappings -->
  <div class="card">
    <div class="card-header bg-secondary text-white">Existing Mappings</div>
    <div class="card-body">
      <table class="table table-bordered table-striped">
        <thead class="table-dark">
          <tr>
            <th>ID</th>
            <th>Biometric UID</th>
            <th>System User ID</th>
            <th>Employee Name</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          <?php while ($row = $mappings->fetch_assoc()) { ?>
            <tr>
              <td><?= $row['id'] ?></td>
              <td><?= $row['machine_uid'] ?></td>
              <td><?= $row['system_user_id'] ?></td>
              <td><?= htmlspecialchars($row['username'] ?? '❌ Not Found') ?></td>
              <td>
                <a href="manage_mappings.php?delete=<?= $row['id'] ?>" 
                   class="btn btn-danger btn-sm"
                   onclick="return confirm('Are you sure to delete this mapping?');">
                   Delete
                </a>
              </td>
            </tr>
          <?php } ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
</body>
</html>
