<?php
require_once __DIR__ . '/../lib/payroll.php';
require_once __DIR__ . '/../lib/fpdf.php';
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');
$db=db();
$pdf=new FPDF();
$pdf->SetTitle("Oylik hisobot $ym");
$pdf->AddPage();

$pdf->SetFillColor(13,110,253);
$pdf->Rect(10,10,190,10,true);
$pdf->SetTextColor(255,255,255);
$pdf->Cell(190,8,"Oylik hisobot ($ym)",1,1);
$pdf->Ln(4);
$pdf->SetTextColor(0,0,0);

$ops=[]; $r=$db->query("SELECT * FROM operators WHERE active=1 ORDER BY name"); while($x=$r->fetch_assoc()) $ops[]=$x;

/* metrics */
$mm=[]; $st=$db->prepare("SELECT * FROM operator_monthly_metrics WHERE ym=?"); $st->bind_param("s",$ym); $st->execute(); $resM=$st->get_result(); while($x=$resM->fetch_assoc()) $mm[(int)$x['operator_id']]=$x; $st->close();
$TG=0; $TN=0;

foreach($ops as $o){
  $m=$mm[$o['id']]??['ym'=>$ym];
  $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);

  // approvals
  $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
  $dyn=0; $di=[];
  $qi=$db->query("SELECT i.id,i.title,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)."' ORDER BY i.plan_id,i.sort_order,i.id");
  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; $earned=earned_rule($approved,$tgt,$rew,$calc,$minp,$allow); $dyn+=$earned;
    $di[] = [$it['title'],$tgt,$approved,$calc,$rew,$earned];
  }

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

  // header per operator
  $pdf->SetFillColor(25,135,84); $pdf->Rect(10,$pdf->GetY(),190,7,true); $pdf->SetTextColor(255,255,255);
  $pdf->Cell(190,6,$o['name']." (".$o['code'].") — ".$o['department']." / ".$o['region'],1,1);
  $pdf->SetTextColor(0,0,0); $pdf->Ln(1);
  $pdf->Cell(190,6,"Asosiy: ".($base_confirmed?'tasdiqlangan':'kutilmoqda')." (".$base_amount.")  |  Dynamic bonus: ".$dyn,0,1);
  $pdf->Cell(190,6,"Gross: ".$gross."   |   Net: ".$net."   |   Jarima: ".$penalties,0,1);

  // dynamic items block
  $pdf->Ln(2);
  $pdf->SetFillColor(13,110,253); $pdf->Rect(10,$pdf->GetY(),190,6,true); $pdf->SetTextColor(255,255,255);
  $pdf->Cell(190,5,"Dynamic bonuslar tafsiloti",1,1); $pdf->SetTextColor(0,0,0);

  foreach($di as $drow){
    list($title,$tgt,$appr,$mode,$rew,$earn) = $drow;
    $pdf->SetFillColor(240,240,240); $pdf->Rect(10,$pdf->GetY(),190,6,true);
    $pdf->Cell(190,5,"$title — reja $tgt / appr $appr — mode $mode — reward $rew — earned $earn",0,1);
  }
  $pdf->Ln(2);

  $TG+=$gross; $TN+=$net;
}

$pdf->SetFillColor(13,110,253); $pdf->Rect(10,$pdf->GetY(),190,7,true); $pdf->SetTextColor(255,255,255);
$pdf->Cell(190,6,"Jami gross: $TG    |    Jami net: $TN",1,1);
$pdf->Output();
