<?php
require_once __DIR__ . '/../config.php';
require_admin();
header('Content-Type: application/json; charset=utf-8');

$db = contracts_db();
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = $_GET['action'] ?? '';

function bad($m,$c=400){ json_out(['error'=>$m],$c); }

if ($method==='GET' && $action==='status') {
  $ym = $_GET['ym'] ?? date('Y-m'); $ymq=$db->real_escape_string($ym);
  $rows=[]; $q=$db->query("SELECT o.id operator_id,o.name,IFNULL(m.admin_finalized,0) admin_finalized,m.operator_signature_path FROM operators o LEFT JOIN operator_monthly_metrics m ON m.operator_id=o.id AND m.ym='$ymq' WHERE o.active=1 ORDER BY o.name");
  $fin=0;$sig=0; while($r=$q->fetch_assoc()){ $r['admin_finalized']=(int)$r['admin_finalized']; if($r['admin_finalized'])$fin++; if($r['operator_signature_path'])$sig++; $rows[]=$r; }
  json_out(['per_operator'=>$rows,'totals'=>['finalized'=>$fin,'signed'=>$sig],'ym'=>$ym]);
}

if ($method==='POST' && in_array($action,['finalize_all','unfinalize_all','finalize_one','unfinalize_one'])) {
  $in=json_decode(file_get_contents('php://input'),true); if(!is_array($in)) bad('Bad JSON');
  $ym=$in['ym']??null; if(!$ym) bad('ym required'); $ymq=$db->real_escape_string($ym); $now=date('Y-m-d H:i:s');

  if($action==='finalize_all' || $action==='unfinalize_all'){
    $setVal = ($action==='finalize_all')?1:0;
    $ops=[]; $r=$db->query("SELECT id FROM operators WHERE active=1"); while($x=$r->fetch_assoc()) $ops[]=(int)$x['id'];
    foreach($ops as $op){
      $st=$db->prepare("SELECT id FROM operator_monthly_metrics WHERE operator_id=? AND ym=?"); $st->bind_param("is",$op,$ym); $st->execute(); $ex=$st->get_result()->fetch_assoc(); $st->close();
      if($ex){
        if($setVal){ $q=$db->prepare("UPDATE operator_monthly_metrics SET admin_finalized=1, admin_finalized_at=? WHERE operator_id=? AND ym=?"); $q->bind_param("sis",$now,$op,$ym); }
        else       { $q=$db->prepare("UPDATE operator_monthly_metrics SET admin_finalized=0, admin_finalized_at=NULL WHERE operator_id=? AND ym=?"); $q->bind_param("is",$op,$ym); }
        $q->execute();
      }else{
        if($setVal){ $q=$db->prepare("INSERT INTO operator_monthly_metrics (operator_id,ym,admin_finalized,admin_finalized_at) VALUES (?,?,1,?)"); $q->bind_param("iss",$op,$ym,$now); $q->execute(); }
        else       { $q=$db->prepare("INSERT INTO operator_monthly_metrics (operator_id,ym,admin_finalized) VALUES (?,?,0)"); $q->bind_param("is",$op,$ym); $q->execute(); }
      }
    }
    json_out(['ok'=>true]);
  }

  $op=(int)($in['operator_id']??0); if(!$op) bad('operator_id required');
  $st=$db->prepare("SELECT id FROM operator_monthly_metrics WHERE operator_id=? AND ym=?"); $st->bind_param("is",$op,$ym); $st->execute(); $ex=$st->get_result()->fetch_assoc(); $st->close();

  if($action==='finalize_one'){
    if($ex){ $q=$db->prepare("UPDATE operator_monthly_metrics SET admin_finalized=1, admin_finalized_at=? WHERE operator_id=? AND ym=?"); $q->bind_param("sis",$now,$op,$ym); }
    else   { $q=$db->prepare("INSERT INTO operator_monthly_metrics (operator_id,ym,admin_finalized,admin_finalized_at) VALUES (?,?,1,?)"); $q->bind_param("iss",$op,$ym,$now); }
    $q->execute(); json_out(['ok'=>true]);
  } else {
    if($ex){ $q=$db->prepare("UPDATE operator_monthly_metrics SET admin_finalized=0, admin_finalized_at=NULL WHERE operator_id=? AND ym=?"); $q->bind_param("is",$op,$ym); $q->execute(); }
    json_out(['ok'=>true]);
  }
}

json_out(['error'=>'Method not allowed'],405);
