<?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') {
  $page = max(1,(int)($_GET['page']??1)); $limit = max(1,min(100,(int)($_GET['limit']??25))); $off = ($page-1)*$limit;
  $q = trim($_GET['q']??''); $where = "WHERE 1=1";
  if ($q!==''){ $qq=db()->real_escape_string($q); $where .= " AND (name LIKE '%$qq%' OR code LIKE '%$qq%')"; }
  $rows=[]; $res=db()->query("SELECT SQL_CALC_FOUND_ROWS * FROM operators $where ORDER BY name LIMIT $off,$limit");
  while($r=$res->fetch_assoc()) $rows[]=$r;
  $total=db()->query("SELECT FOUND_ROWS() x")->fetch_assoc()['x'];
  json_out(['rows'=>$rows,'total'=>(int)$total,'page'=>$page,'limit'=>$limit]);
}
if ($method === 'POST') {
  $data = json_decode(file_get_contents('php://input'), true);
  $code=$data['code']??null; $name=$data['name']??null; $dep=$data['department']??'Sales'; $reg=$data['region']??null;
  if(!$code||!$name) json_out(['error'=>'code va name shart'],400);
  $st=db()->prepare("INSERT INTO operators (code,name,department,region) VALUES (?,?,?,?)");
  $st->bind_param("ssss",$code,$name,$dep,$reg); $st->execute(); json_out(['id'=>$st->insert_id]);
}
if ($method === 'PUT') {
  $data=json_decode(file_get_contents('php://input'), true);
  $id=(int)($data['id']??0); if(!$id) json_out(['error'=>'id shart'],400);
  $name=$data['name']??null; $dep=$data['department']??null; $reg=$data['region']??null; $active=isset($data['active'])?(int)$data['active']:1;
  $st=db()->prepare("UPDATE operators SET name=?, department=?, region=?, active=? WHERE id=?");
  $st->bind_param("sssii",$name,$dep,$reg,$active,$id); $st->execute(); json_out(['ok'=>true]);
}
if ($method === 'DELETE') {
  $data=json_decode(file_get_contents('php://input'), true);
  $id=(int)($data['id']??0); if(!$id) json_out(['error'=>'id shart'],400);
  $st=db()->prepare("DELETE FROM operators WHERE id=?"); $st->bind_param("i",$id); $st->execute(); json_out(['ok'=>true]);
}
json_out(['error'=>'Method not allowed'],405);
