<?php
require_once __DIR__ . '/../lib/payroll.php'; // base/penalties hisoblari uchun
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'");

function earned_rule($approved,$target,$amount,$calc,$minp,$allow){
  if($target <= 0 || $amount <= 0) return 0;
  $pct = $approved / $target;
  if(!$allow) $pct = min(1.0, $pct);
  if($pct < $minp) return 0;
  if($calc === 'threshold') return ($pct >= 1.0) ? $amount : 0;
  return (int)round($amount * $pct);
}

$ym = $_GET['ym'] ?? date('Y-m');
$dept = trim($_GET['dept'] ?? '');
$region = trim($_GET['region'] ?? '');
$q = trim($_GET['q'] ?? '');
$op = (int)($_GET['op'] ?? 0);

$db = contracts_db();
$where = "WHERE active=1";
if($op>0) $where .= " AND id=".$op;
if($dept!==''){ $d=$db->real_escape_string($dept); $where.=" AND department LIKE '%$d%'"; }
if($region!==''){ $r=$db->real_escape_string($region); $where.=" AND region LIKE '%$r%'"; }
if($q!==''){ $qq=$db->real_escape_string($q); $where.=" AND (name LIKE '%$qq%' OR code LIKE '%$qq%')"; }

$ops = [];
$opsRes = $db->query("SELECT * FROM operators $where ORDER BY name ASC");
while($row = $opsRes->fetch_assoc()) $ops[] = $row;

/* metrics (base/penalties/finalize/sign) */
$mm = [];
$st = $db->prepare("SELECT * FROM operator_monthly_metrics WHERE ym=?");
$st->bind_param("s", $ym);
$st->execute();
$resM = $st->get_result();
while($r = $resM->fetch_assoc()) $mm[(int)$r['operator_id']] = $r;
$st->close();

$rows = [];
$tot = ['base'=>0,'gross'=>0,'penalties'=>0,'net'=>0];

foreach($ops as $o){
  $m = $mm[$o['id']] ?? ['ym'=>$ym];
  /* base/penalties lib/payroll.php orqali (statik bonuslar hisobga olinmaydi — keyin dynamic qo‘shamiz) */
  $targets = ['base_fixed'=>($m['base_amount']??1500000)]; // compute_payroll_row defaultidan mustaqil bo‘lishi uchun
  $row = [
    'operator_id'=>$o['id'],
    'code'=>$o['code'],
    'name'=>$o['name'],
    'department'=>$o['department'],
    'region'=>$o['region'],
    'ym'=>$ym,
    'base_confirmed'=>(int)($m['base_confirmed']??0),
    'base_amount'=> isset($m['base_amount']) ? (int)$m['base_amount'] : 1500000
  ];
  $row['base'] = $row['base_confirmed'] ? $row['base_amount'] : 0;
  $pen = (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);

  /* approved per item */
  $ap = [];
  $qr = $db->query("SELECT item_id, COUNT(*) c FROM kpi_submissions
                    WHERE operator_id=".$o['id']." AND ym='".$db->real_escape_string($ym)."' AND status='approved'
                    GROUP BY item_id");
  while($x=$qr->fetch_assoc()) $ap[(int)$x['item_id']] = (int)$x['c'];

  /* dynamic bonus: barcha assigned itemlar uchun */
  $dyn = 0;
  $avgPctSum=0; $avgCnt=0;
  $qi = $db->query("SELECT i.id,i.target_int,i.reward_amount,i.reward_calc,i.reward_min_pct,i.reward_allow_over
                    FROM kpi_items i
                    JOIN kpi_plans p ON p.id=i.plan_id
                    JOIN kpi_assignments a ON a.plan_id=p.id AND a.operator_id=".$o['id']."
                    WHERE p.ym='".$db->real_escape_string($ym)."'");
  while($it=$qi->fetch_assoc()){
    $iid=(int)$it['id']; $tgt=(int)$it['target_int']; $rew=(int)$it['reward_amount'];
    $calc=$it['reward_calc']??'proportional';
    $minp=(float)($it['reward_min_pct']??0.0);
    $allow=!empty($it['reward_allow_over'])?1:0;
    $approved = $ap[$iid] ?? 0;
    if($tgt>0){ $avgPctSum += min(100.0, $approved*100.0/$tgt); $avgCnt++; }
    $dyn += earned_rule($approved,$tgt,$rew,$calc,$minp,$allow);
  }
  $row['plan_pct_avg'] = $avgCnt>0 ? round($avgPctSum/$avgCnt,1) : null;
  $row['dynamic_bonus'] = $dyn;

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

  $row['other_bonus']      = (int)($m['other_bonus']??0);
  $row['penalties_total']  = $pen;
  $row['gross']            = $gross;
  $row['net']              = $net;

  /* finalize/sign holati */
  $row['admin_finalized']         = (int)($m['admin_finalized'] ?? 0);
  $row['operator_signature_path'] = $m['operator_signature_path'] ?? null;
  $row['operator_signed_at']      = $m['operator_signed_at'] ?? null;

  $rows[] = $row;
  $tot['base'] += $row['base']; $tot['gross'] += $gross; $tot['penalties'] += $pen; $tot['net'] += $net;
}

json_out(['ym'=>$ym,'rows'=>$rows,'totals'=>$tot]);
