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

header('Content-Type: application/json; charset=utf-8');
ini_set('default_charset', 'UTF-8');
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
mb_regex_encoding('UTF-8');
date_default_timezone_set('Asia/Tashkent');

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;
  }
}

$db = contracts_db();
mysqli_set_charset($db, 'utf8mb4');
@$db->query("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
@$db->query("SET time_zone = '+05:00'");

$u = current_user();
if(!$u){ json_out(['ok'=>false,'error'=>'Login kerak'], 403); }

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

// operator_id: operator o‘zi kirsin, admin bo‘lsa GETdan otsin
$op_id = 0;
if (!empty($u['role']) && $u['role'] === 'admin') {
  $op_id = isset($_GET['operator_id']) ? (int)$_GET['operator_id'] : 0;
  if ($op_id <= 0) json_out(['ok'=>false,'error'=>'operator_id kerak (admin)'], 400);
} else {
  // operator sifatida
  $op_id = (int)($u['operator_id'] ?? $u['id'] ?? 0);
  if ($op_id <= 0) json_out(['ok'=>false,'error'=>'Operator kerak'], 403);
}

/* operator ma’lumotlari */
$op = null;
$ro = $db->query("SELECT id,name,code,department,region FROM operators WHERE id=$op_id LIMIT 1");
if($ro) $op = $ro->fetch_assoc();
if(!$op) $op = ['id'=>$op_id,'name'=>'','code'=>'','department'=>'','region'=>''];

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

/* base va penalties (dinamik) */
$base_amount    = isset($m['base_amount']) ? (int)$m['base_amount'] : 0;
$base_confirmed = (int)($m['base_confirmed'] ?? 0);

// penalti komponentlari (bo'lmasa 0)
$late_minutes       = (int)($m['late_minutes'] ?? 0);
$absent_days        = (int)($m['absent_days'] ?? 0);
$bad_comm_count     = (int)($m['bad_comm_count'] ?? 0);
$missing_info_count = (int)($m['missing_info_count'] ?? 0);
$other_penalty      = (int)($m['other_penalty'] ?? 0);

// penalti formulalari (moslab o‘zgartirishingiz mumkin)
$penalty_late   = $late_minutes * 300;
$penalty_absent = $absent_days * 100000;
$penalty_bad    = $bad_comm_count * 30000;
$penalty_miss   = $missing_info_count * 20000;

$penalties_list = [
  ['reason'=>'Kechikish (daqiqalar)', 'amount'=>$penalty_late],
  ['reason'=>'Ishga kelmaslik (kunlar)', 'amount'=>$penalty_absent],
  ['reason'=>'Yomon aloqa', 'amount'=>$penalty_bad],
  ['reason'=>'Ma’lumot yetishmasligi', 'amount'=>$penalty_miss],
];
if ($other_penalty !== 0) {
  $penalties_list[] = ['reason'=>'Boshqa jarima', 'amount'=>$other_penalty];
}
$penalties_total = $penalty_late + $penalty_absent + $penalty_bad + $penalty_miss + $other_penalty;

/* submissions statuslari: item_id => [approved,pending,rejected] (faqat approved hisoblanadi) */
$stat=[];
$qStat = "
  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
";
if ($rs = $db->query($qStat)) {
  while($x = $rs->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];
    if (isset($stat[$iid][$stt])) $stat[$iid][$stt]=$c;
  }
}

/* rejalarga asoslangan bonuslar */
$plans=[]; $dynamic_bonus=0; $avgPctSum=0; $avgCnt=0;

// shu oy uchun operatorga biriktirilgan planlar
$qPlans = "
  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
";
if ($rp = $db->query($qPlans)) {
  while($p = $rp->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=max(0, (int)($it['target_int'] ?? 0));
      $rew=max(0, (int)($it['reward_amount'] ?? 0));
      $calc=strtolower($it['reward_calc'] ?? 'proportional');
      $minp=(float)($it['reward_min_pct'] ?? 0.0); // 0..1 yoki 0..100 bo'lishi mumkin
      if($minp>1) $minp = $minp/100.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;
      $pctPay = $allow ? $pct : min(1.0, $pct);

      $earned=0;
      if($tgt>0 && $rew>0 && $pct >= $minp){
        if($calc==='threshold'){
          $earned = ($pct >= 1.0) ? $rew : 0;
        }else{
          $earned = (int)round($rew * $pctPay);
        }
      }

      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;
    if($planCnt>0){ $avgPctSum += ($planPctSum/$planCnt); $avgCnt++; }
  }
}

// boshqa bonus/umumiy hisob
$other_bonus = (int)($m['other_bonus'] ?? 0);
$gross = $base_amount + $dynamic_bonus + $other_bonus;
$net   = max(0, $gross - $penalties_total);

// finalize va imzo holati
$admin_finalized      = (int)($m['admin_finalized'] ?? 0);
$operator_sig_path    = $m['operator_signature_path'] ?? null;
$operator_signed_at   = $m['operator_signed_at'] ?? null;
$operator_signed      = ($operator_sig_path && $operator_signed_at) ? 1 : 0;

// FRONT-END kutgan shaklda qaytaramiz:
json_out([
  'ok'      => true,
  'ym'      => $ym,
  'operator'=> [
    'id'=>$op['id'],
    'name'=>$op['name'] ?? '',
    'code'=>$op['code'] ?? '',
    'department'=>$op['department'] ?? '',
    'region'=>$op['region'] ?? ''
  ],
  'plans'   => $plans,
  'breakdown' => [
    'base_amount'            => $base_amount,          // doim ko‘rsatiladi
    'base_confirmed'         => $base_confirmed,       // holatini ham qo‘yib beramiz
    'dynamic_bonus'          => $dynamic_bonus,
    'other_bonus'            => $other_bonus,
    'penalties_total'        => $penalties_total,
    'penalties_list'         => $penalties_list,       // tafsilotlar
    'gross'                  => $gross,
    'net'                    => $net,
    'admin_finalized'        => $admin_finalized,
    'operator_signed'        => $operator_signed,
    'operator_signature_path'=> $operator_sig_path,
    'operator_signed_at'     => $operator_signed_at
  ]
]);
