<?php
require_once __DIR__ . '/../config.php';


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

$u = current_user();
if(!$u){ http_response_code(403); exit('Login kerak'); }

$db = contracts_db();
$ym = $_GET['ym'] ?? date('Y-m');

// operator_id: operator o'zi chaqirsa - o'zidan olamiz; admin bo'lsa GETdan olish mumkin
$op_id = ($u['role']==='operator') ? (int)$u['operator_id'] : 0;
if($u['role']==='admin'){
  $op_id = isset($_GET['operator_id']) ? (int)$_GET['operator_id'] : 0;
  if($op_id<=0){ http_response_code(400); json_out(['error'=>'operator_id kerak (admin)'],400); }
}
if($op_id<=0){ http_response_code(403); exit('Operator kerak'); }

/* operator ma'lumotlari */
$op = $db->query("SELECT * FROM operators WHERE id=$op_id LIMIT 1")->fetch_assoc();

/* metrics row */
$st=$db->prepare("SELECT * FROM operator_monthly_metrics WHERE operator_id=? AND ym=? LIMIT 1");
$st->bind_param("is",$op_id,$ym); $st->execute(); $m=$st->get_result()->fetch_assoc(); $st->close();
if(!$m) $m=['ym'=>$ym];

/* base & penalties */
$base_amount    = isset($m['base_amount']) ? (int)$m['base_amount'] : 1500000;
$base_confirmed = (int)($m['base_confirmed'] ?? 0);
$base           = $base_confirmed ? $base_amount : 0;
$penalties      = (int)($m['late_minutes']??0)*300 + (int)($m['absent_days']??0)*100000 +
                  (int)($m['bad_comm_count']??0)*30000 + (int)($m['missing_info_count']??0)*20000 +
                  (int)($m['other_penalty']??0);

/* statuslar: item_id => [approved,pending,rejected] */
$stat=[];
$r=$db->query("SELECT item_id,status,COUNT(*) c FROM kpi_submissions
               WHERE operator_id=$op_id AND ym='".$db->real_escape_string($ym)."'
               GROUP BY item_id,status");
while($x=$r->fetch_assoc()){
  $iid=(int)$x['item_id']; $stt=$x['status']; $c=(int)$x['c'];
  if(!isset($stat[$iid])) $stat[$iid]=['approved'=>0,'pending'=>0,'rejected'=>0];
  $stat[$iid][$stt]=$c;
}

/* plans + items */
$plans=[]; $dynamic_bonus=0; $avgPctSum=0; $avgCnt=0;

$q=$db->query("SELECT p.* FROM kpi_assignments a JOIN kpi_plans p ON p.id=a.plan_id
               WHERE a.operator_id=$op_id AND p.ym='".$db->real_escape_string($ym)."'
               ORDER BY p.id DESC");
while($p=$q->fetch_assoc()){
  $items=[]; $planEarned=0; $planPctSum=0; $planCnt=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);
    $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'];

    $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);
    }
    if($tgt>0){ $planPctSum += min(100.0,$appr*100.0/$tgt); $planCnt++; }

    $items[]=[
      'id'=>$iid,
      'title'=>$it['title'],
      'target'=>$tgt,
      'approved'=>$appr,
      'pending'=>$pend,
      'rejected'=>$rej,
      'reward_amount'=>$rew,
      'reward_calc'=>$calc,
      'reward_min_pct'=>$minp,            // 0..1
      'reward_allow_over'=>$allow?1:0,
      'earned'=>$earned,
      'pct'=> ($tgt>0)? round($appr*100.0/$tgt,1) : 0
    ];
    $planEarned += $earned;
  }

  $plans[]=[
    'plan'=>['id'=>$p['id'],'name'=>$p['name'],'ym'=>$p['ym'],'description'=>$p['description']],
    'items'=>$items,
    'plan_earned'=>$planEarned,
    'plan_pct'=> ($planCnt>0)? round($planPctSum/$planCnt,1) : null
  ];
  $dynamic_bonus += $planEarned;
  $avgPctSum += ($planCnt>0)? ($planPctSum/$planCnt) : 0;
  if($planCnt>0) $avgCnt++;
}

$gross = $base + $dynamic_bonus + (int)($m['other_bonus']??0);
$net   = max(0, $gross - $penalties);

json_out([
  'ym'=>$ym,
  'operator'=>['id'=>$op['id'],'name'=>$op['name'],'code'=>$op['code'],'department'=>$op['department'],'region'=>$op['region']],
  'plans'=>$plans,
  'totals'=>[
    'base_amount'=>$base_amount,'base_confirmed'=>$base_confirmed,
    'dynamic_bonus'=>$dynamic_bonus,'other_bonus'=>(int)($m['other_bonus']??0),
    'gross'=>$gross,'penalties'=>$penalties,'net'=>$net,
    'avg_pct'=> ($avgCnt>0)? round($avgPctSum/$avgCnt,1) : null
  ],
  'finalize'=>[
    'admin_finalized'=>(int)($m['admin_finalized']??0),
    'operator_signature_path'=>$m['operator_signature_path']??null,
    'operator_signed_at'=>$m['operator_signed_at']??null
  ]
]);
