<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../config/config.php';
session_start();

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
  http_response_code(401);
  echo json_encode(['ok'=>false,'error'=>'Not logged in']); exit;
}
if (($_SESSION['role'] ?? 'user') !== 'admin') {
  http_response_code(403);
  echo json_encode(['ok'=>false,'error'=>'Admin only']); exit;
}

$id = isset($_POST['id']) && $_POST['id'] !== '' ? (int)$_POST['id'] : null;
$name = trim((string)($_POST['name'] ?? ''));
$username = trim((string)($_POST['username'] ?? ''));
$role = (($_POST['role'] ?? 'user') === 'admin') ? 'admin' : 'user';
$password = (string)($_POST['password'] ?? '');

if ($name === '' || $username === '') {
  http_response_code(400);
  echo json_encode(['ok'=>false,'error'=>'Name und Username sind Pflicht']); exit;
}

try {
  if ($id === null) {
    // CREATE: Passwort optional -> wenn leer: first_login=1 und password_hash=NULL
    if ($password === '') {
      $st = $pdo->prepare("INSERT INTO users (name, username, password_hash, role, first_login, last_login)
                           VALUES (:n,:u,NULL,:r,1,NULL)");
      $st->execute([':n'=>$name, ':u'=>$username, ':r'=>$role]);
    } else {
      $hash = password_hash($password, PASSWORD_DEFAULT);
      $st = $pdo->prepare("INSERT INTO users (name, username, password_hash, role, first_login, last_login)
                           VALUES (:n,:u,:p,:r,0,NULL)");
      $st->execute([':n'=>$name, ':u'=>$username, ':p'=>$hash, ':r'=>$role]);
    }

    echo json_encode(['ok'=>true,'id'=>(int)$pdo->lastInsertId()], JSON_UNESCAPED_UNICODE);
    exit;
  }

  // UPDATE
  if ($password !== '') {
    // Admin setzt neues Passwort -> first_login=0
    $hash = password_hash($password, PASSWORD_DEFAULT);
    $st = $pdo->prepare("UPDATE users SET name=:n, username=:u, role=:r, password_hash=:p, first_login=0 WHERE id=:id");
    $st->execute([':n'=>$name, ':u'=>$username, ':r'=>$role, ':p'=>$hash, ':id'=>$id]);
  } else {
    $st = $pdo->prepare("UPDATE users SET name=:n, username=:u, role=:r WHERE id=:id");
    $st->execute([':n'=>$name, ':u'=>$username, ':r'=>$role, ':id'=>$id]);
  }

  echo json_encode(['ok'=>true,'id'=>$id], JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
  if ((int)($e->errorInfo[1] ?? 0) === 1062) {
    http_response_code(409);
    echo json_encode(['ok'=>false,'error'=>'Username ist schon vergeben']); exit;
  }
  
  http_response_code(500);
  echo json_encode(['ok'=>false,'error'=>'DB Fehler']); exit;
}
