<?php
require_once __DIR__ . '/../config.php'; require_admin();


$db = contracts_db();
mysqli_set_charset($db, 'utf8mb4');             // <-- juda muhim
$db->query("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
$db->query("SET time_zone = '+05:00'");

$method=$_SERVER['REQUEST_METHOD']; $override=$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ?? ($_REQUEST['method'] ?? null); if($override) $method=strtoupper($override);

if($method==='GET'){
  $rows=[]; $r=db()->query("SELECT u.id,u.username,u.role,u.operator_id,o.name operator_name FROM users u LEFT JOIN operators o ON o.id=u.operator_id ORDER BY u.id DESC");
  while($x=$r->fetch_assoc()) $rows[]=$x; json_out(['rows'=>$rows]);
}
if($method==='POST'){
  $d=json_decode(file_get_contents('php://input'), true);
  $username=$d['username']??null; $password=$d['password']??null; $role=$d['role']??'operator'; $operator_id=isset($d['operator_id'])?(int)$d['operator_id']:null;
  if(!$username||!$password) json_out(['error'=>'username/password shart'],400);
  $hash=$password;
  $st=db()->prepare("INSERT INTO users (username,password_hash,role,operator_id) VALUES (?,?,?,?)");
  $st->bind_param("sssi",$username,$hash,$role,$operator_id); $st->execute(); json_out(['id'=>$st->insert_id]);
}
if($method==='PUT'){
  $d=json_decode(file_get_contents('php://input'), true);
  $id=(int)($d['id']??0); if(!$id) json_out(['error'=>'id shart'],400);
  $role=$d['role']??null; $operator_id=isset($d['operator_id'])?(int)$d['operator_id']:null; $password=$d['password']??null;
  if($password){ $hash=password_hash($password,PASSWORD_BCRYPT); $st=db()->prepare("UPDATE users SET role=?, operator_id=?, password_hash=? WHERE id=?"); $st->bind_param("sisi",$role,$operator_id,$hash,$id); }
  else { $st=db()->prepare("UPDATE users SET role=?, operator_id=? WHERE id=?"); $st->bind_param("sii",$role,$operator_id,$id); }
  $st->execute(); json_out(['ok'=>true]);
}
if($method==='DELETE'){
  $d=json_decode(file_get_contents('php://input'), true);
  $id=(int)($d['id']??0); if(!$id) json_out(['error'=>'id shart'],400);
  contracts_db()->query("DELETE FROM users WHERE id=".$id); json_out(['ok'=>true]);
}
json_out(['error'=>'Method not allowed'],405);
