<?php
require_once __DIR__ . '/../config.php';
function proportional_bonus($a,$t,$m){ if($t<=0) return 0; $r=$a/$t; if($r<0.5) return 0; if($r>=0.9) return (int)$m; return (int)round($m*$r); }
function rating_bonus($p){ if($p===1||$p==='1') return 200000; if($p===2||$p==='2') return 100000; return 0; }
function get_targets($ym){ $db=db(); $ym=$db->real_escape_string($ym); $q=$db->query("SELECT * FROM monthly_targets WHERE ym='$ym' LIMIT 1"); $row=$q?$q->fetch_assoc():null; if(!$row){ $db->query("INSERT INTO monthly_targets (ym) VALUES ('$ym')"); $q=$db->query("SELECT * FROM monthly_targets WHERE ym='$ym' LIMIT 1"); $row=$q->fetch_assoc(); } return $row; }
function compute_payroll_row($op,$m,$t){
  $def=(int)($t['base_fixed']??1500000);
  $base_conf=(int)($m['base_confirmed']??0); $base_amt=isset($m['base_amount'])?(int)$m['base_amount']:$def; $base=$base_conf?$base_amt:0;
  $bonus_reac=proportional_bonus((int)($m['reac_count']??0),(int)$t['target_reactivation'],(int)$t['bonus_reactivation_max']);
  $bonus_new=proportional_bonus((int)($m['new_count']??0),(int)$t['target_new'],(int)$t['bonus_new_max']);
  $bonus_flow=!empty($m['flow_report_submitted'])?(int)$t['bonus_flow_control']:0;
  $bonus_tg=((int)($m['telegram_added']??0)>=(int)$t['telegram_target'])?(int)$t['bonus_telegram']:0;
  $bonus_ig=(((int)($m['insta_accounts']??0)>=(int)$t['insta_accounts_target'])&&((int)($m['insta_videos']??0)>=(int)$t['insta_videos_target']))?(int)$t['bonus_instagram']:0;
  $bonus_rating=rating_bonus($m['rating_position']??null);
  $gross=$base+$bonus_reac+$bonus_new+$bonus_flow+$bonus_tg+$bonus_ig+$bonus_rating+(int)($m['other_bonus']??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);
  $net=max(0,$gross-$pen);
  return ['operator_id'=>$op['id'],'code'=>$op['code'],'name'=>$op['name'],'department'=>$op['department'],'region'=>$op['region'],'ym'=>$m['ym'],
    'base'=>$base,'base_amount'=>$base_amt,'base_confirmed'=>$base_conf,'base_pending'=>$base_conf?0:$base_amt,
    'bonus_reactivation'=>$bonus_reac,'bonus_new'=>$bonus_new,'bonus_flow_control'=>$bonus_flow,'bonus_telegram'=>$bonus_tg,'bonus_instagram'=>$bonus_ig,'bonus_rating'=>$bonus_rating,
    'gross'=>$gross,'penalties_total'=>$pen,'net'=>$net];
}
