<?php
require_once __DIR__ . '/../config.php';
require_operator();

header('Content-Type: application/json; charset=utf-8');
date_default_timezone_set('Asia/Tashkent');

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

function json_out($d,$c=200){ http_response_code($c); header('Content-Type: application/json; charset=utf-8'); echo json_encode($d, JSON_UNESCAPED_UNICODE); exit; }
function norm($s){ return is_string($s)?trim($s):''; }
function i($v){ return (int)$v; }

$u = current_user();
$op_id = (int)($u['operator_id'] ?? 0);
if ($op_id <= 0) json_out(['ok'=>false,'error'=>'Operator bog'lanmagan'],403);

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

# metrics
$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];

# attendance-derived penalties (fallback 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);

$att = [
  'Kechikish (daqiqalar)'   => $late_minutes * 300,
  'Ishga kelmaslik (kunlar)'=> $absent_days * 100000,
  'Yomon aloqa'             => $bad_comm_count * 30000,
  'Ma’lumot yetishmasligi'  => $missing_info_count * 20000
];
$attendance_total = 0; foreach($att as $k=>$v){ $attendance_total += (int)$v; }

# manual items (operator_penalties)
$items = [];
@$r=$db->query("SELECT id, reason, amount, created_at FROM operator_penalties WHERE operator_id={$op_id} AND ym='".$db->real_escape_string($ym)."' ORDER BY id DESC");
if($r){ while($x=$r->fetch_assoc()) $items[]=$x; }
$items_total = 0; foreach($items as $it){ $items_total += (int)($it['amount'] ?? 0); }

$total = $attendance_total + $items_total;

json_out([
  'ok'=>true,
  'ym'=>$ym,
  'operator_id'=>$op_id,
  'metrics'=>$m,
  'attendance_penalties'=>$att,
  'attendance_total'=>$attendance_total,
  'items'=>$items,
  'items_total'=>$items_total,
  'total'=>$total
]);
