<?php
/* API Keperawatan – MySQL backend (compat + verbose) */

/* ====== Error mode ======
 * Produksi: sembunyikan error HTML (biar output tetap JSON).
 * Waktu debug, akses endpoint debug pakai ?debug=1.
 */
error_reporting(E_ALL);
ini_set('display_errors', '0');             // <- set 1 sementara kalau masih 500
header('Content-Type: application/json; charset=utf-8');
date_default_timezone_set('Asia/Jakarta');

/* Toggle debug by query ?debug=1 */
if (!defined('DEBUG')) {
  define('DEBUG', (isset($_GET['debug']) && $_GET['debug'] == '1'));
}
$DEBUG_FLAG = DEBUG;

/* ========== CONFIG ========== */
define('API_KEY', 'b48255563262e29448a6ec087da6ad123e49fcdb5475d08b8fe2927b324f633b');

$dbhost = 'localhost';
$dbname = 'kepx5469_laporan_bulanan_RI_RJ';
$dbuser = 'kepx5469_spoweb';
$dbpass = 'Bosssakti';

/* ========== UTIL CORE ========== */
function out($arr, $code=200){ http_response_code($code); echo json_encode($arr, JSON_UNESCAPED_UNICODE); exit; }
function bad($msg, $code=400){ out(['ok'=>false,'message'=>$msg], $code); }

function pdo(){
  static $db=null; global $dbhost,$dbname,$dbuser,$dbpass;
  if ($db) return $db;
  try{
    $db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpass,[
      PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,
    ]);
    return $db;
  }catch(Throwable $e){ bad('DB connect error: '.$e->getMessage(), 500); }
}

/* header helper */
function all_headers(){
  if (function_exists('getallheaders')) return getallheaders();
  $out=[]; foreach($_SERVER as $k=>$v){ if(strpos($k,'HTTP_')===0){ $name=str_replace(' ','-',ucwords(strtolower(str_replace('_',' ',substr($k,5))))); $out[$name]=$v; } }
  return $out;
}

/* ambil key dari header/query/body */
function incoming_key(){
  $h = all_headers(); $cand=[];
  foreach($h as $n=>$v){ if (strtolower($n)==='x-api-key') $cand[]=$v; }
  if (!empty($h['Authorization']) && preg_match('/Bearer\s+(.+)/i',$h['Authorization'],$m)) $cand[]=$m[1];
  if (isset($_GET['key']))   $cand[]=$_GET['key'];
  if (isset($_GET['token'])) $cand[]=$_GET['token'];  // ✅ FIX: hapus kurung tutup ekstra
  if ($_SERVER['REQUEST_METHOD']==='POST'){
    $raw=file_get_contents('php://input'); $j=json_decode($raw,true);
    if (is_array($j) && !empty($j['api_key'])) $cand[]=$j['api_key'];
  }
  foreach($cand as $k){ $k=trim((string)$k); if($k!=='' && hash_equals(API_KEY,$k)) return $k; }
  return null;
}

function requireKey(){ if(!incoming_key()) out(['ok'=>false,'message'=>'Unauthorized'],401); }

function body(){ $raw=file_get_contents('php://input'); if(!$raw) return []; $j=json_decode($raw,true); return is_array($j)?$j:[]; }

function loadPayload($db,$reportId){
  $p=['metrics'=>[],'rka'=>[],'discipline'=>[],'issues'=>[],'qualityCsv'=>'','conclusionHtml'=>''];
  $st=$db->prepare("SELECT k,v FROM metrics WHERE report_id=?"); $st->execute([$reportId]); foreach($st as $r){ $p['metrics'][$r['k']]=$r['v']; }
  $st=$db->prepare("SELECT no_urut,kegiatan,tercapai,ket FROM rka WHERE report_id=? ORDER BY no_urut"); $st->execute([$reportId]); while($r=$st->fetch(PDO::FETCH_NUM)) $p['rka'][]=$r;
  $st=$db->prepare("SELECT no_urut,nama,jml_terlambat,alasan,tgl_pembinaan,ket FROM discipline WHERE report_id=? ORDER BY no_urut"); $st->execute([$reportId]); while($r=$st->fetch(PDO::FETCH_NUM)) $p['discipline'][]=$r;
  $st=$db->prepare("SELECT no_urut,hari,tanggal,masalah,tindak_lanjut,selesai,ket FROM issues WHERE report_id=? ORDER BY no_urut"); $st->execute([$reportId]); while($r=$st->fetch(PDO::FETCH_NUM)) $p['issues'][]=$r;
  $st=$db->prepare("SELECT csv_text FROM quality_csv WHERE report_id=?"); $st->execute([$reportId]); if($q=$st->fetch()) $p['qualityCsv']=(string)$q['csv_text'];
  $st=$db->prepare("SELECT html FROM conclusion WHERE report_id=?"); $st->execute([$reportId]); if($q=$st->fetch()) $p['conclusionHtml']=(string)$q['html'];
  return $p;
}
function uuid32(){ return bin2hex(random_bytes(16)); }

/* ========== ROUTER ========== */
$action = isset($_GET['action'])?$_GET['action']:'';
$b = body();

/* debug endpoints (tidak perlu key) */
if ($DEBUG_FLAG && $action==='whoami') out(['ok'=>true,'file'=>__FILE__,'php'=>PHP_VERSION]);
if ($DEBUG_FLAG && $action==='headers') out(['ok'=>true,'headers'=>all_headers()]);
if ($DEBUG_FLAG && $action==='debug_key') out(['ok'=>true,'incoming'=> incoming_key()!==null]);

/* semua endpoint non-debug perlu key */
requireKey();

try{
  $db = pdo();

  if ($action==='ping') out(['ok'=>true,'time'=>date('c')]);

  if ($action==='get_units'){
    $rows=$db->query("SELECT unit_id,unit_name,grp,kasubdiv,bed_count,use_bor_toi,active FROM units WHERE active=1 ORDER BY unit_name")->fetchAll();
    out(['ok'=>true,'units'=>$rows]);
  }

  if ($action==='find_or_create_report'){
    if (!empty($b['reportId'])){
      $st=$db->prepare("SELECT * FROM reports WHERE report_id=?"); $st->execute([$b['reportId']]);
      $rep=$st->fetch(); if(!$rep) bad('Report tidak ditemukan',404);
      $payload=loadPayload($db,$rep['report_id']); out(['ok'=>true,'report'=>$rep,'payload'=>$payload]);
    }
    $u=isset($b['unitId'])?$b['unitId']:''; $bln=(int)($b['bulan']??0); $thn=(int)($b['tahun']??0);
    if(!$u||!$bln||!$thn) bad('unitId/bulan/tahun wajib');
    $st=$db->prepare("SELECT * FROM reports WHERE unit_id=? AND bulan=? AND tahun=?"); $st->execute([$u,$bln,$thn]); $rep=$st->fetch();
    if(!$rep){
      $id=uuid32(); $now=date('Y-m-d H:i:s');
      $st=$db->prepare("INSERT INTO reports(report_id,unit_id,bulan,tahun,stage,status,title,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)");
      $st->execute([$id,$u,$bln,$thn,'unit','draft','Laporan Bulanan Keperawatan',$now,$now]);
      $rep=$db->query("SELECT * FROM reports WHERE report_id='$id'")->fetch();
    }
    $payload=loadPayload($db,$rep['report_id']); out(['ok'=>true,'report'=>$rep,'payload'=>$payload]);
  }

  if ($action==='save_report'){
    $id=$b['reportId']??''; if(!$id) bad('reportId wajib');
    $db->beginTransaction();

    if(!empty($b['metrics'])){
      $ps=$db->prepare("REPLACE INTO metrics(report_id,k,v) VALUES(?,?,?)");
      foreach($b['metrics'] as $k=>$v) $ps->execute([$id,$k,(string)$v]);
    }

    $db->prepare("DELETE FROM rka WHERE report_id=?")->execute([$id]);
    if(!empty($b['rka'])){
      $ps=$db->prepare("INSERT INTO rka(report_id,no_urut,kegiatan,tercapai,ket) VALUES(?,?,?,?,?)");
      foreach($b['rka'] as $r) $ps->execute([$id,(int)($r[0]??0),(string)($r[1]??''),(string)($r[2]??''),(string)($r[3]??'')]);
    }

    $db->prepare("DELETE FROM discipline WHERE report_id=?")->execute([$id]);
    if(!empty($b['discipline'])){
      $ps=$db->prepare("INSERT INTO discipline(report_id,no_urut,nama,jml_terlambat,alasan,tgl_pembinaan,ket) VALUES(?,?,?,?,?,?,?)");
      foreach($b['discipline'] as $r) $ps->execute([$id,(int)($r[0]??0),(string)($r[1]??''),(int)($r[2]??0),(string)($r[3]??''),($r[4]?:null),(string)($r[5]??'')]);
    }

    $db->prepare("DELETE FROM issues WHERE report_id=?")->execute([$id]);
    if(!empty($b['issues'])){
      $ps=$db->prepare("INSERT INTO issues(report_id,no_urut,hari,tanggal,masalah,tindak_lanjut,selesai,ket) VALUES(?,?,?,?,?,?,?,?)");
      foreach($b['issues'] as $r) $ps->execute([$id,(int)($r[0]??0),(string)($r[1]??''),($r[2]?:null),(string)($r[3]??''),(string)($r[4]??''),(string)($r[5]??''),(string)($r[6]??'')]);
    }

    $db->prepare("REPLACE INTO quality_csv(report_id,csv_text) VALUES(?,?)")->execute([$id,(string)($b['qualityCsv']??'')]);
    $db->prepare("REPLACE INTO conclusion(report_id,html) VALUES(?,?)")->execute([$id,(string)($b['conclusionHtml']??'')]);

    // ✅ FIX: hilangkan bracket ganda
    $db->prepare("UPDATE reports SET updated_at=NOW() WHERE report_id=?")->execute([$id]);

    // Recompute series
    $m=$b['metrics']??[]; $HP=(float)($m['ri.hariPerawatan']??0); $TT=(float)($m['ri.tempatTidur']??0);
    $days=(float)($m['umum.jumlahHari']??0); $keluar=(float)($m['ri.pasienKeluar']??0); $jumlah=(int)($m['umum.jumlahPasien']??0);
    $BOR=($HP>0&&$TT>0&&$days>0)?($HP/($TT*$days))*100:0; $TOI=($TT>0&&$days>0&&$keluar>0)?((($TT*$days)-$HP)/$keluar):0;

    $rep=$db->prepare("SELECT unit_id,bulan,tahun FROM reports WHERE report_id=?"); $rep->execute([$id]);
    if($row=$rep->fetch()){
      $ps=$db->prepare("INSERT INTO patient_series(unit_id,bulan,tahun,jumlah_pasien,bor,toi)
                        VALUES(?,?,?,?,?,?)
                        ON DUPLICATE KEY UPDATE jumlah_pasien=VALUES(jumlah_pasien), bor=VALUES(bor), toi=VALUES(toi)");
      $ps->execute([$row['unit_id'],(int)$row['bulan'],(int)$row['tahun'],$jumlah,$BOR,$TOI]);
    }

    $db->commit(); out(['ok'=>true]);
  }

  if ($action==='get_series'){
    $u=$_GET['unitId']??''; if(!$u) bad('unitId wajib');
    $st=$db->prepare("SELECT bulan,tahun,jumlah_pasien,bor,toi FROM patient_series WHERE unit_id=? ORDER BY tahun,bulan");
    $st->execute([$u]); out(['ok'=>true,'items'=>$st->fetchAll()]);
  }

  if ($action==='submit'){
    $id=$b['reportId']??''; if(!$id) bad('reportId wajib');
    $stages=['unit','kasubdiv','kadiv','direktur','final'];
    $st=$db->prepare("SELECT stage FROM reports WHERE report_id=?"); $st->execute([$id]); $r=$st->fetch(); if(!$r) bad('Report tidak ditemukan',404);
    $cur=$r['stage']?:'unit'; $idx=array_search($cur,$stages,true); if($idx===false)$idx=0;
    if($idx>=count($stages)-1){ $new='final'; $status='final'; } else { $new=$stages[$idx+1]; $status=($new==='final'?'final':'submitted'); }
    $ps=$db->prepare("UPDATE reports SET stage=?,status=?,updated_at=NOW() WHERE report_id=?"); $ps->execute([$new,$status,$id]);
    out(['ok'=>true,'stage'=>$new,'status'=>$status]);
  }

  bad('unknown action',404);

}catch(Throwable $e){
  bad('Server error: '.$e->getMessage(),500);
}
