<?php
require_once __DIR__ . '/../config.php';
if (function_exists('require_admin')) require_admin(); // faqat admin
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; }

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = $_GET['action'] ?? '';

if ($method==='GET' && $action==='summary') {
  $ym = norm($_GET['ym'] ?? ''); $op_id = i($_GET['operator_id'] ?? 0);
  if(!$ym || !$op_id) json_out(['ok'=>false,'error'=>'ym,operator_id shart'],400);

  // 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];

  // penalties items
  $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");
  while($x=$r->fetch_assoc()) $items[]=$x;

  json_out(['ok'=>true,'metrics'=>$m,'items'=>$items]);
}

/* metrics saqlash: base_amount, base_confirmed, late_minutes, absent_days, bad_comm_count, missing_info_count, other_penalty, other_bonus, admin_finalized */
if ($method==='POST' && $action==='save_metrics') {
  $in = json_decode(file_get_contents('php://input'), true);
  if(!is_array($in)) json_out(['ok'=>false,'error'=>'Bad JSON'],400);
  $ym = norm($in['ym'] ?? ''); $op_id = i($in['operator_id'] ?? 0);
  if(!$ym || !$op_id) json_out(['ok'=>false,'error'=>'ym,operator_id shart'],400);

  $fields = [
    'base_amount'=>i($in['base_amount'] ?? 0),
    'base_confirmed'=>i($in['base_confirmed'] ?? 0),
    'late_minutes'=>i($in['late_minutes'] ?? 0),
    'absent_days'=>i($in['absent_days'] ?? 0),
    'bad_comm_count'=>i($in['bad_comm_count'] ?? 0),
    'missing_info_count'=>i($in['missing_info_count'] ?? 0),
    'other_penalty'=>i($in['other_penalty'] ?? 0),
    'other_bonus'=>i($in['other_bonus'] ?? 0),
    'admin_finalized'=>i($in['admin_finalized'] ?? 0),
  ];

  // upsert
  $ex=$db->prepare("SELECT id FROM operator_monthly_metrics WHERE operator_id=? AND ym=? LIMIT 1");
  $ex->bind_param("is",$op_id,$ym); $ex->execute(); $row=$ex->get_result()->fetch_assoc(); $ex->close();

  if($row){
    $sql="UPDATE operator_monthly_metrics SET base_amount=?, base_confirmed=?, late_minutes=?, absent_days=?, bad_comm_count=?, missing_info_count=?, other_penalty=?, other_bonus=?, admin_finalized=? WHERE operator_id=? AND ym=?";
    $st=$db->prepare($sql);
    $st->bind_param("iiiiiiiiiss",
      $fields['base_amount'],$fields['base_confirmed'],$fields['late_minutes'],$fields['absent_days'],
      $fields['bad_comm_count'],$fields['missing_info_count'],$fields['other_penalty'],$fields['other_bonus'],
      $fields['admin_finalized'],$op_id,$ym);
    $st->execute(); $st->close();
  }else{
    $sql="INSERT INTO operator_monthly_metrics (operator_id,ym,base_amount,base_confirmed,late_minutes,absent_days,bad_comm_count,missing_info_count,other_penalty,other_bonus,admin_finalized) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
    $st=$db->prepare($sql);
    $st->bind_param("isiiiiiiiii",$op_id,$ym,$fields['base_amount'],$fields['base_confirmed'],$fields['late_minutes'],$fields['absent_days'],$fields['bad_comm_count'],$fields['missing_info_count'],$fields['other_penalty'],$fields['other_bonus'],$fields['admin_finalized']);
    $st->execute(); $st->close();
  }
  json_out(['ok'=>true]);
}

/* Penalty item qo‘shish */
if ($method==='POST' && $action==='add_item') {
  $in = json_decode(file_get_contents('php://input'), true);
  if(!is_array($in)) json_out(['ok'=>false,'error'=>'Bad JSON'],400);
  $ym = norm($in['ym'] ?? ''); $op_id = i($in['operator_id'] ?? 0);
  $reason = norm($in['reason'] ?? ''); $amount = i($in['amount'] ?? 0);
  $uid = i(current_user()['id'] ?? 0);
  if(!$ym || !$op_id || !$reason) json_out(['ok'=>false,'error'=>'ym,operator_id,reason shart'],400);
  $st=$db->prepare("INSERT INTO operator_penalties (operator_id,ym,reason,amount,created_by) VALUES (?,?,?,?,?)");
  $st->bind_param("issii",$op_id,$ym,$reason,$amount,$uid);
  $st->execute();
  json_out(['ok'=>true,'id'=>$st->insert_id]);
}

/* Penalty item update */
if ($method==='POST' && $action==='update_item') {
  $in = json_decode(file_get_contents('php://input'), true);
  if(!is_array($in)) json_out(['ok'=>false,'error'=>'Bad JSON'],400);
  $id=i($in['id'] ?? 0); $reason=norm($in['reason'] ?? ''); $amount=i($in['amount'] ?? 0);
  if(!$id || !$reason) json_out(['ok'=>false,'error'=>'id,reason shart'],400);
  $st=$db->prepare("UPDATE operator_penalties SET reason=?, amount=? WHERE id=?");
  $st->bind_param("sii",$reason,$amount,$id);
  $st->execute();
  json_out(['ok'=>true]);
}

/* Penalty item delete */
if ($method==='POST' && $action==='delete_item') {
  $in = json_decode(file_get_contents('php://input'), true);
  if(!is_array($in)) json_out(['ok'=>false,'error'=>'Bad JSON'],400);
  $id = i($in['id'] ?? 0);
  if(!$id) json_out(['ok'=>false,'error'=>'id shart'],400);
  $db->query("DELETE FROM operator_penalties WHERE id=$id");
  json_out(['ok'=>true]);
}

json_out(['ok'=>false,'error'=>'Unknown action'],404);
