<?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'");


header('Content-Type: application/json; charset=utf-8');

$db = contracts_db();
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = $_GET['action'] ?? '';

if (!function_exists('json_out')) {
  function json_out($data, $code=200){
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
  }
}
function json_bad($msg, $code=400){ json_out(['error'=>$msg], $code); }

/* Yordamchi: evidence_types normalize (array|string -> string) */
function norm_evidence($v){
  if (is_array($v)) return implode(',', array_filter(array_map('trim',$v)));
  if (is_string($v)) return trim($v);
  return '';
}
/* Yordamchi: safe bool->int */
function bool01($v){ return !empty($v) ? 1 : 0; }
/* Yordamchi: float sanitizatsiya (NaN -> 0) */
function f0($v){ $x = floatval($v); return is_finite($x) ? $x : 0.0; }

/* ------------------------------------------
   PLANS: list_plans  (GET)
   ?action=list_plans&ym=2025-09&q=&page=1&limit=20
-------------------------------------------*/
if ($method === 'GET' && $action === 'list_plans') {
  $ym   = trim($_GET['ym'] ?? '');
  $q    = trim($_GET['q'] ?? '');
  $page = max(1, (int)($_GET['page'] ?? 1));
  $limit= max(1, min(100, (int)($_GET['limit'] ?? 20)));
  $off  = ($page-1)*$limit;

  $where = "WHERE 1=1";
  if ($ym !== '') { $ymq = $db->real_escape_string($ym); $where .= " AND ym='$ymq'"; }
  if ($q  !== '') { $qq  = $db->real_escape_string($q);  $where .= " AND (name LIKE '%$qq%' OR description LIKE '%$qq%')"; }

  $rows = [];
  $res = $db->query("SELECT SQL_CALC_FOUND_ROWS * FROM kpi_plans $where ORDER BY ym DESC, id DESC LIMIT $off,$limit");
  if(!$res){ json_bad('DB error: '.$db->error, 500); }
  while ($r = $res->fetch_assoc()) $rows[] = $r;
  $fr = $db->query("SELECT FOUND_ROWS() x");
  $total = (int)($fr ? ($fr->fetch_assoc()['x'] ?? 0) : 0);

  json_out(['rows'=>$rows,'total'=>$total,'page'=>$page,'limit'=>$limit]);
}

/* ------------------------------------------
   PLANS: create (POST: ym,name,description)
-------------------------------------------*/
if ($method === 'POST' && $action === 'create') {
  $in  = json_decode(file_get_contents('php://input'), true);
  if (!is_array($in)) json_bad('Bad JSON');
  $ym  = $in['ym'] ?? null;
  $name= $in['name'] ?? null;
  $desc= $in['description'] ?? null;
  if (!$ym || !$name) json_bad('ym va name shart');
  $uid = current_user()['id'] ?? null;

  $st = $db->prepare("INSERT INTO kpi_plans (ym,name,description,created_by) VALUES (?,?,?,?)");
  if(!$st){ json_bad('DB prepare error: '.$db->error, 500); }
  $st->bind_param("sssi", $ym, $name, $desc, $uid);
  if(!$st->execute()){ json_bad('DB exec error: '.$st->error, 500); }
  json_out(['ok'=>true, 'plan_id'=>$st->insert_id]);
}

/* ------------------------------------------
   PLANS: update (PUT: id, ym,name,description)
-------------------------------------------*/
if ($method === 'PUT' && $action === 'update') {
  $in  = json_decode(file_get_contents('php://input'), true);
  if (!is_array($in)) json_bad('Bad JSON');
  $id  = (int)($in['id'] ?? 0);
  $ym  = $in['ym'] ?? null;
  $name= $in['name'] ?? null;
  $desc= $in['description'] ?? null;
  if (!$id || !$ym || !$name) json_bad('id, ym, name shart');

  $st = $db->prepare("UPDATE kpi_plans SET ym=?, name=?, description=? WHERE id=?");
  if(!$st){ json_bad('DB prepare error: '.$db->error, 500); }
  $st->bind_param("sssi", $ym, $name, $desc, $id);
  if(!$st->execute()){ json_bad('DB exec error: '.$st->error, 500); }
  json_out(['ok'=>true]);
}

/* ------------------------------------------
   PLANS: delete (DELETE: id)
-------------------------------------------*/
if ($method === 'DELETE' && $action === 'delete') {
  $in  = json_decode(file_get_contents('php://input'), true);
  if (!is_array($in)) json_bad('Bad JSON');
  $id  = (int)($in['id'] ?? 0);
  if (!$id) json_bad('id shart');
  if(!$db->query("DELETE FROM kpi_plans WHERE id=$id")){ json_bad('DB error: '.$db->error, 500); }
  json_out(['ok'=>true]);
}

/* ------------------------------------------
   ITEMS: list_items (GET: plan_id)
-------------------------------------------*/
if ($method === 'GET' && $action === 'list_items') {
  $plan_id = (int)($_GET['plan_id'] ?? 0);
  if (!$plan_id) json_bad('plan_id shart');
  $items = [];
  $r = $db->query("SELECT * FROM kpi_items WHERE plan_id=$plan_id ORDER BY sort_order,id");
  if(!$r){ json_bad('DB error: '.$db->error, 500); }
  while ($x = $r->fetch_assoc()) $items[] = $x;
  json_out(['items'=>$items]);
}

/* ------------------------------------------
   ITEMS: add_item (POST)
-------------------------------------------*/
if ($method === 'POST' && $action === 'add_item') {
  $in = json_decode(file_get_contents('php://input'), true);
  if (!is_array($in)) json_bad('Bad JSON');

  $plan_id     = (int)($in['plan_id'] ?? 0);
  $title       = $in['title'] ?? null;
  $desc        = $in['description'] ?? null;
  $target_int  = (int)($in['target_int'] ?? 0);

  // Evidence + required
  $evidence    = norm_evidence($in['evidence_types'] ?? '');
  $required    = bool01($in['required'] ?? 0);

  // Sort
  $sort_order  = (int)($in['sort_order'] ?? 0);

  // Rewards
  $reward_amount     = (int)($in['reward_amount'] ?? 0);
  $reward_calc       = $in['reward_calc'] ?? 'proportional';
  $reward_min_pct    = f0($in['reward_min_pct'] ?? 0);   // 0..1 kutiladi
  $reward_allow_over = bool01($in['reward_allow_over'] ?? 1);

  if (!$plan_id || !$title) json_bad('plan_id va title shart');

  // INSERT including reward fields
  $sql = "INSERT INTO kpi_items
          (plan_id,title,description,target_int,evidence_types,required,sort_order,
           reward_amount,reward_calc,reward_min_pct,reward_allow_over)
          VALUES (?,?,?,?,?,?,?,?,?,?,?)";
  $st = $db->prepare($sql);
  if(!$st){ json_bad('DB prepare error: '.$db->error, 500); }
  // types: i s s i s i i i s d i
  $st->bind_param("issisiiisdi",
    $plan_id, $title, $desc, $target_int, $evidence, $required, $sort_order,
    $reward_amount, $reward_calc, $reward_min_pct, $reward_allow_over
  );
  if(!$st->execute()){ json_bad('DB exec error: '.$st->error, 500); }

  json_out(['ok'=>true, 'item_id'=>$st->insert_id]);
}

/* ------------------------------------------
   ITEMS: update_item (PUT)
-------------------------------------------*/
if ($method === 'PUT' && $action === 'update_item') {
  $in = json_decode(file_get_contents('php://input'), true);
  if (!is_array($in)) json_bad('Bad JSON');

  $id          = (int)($in['id'] ?? 0);
  $title       = $in['title'] ?? null;
  $desc        = $in['description'] ?? null;
  $target_int  = (int)($in['target_int'] ?? 0);

  // Evidence + required
  $evidence    = norm_evidence($in['evidence_types'] ?? '');
  $required    = bool01($in['required'] ?? 0);

  // Rewards
  $reward_amount     = (int)($in['reward_amount'] ?? 0);
  $reward_calc       = $in['reward_calc'] ?? 'proportional';
  $reward_min_pct    = f0($in['reward_min_pct'] ?? 0);
  $reward_allow_over = bool01($in['reward_allow_over'] ?? 1);

  if (!$id || !$title) json_bad('id va title shart');

  $sql = "UPDATE kpi_items
          SET title=?, description=?, target_int=?, evidence_types=?, required=?,
              reward_amount=?, reward_calc=?, reward_min_pct=?, reward_allow_over=?
          WHERE id=?";
  $st = $db->prepare($sql);
  if(!$st){ json_bad('DB prepare error: '.$db->error, 500); }
  // types: s s i s i i s d i i
  $st->bind_param("ssisiisdii",
    $title, $desc, $target_int, $evidence, $required,
    $reward_amount, $reward_calc, $reward_min_pct, $reward_allow_over,
    $id
  );
  if(!$st->execute()){ json_bad('DB exec error: '.$st->error, 500); }

  json_out(['ok'=>true]);
}

/* ------------------------------------------
   ITEMS: delete_item (DELETE: id)
-------------------------------------------*/
if ($method === 'DELETE' && $action === 'delete_item') {
  $in = json_decode(file_get_contents('php://input'), true);
  if (!is_array($in)) json_bad('Bad JSON');
  $id = (int)($in['id'] ?? 0);
  if (!$id) json_bad('id shart');
  if(!$db->query("DELETE FROM kpi_items WHERE id=$id")){ json_bad('DB error: '.$db->error, 500); }
  json_out(['ok'=>true]);
}

/* ------------------------------------------
   ITEMS: reorder_items (POST)
   { plan_id, order: [item_id1,item_id2,...] }
-------------------------------------------*/
if ($method === 'POST' && $action === 'reorder_items') {
  $in = json_decode(file_get_contents('php://input'), true);
  if (!is_array($in)) json_bad('Bad JSON');
  $plan_id = (int)($in['plan_id'] ?? 0);
  $order   = $in['order'] ?? [];
  if (!$plan_id || !is_array($order)) json_bad('plan_id va order[] shart');

  $sort = 1;
  $st = $db->prepare("UPDATE kpi_items SET sort_order=? WHERE id=? AND plan_id=?");
  if(!$st){ json_bad('DB prepare error: '.$db->error, 500); }
  foreach ($order as $item_id) {
    $iid = (int)$item_id;
    $st->bind_param("iii", $sort, $iid, $plan_id);
    if(!$st->execute()){ json_bad('DB exec error: '.$st->error, 500); }
    $sort++;
  }
  json_out(['ok'=>true]);
}

/* ------------------------------------------
   ASSIGN: list_assignments (GET: plan_id) -> operator_id massiv
-------------------------------------------*/
if ($method === 'GET' && $action === 'list_assignments') {
  $plan_id = (int)($_GET['plan_id'] ?? 0);
  if (!$plan_id) json_bad('plan_id shart');
  $assigned = [];
  $r = $db->query("SELECT operator_id FROM kpi_assignments WHERE plan_id=$plan_id");
  if(!$r){ json_bad('DB error: '.$db->error, 500); }
  while ($x = $r->fetch_assoc()) $assigned[] = (int)$x['operator_id'];
  json_out(['assigned'=>$assigned]);
}

/* ------------------------------------------
   ASSIGN: assign_bulk / unassign_bulk (POST)
-------------------------------------------*/
if ($method === 'POST' && in_array($action, ['assign_bulk','unassign_bulk'])) {
  $in = json_decode(file_get_contents('php://input'), true);
  if (!is_array($in)) json_bad('Bad JSON');
  $plan_id = (int)($in['plan_id'] ?? 0);
  $ops     = $in['operator_ids'] ?? [];
  if (!$plan_id || !is_array($ops)) json_bad('plan_id va operator_ids[] shart');

  if ($action === 'assign_bulk') {
    $st = $db->prepare("INSERT IGNORE INTO kpi_assignments (plan_id, operator_id) VALUES (?,?)");
    if(!$st){ json_bad('DB prepare error: '.$db->error, 500); }
    foreach ($ops as $oid) {
      $o=(int)$oid;
      $st->bind_param("ii",$plan_id,$o);
      if(!$st->execute()){ json_bad('DB exec error: '.$st->error, 500); }
    }
    json_out(['ok'=>true]);
  } else {
    // Unassign
    $ids = array_map('intval', $ops);
    if (count($ids)>0) {
      $inList = implode(',', $ids);
      if(!$db->query("DELETE FROM kpi_assignments WHERE plan_id=$plan_id AND operator_id IN ($inList)")){
        json_bad('DB error: '.$db->error, 500);
      }
    }
    json_out(['ok'=>true]);
  }
}

/* ------------------------------------------
   ALIAS for operator plan view:
   action=list  => return {plan, items}
-------------------------------------------*/
if ($method === 'GET' && $action === 'list') {
  $plan_id = (int)($_GET['plan_id'] ?? 0);
  if (!$plan_id) json_bad('plan_id shart');
  $pr = $db->query("SELECT * FROM kpi_plans WHERE id=$plan_id");
  if(!$pr){ json_bad('DB error: '.$db->error, 500); }
  $plan = $pr->fetch_assoc();
  $items = [];
  $r = $db->query("SELECT * FROM kpi_items WHERE plan_id=$plan_id ORDER BY sort_order,id");
  if(!$r){ json_bad('DB error: '.$db->error, 500); }
  while ($x = $r->fetch_assoc()) $items[] = $x;
  json_out(['plan'=>$plan,'items'=>$items]);
}

json_out(['error'=>'Not found'],404);
