<?php
require_once __DIR__ . '/../../../app/Models/User.php';
$user = new User();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $u = $user->getById((int)$_GET['id']);
    if (!$u) { echo "User not found"; exit; }
?>
<form id="editUserForm" enctype="multipart/form-data">
  <input type="hidden" name="id" value="<?= $u['id'] ?>">
  <div class="form-row">
    <div class="form-group col-md-6"><label>Name</label><input name="name" value="<?= htmlspecialchars($u['name']) ?>" class="form-control"></div>
    <div class="form-group col-md-6"><label>Email</label><input type="email" name="email" value="<?= htmlspecialchars($u['email']) ?>" class="form-control"></div>
  </div>
  <div class="form-row">
    <div class="form-group col-md-6">
      <label>Role</label>
      <select name="role" class="form-control">
        <?php foreach(['admin','manager','staff'] as $r): ?>
          <option value="<?= $r ?>" <?= $r==$u['role']?'selected':'' ?>><?= ucfirst($r) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="form-group col-md-6">
      <label>Status</label>
      <select name="status" class="form-control">
        <option value="active" <?= $u['status']=='active'?'selected':'' ?>>Active</option>
        <option value="disabled" <?= $u['status']=='disabled'?'selected':'' ?>>Disabled</option>
      </select>
    </div>
  </div>
  <div class="form-group">
    <label>Profile Image</label>
    <input type="file" name="profile_image" class="form-control-file" accept="image/*">
    <?php if(!empty($u['profile_image'])): ?>
      <img src="<?= htmlspecialchars($u['profile_image']) ?>" width="80" class="mt-2 rounded">
    <?php endif; ?>
  </div>
  <button type="submit" class="btn btn-warning btn-block">Update</button>
</form>

<script>
$('#editUserForm').on('submit', function(e){
  e.preventDefault();
  var formData = new FormData(this);
  $.ajax({
    url: 'ajax/users/edit.php', method: 'POST', data: formData,
    contentType: false, processData: false,
    success: function(){ location.reload(); }
  });
});
</script>
<?php
exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)$_POST['id'];
    $user->update($id, $_POST, $_FILES['profile_image'] ?? null);
    echo 'updated';
}
