<?php
require_once __DIR__ . '/../config.php';
$u = current_user();
if (!$u || $u['role']!=='operator') { http_response_code(403); echo "Operator kerak"; exit; }
$op = (int)$u['operator_id'];
$ym = isset($_GET['ym']) ? $_GET['ym'] : date('Y-m');

$db = contracts_db(); $ym_q = $db->real_escape_string($ym);
$q = $db->query("SELECT p.* FROM kpi_assignments a JOIN kpi_plans p ON p.id=a.plan_id WHERE a.operator_id={$op} AND p.ym='{$ym_q}' ORDER BY p.id DESC");
$plans = []; while ($r = $q->fetch_assoc()) $plans[] = $r;

$out = [];


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

foreach ($plans as $p) {
  $items = []; $r = $db->query("SELECT * FROM kpi_items WHERE plan_id={$p['id']} ORDER BY sort_order,id");
  $plan_counts = ['approved'=>0, 'pending'=>0, 'rejected'=>0, 'total'=>0];
  $pct_sum = 0; $n = 0;
  while ($it = $r->fetch_assoc()) {
    $item_id = (int)$it['id'];

    $st = $db->prepare("SELECT status, COUNT(*) c FROM kpi_submissions WHERE plan_id=? AND item_id=? AND operator_id=? AND ym=? GROUP BY status");
    $st->bind_param("iiis", $p['id'], $item_id, $op, $ym);
    $st->execute(); $res=$st->get_result(); $approved=0;$pending=0;$rejected=0;
    while($row=$res->fetch_assoc()){
      if($row['status']==='approved') $approved=(int)$row['c'];
      elseif($row['status']==='pending') $pending=(int)$row['c'];
      elseif($row['status']==='rejected') $rejected=(int)$row['c'];
    } $st->close();

    $it['approved_count']=$approved; $it['pending_count']=$pending; $it['rejected_count']=$rejected;

    $plan_counts['approved'] += $approved; $plan_counts['pending'] += $pending; $plan_counts['rejected'] += $rejected;
    $plan_counts['total'] += ($approved+$pending+$rejected);

    $tgt=(int)$it['target_int']; if($tgt>0){ $pct_sum += min(100.0, $approved*100.0/$tgt); $n++; }
    $items[]=$it;
  }
  $plan_pct = $n>0 ? round($pct_sum/$n,1) : null;
  $out[] = ['plan'=>$p,'items'=>$items,'plan_pct'=>$plan_pct,'plan_counts'=>$plan_counts];
}
json_out(['ym'=>$ym,'plans'=>$out]);
