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

/* Operatorga biriktirilgan planlar (shu oy) */
$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;

/* Statuslarni oldindan yig'ish: item_id => [approved,pending,rejected] */
$stat = [];
$r = $db->query("SELECT item_id, status, COUNT(*) c
                 FROM kpi_submissions
                 WHERE operator_id={$op} AND ym='{$ym_q}'
                 GROUP BY item_id, status");
while($x=$r->fetch_assoc()){
  $iid=(int)$x['item_id']; $st=$x['status']; $c=(int)$x['c'];
  if(!isset($stat[$iid])) $stat[$iid]=['approved'=>0,'pending'=>0,'rejected'=>0];
  $stat[$iid][$st]=$c;
}

$out=[];
foreach($plans as $p){
  $items=[]; $sumPct=0; $n=0;
  $plan_counts=['approved'=>0,'pending'=>0,'rejected'=>0,'total'=>0];
  $plan_earned=0;

  $ri = $db->query("SELECT * FROM kpi_items WHERE plan_id=".$p['id']." ORDER BY sort_order,id");
  while($it=$ri->fetch_assoc()){
    $iid=(int)$it['id'];
    $tgt=(int)$it['target_int'];
    $rew=(int)($it['reward_amount']??0);
    $calc=$it['reward_calc']??'proportional';
    $minp=(float)($it['reward_min_pct']??0.0);   // 0..1
    $allow=!empty($it['reward_allow_over'])?1:0;

    $s = $stat[$iid] ?? ['approved'=>0,'pending'=>0,'rejected'=>0];
    $appr=(int)$s['approved']; $pend=(int)$s['pending']; $rej=(int)$s['rejected'];

    /* earned hisob */
    $pct = ($tgt>0) ? ($appr/$tgt) : 0.0;
    if(!$allow) $pct = min(1.0,$pct);
    $earned = 0;
    if($tgt>0 && $rew>0 && $pct >= $minp){
      $earned = ($calc==='threshold') ? (($pct>=1.0)?$rew:0) : (int)round($rew*$pct);
    }

    $it['approved_count']=$appr;
    $it['pending_count'] =$pend;
    $it['rejected_count']=$rej;
    $it['earned_amount'] =$earned;

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

    if($tgt>0){ $sumPct += min(100.0, $appr*100.0/$tgt); $n++; }
    $plan_earned += $earned;

    $items[]=$it;
  }

  $plan_pct = $n>0 ? round($sumPct/$n,1) : null;
  $out[] = [
    'plan'        => $p,
    'items'       => $items,
    'plan_pct'    => $plan_pct,
    'plan_counts' => $plan_counts,
    'plan_earned' => $plan_earned
  ];
}

json_out(['ym'=>$ym, 'plans'=>$out]);
