<?php
// ==========================================================
// api.php  —  RS Balimed Poliklinik API
// ==========================================================

// ------ DEBUG (matikan di produksi) ------
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ------ HEADERS dasar ------
header('Content-Type: application/json; charset=utf-8');

// ------ CONFIG ------
$cfgPath = __DIR__ . '/config.php';
if (!file_exists($cfgPath)) {
  http_response_code(500);
  echo json_encode(['ok' => false, 'error' => 'config.php not found']);
  exit;
}
$CFG = require $cfgPath;

// Zona waktu & CORS
date_default_timezone_set($CFG['TZ'] ?? 'Asia/Jakarta');
$CORS = $CFG['CORS_ORIGIN'] ?? '*';
header('Access-Control-Allow-Origin: ' . $CORS);
header('Access-Control-Allow-Headers: X-API-Key, X-APIKEY, Content-Type');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

// Preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  http_response_code(204);
  exit;
}

// ------ HELPERS ------
function out($data, int $code = 200) {
  http_response_code($code);
  echo json_encode($data, JSON_UNESCAPED_UNICODE);
  exit;
}

function get_action(): string {
  // query/body
  $action = $_GET['action'] ?? $_POST['action'] ?? '';

  // path (…/api.php/<action>)
  if (!$action) {
    $path = $_SERVER['PATH_INFO'] ?? '';
    if (!$path && isset($_SERVER['REQUEST_URI'])) {
      $path = explode('?', $_SERVER['REQUEST_URI'], 2)[0];
    }
    if ($path) {
      $parts = array_values(array_filter(explode('/', $path)));
      if (!empty($parts)) {
        $last = end($parts);
        if (stripos($last, '.php') === false) $action = $last;
      }
    }
  }
  return trim($action);
}

/** Ambil api key: header || $_SERVER || query/body */
function read_api_key(): ?string {
  if (function_exists('getallheaders')) {
    foreach (getallheaders() as $k => $v) {
      if (strcasecmp($k, 'X-API-Key') === 0 || strcasecmp($k, 'X-APIKEY') === 0) {
        $v = trim($v);
        if ($v !== '') return $v;
      }
    }
  }
  foreach (['HTTP_X_API_KEY','HTTP_X_APIKEY','X_API_KEY','X_APIKEY','HTTP_X_API_KEY_'] as $h) {
    if (!empty($_SERVER[$h])) return trim($_SERVER[$h]);
  }
  if (isset($_GET['api_key']))  return trim((string)$_GET['api_key']);
  if (isset($_POST['api_key'])) return trim((string)$_POST['api_key']);
  return null;
}

function require_auth(array $CFG) {
  $key = read_api_key();
  if (!$key || !hash_equals($CFG['API_KEY'], $key)) {
    out(['ok' => false, 'error' => 'Unauthorized'], 401);
  }
}

/** Normalisasi tanggal: "YYYY-MM-DD" | "dd/mm/yyyy" | string strtotime */
function ymd_or_null($s): ?string {
  if ($s === null) return null;
  $s = trim((string)$s);
  if ($s === '') return null;

  if (preg_match('~^(\d{4})-(\d{1,2})-(\d{1,2})$~', $s, $m)) {
    return sprintf('%04d-%02d-%02d', $m[1], $m[2], $m[3]);
  }
  if (preg_match('~^(\d{1,2})/(\d{1,2})/(\d{4})$~', $s, $m)) {
    return sprintf('%04d-%02d-%02d', $m[3], $m[2], $m[1]);
  }
  $t = strtotime($s);
  return $t ? date('Y-m-d', $t) : null;
}

/** Map row laporan ke struktur yang dipakai UI */
function map_report_row(array $r): array {
  $tgl = $r['tanggal_laporan'];
  if ($tgl === '0000-00-00' || !$tgl) $tgl = null;

  $jd = json_decode($r['kunjungan_dokter'] ?? '[]', true);
  if (!is_array($jd)) $jd = [];
  $jt = json_decode($r['dokter_tidak_praktek'] ?? '[]', true);
  if (!is_array($jt)) $jt = [];

  return [
    'id'                 => (int)$r['id'],
    'tanggal'            => $tgl,
    'shift'              => $r['shift'],
    'kunjunganDokter'    => $jd,
    'dokterTidakPraktek' => $jt,
    'pasienKhusus'       => $r['pasien_khusus'],
    'masalah'            => $r['masalah_kendala'],
    'inventaris'         => $r['inventaris_logistik'],
    'petugasEcho'        => $r['petugas_echo'],
    'petugasTreadmill'   => $r['petugas_treadmill'],
    'petugasEKG'         => $r['petugas_ekg'],
    'namaKatim'          => $r['nama_katim'],
  ];
}

// ------ ROUTER ------
$action = get_action();

// /ping tanpa DB & tanpa auth → untuk cek cepat
if ($action === 'ping') {
  out(['ok' => true, 'ts' => date('c')]);
}

// selain ping → wajib API key
require_auth($CFG);

// ------ DB CONNECT ------
try {
  $pdo = new PDO(
    "mysql:host={$CFG['DB_HOST']};dbname={$CFG['DB_NAME']};charset=utf8mb4",
    $CFG['DB_USER'],
    $CFG['DB_PASS'],
    [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]
  );
} catch (Exception $e) {
  out(['ok' => false, 'error' => 'DB failed: ' . $e->getMessage()], 500);
}

// ------ ENDPOINTS ------

// GET /listDoctors
if ($action === 'listDoctors') {
  $rows = $pdo->query(
    "SELECT nama_dokter FROM doctors WHERE COALESCE(aktif,1)=1 ORDER BY nama_dokter ASC"
  )->fetchAll(PDO::FETCH_COLUMN);
  out(['ok' => true, 'items' => $rows]);
}

// POST /bulkUpsertDoctors  (body: {items:[...]} atau {text:"nama\nnama"})
// Pastikan ada index unik: ALTER TABLE doctors ADD UNIQUE KEY uq_nama_dokter(nama_dokter);
if ($action === 'bulkUpsertDoctors') {
  $payload = json_decode(file_get_contents('php://input'), true) ?: [];
  $items = [];
  if (!empty($payload['items']) && is_array($payload['items'])) {
    $items = $payload['items'];
  } elseif (!empty($payload['text'])) {
    $items = array_filter(array_map('trim', preg_split('~\r?\n~', $payload['text'])));
  }
  if (!$items) out(['ok' => false, 'error' => 'No items'], 400);

  $stmt = $pdo->prepare(
    "INSERT INTO doctors(nama_dokter, aktif) VALUES(?,1)
     ON DUPLICATE KEY UPDATE aktif=VALUES(aktif)"
  );
  $n = 0;
  foreach ($items as $name) {
    $name = trim((string)$name);
    if ($name === '') continue;
    $stmt->execute([$name]);
    $n++;
  }
  out(['ok' => true, 'inserted' => $n]);
}

// GET /listStaff
if ($action === 'listStaff') {
  $rows = $pdo->query("SELECT nama_staf FROM staff ORDER BY nama_staf ASC")
              ->fetchAll(PDO::FETCH_COLUMN);
  out(['ok' => true, 'items' => $rows]);
}

// POST /saveDraft  atau  /saveReport  (alias)
if ($action === 'saveDraft' || $action === 'saveReport') {
  $p = json_decode(file_get_contents('php://input'), true) ?: [];

  $tgl   = ymd_or_null($p['tanggal'] ?? null);
  $shift = trim((string)($p['shift'] ?? ''));
  $kunj  = json_encode($p['kunjunganDokter'] ?? []);
  $off   = json_encode($p['dokterTidakPraktek'] ?? []);

  $stmt = $pdo->prepare(
    "INSERT INTO laporan_poliklinik
     (tanggal_laporan, shift, kunjungan_dokter, dokter_tidak_praktek,
      pasien_khusus, masalah_kendala, inventaris_logistik,
      petugas_echo, petugas_treadmill, petugas_ekg, nama_katim)
     VALUES (?,?,?,?,?,?,?,?,?,?,?)"
  );

  $stmt->execute([
    $tgl,
    $shift,
    $kunj,
    $off,
    $p['pasienKhusus'] ?? '',
    $p['masalah'] ?? '',
    $p['inventaris'] ?? '',
    $p['petugasEcho'] ?? '',
    $p['petugasTreadmill'] ?? '',
    $p['petugasEKG'] ?? '',
    $p['namaKatim'] ?? ''
  ]);

  out(['ok' => true, 'message' => 'Laporan berhasil disimpan', 'id' => $pdo->lastInsertId()]);
}

// GET /listReports
if ($action === 'listReports') {
  $sql = "SELECT id, tanggal_laporan, shift, kunjungan_dokter, dokter_tidak_praktek,
                 pasien_khusus, masalah_kendala, inventaris_logistik,
                 petugas_echo, petugas_treadmill, petugas_ekg, nama_katim
          FROM laporan_poliklinik
          ORDER BY NULLIF(tanggal_laporan,'0000-00-00') DESC, id DESC
          LIMIT 200";
  $rows  = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
  $items = array_map('map_report_row', $rows);
  out(['ok' => true, 'items' => $items]);
}

// GET /latestReport
if ($action === 'latestReport') {
  $sql = "SELECT * FROM laporan_poliklinik
          ORDER BY NULLIF(tanggal_laporan,'0000-00-00') DESC, id DESC
          LIMIT 1";
  $row = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
  if (!$row) out(['ok' => false, 'error' => 'No data'], 404);
  out(['ok' => true, 'report' => map_report_row($row)]);
}

// POST /cloneReport  (body: {source_id, target_date, target_shift})
if ($action === 'cloneReport') {
  $p = json_decode(file_get_contents('php://input'), true) ?: [];
  $sourceId    = (int)($p['source_id'] ?? 0);
  $targetDate  = ymd_or_null($p['target_date'] ?? null);
  $targetShift = trim((string)($p['target_shift'] ?? ''));

  if (!$sourceId || !$targetDate || !$targetShift) {
    out(['ok' => false, 'error' => 'Missing source_id / target_date / target_shift'], 400);
  }

  $get = $pdo->prepare("SELECT * FROM laporan_poliklinik WHERE id=?");
  $get->execute([$sourceId]);
  $row = $get->fetch(PDO::FETCH_ASSOC);
  if (!$row) out(['ok' => false, 'error' => 'Source not found'], 404);

  $ins = $pdo->prepare(
    "INSERT INTO laporan_poliklinik
     (tanggal_laporan, shift, kunjungan_dokter, dokter_tidak_praktek,
      pasien_khusus, masalah_kendala, inventaris_logistik,
      petugas_echo, petugas_treadmill, petugas_ekg, nama_katim)
     VALUES (?,?,?,?,?,?,?,?,?,?,?)"
  );
  $ins->execute([
    $targetDate,
    $targetShift,
    $row['kunjungan_dokter'],
    $row['dokter_tidak_praktek'],
    $row['pasien_khusus'],
    $row['masalah_kendala'],
    $row['inventaris_logistik'],
    $row['petugas_echo'],
    $row['petugas_treadmill'],
    $row['petugas_ekg'],
    $row['nama_katim']
  ]);

  out(['ok' => true, 'new_id' => $pdo->lastInsertId()]);
}

// GET /debug  (jangan aktifkan di publik bila tak perlu)
if ($action === 'debug') {
  out([
    'ok'          => true,
    'php_version' => PHP_VERSION,
    'time'        => date('c'),
    'server'      => [
      'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'] ?? null,
      'REQUEST_URI' => $_SERVER['REQUEST_URI'] ?? null,
      'METHOD'      => $_SERVER['REQUEST_METHOD'] ?? null,
    ],
    'cors_origin' => $CORS,
  ]);
}

// Default 404
out(['ok' => false, 'error' => 'Route not found'], 404);
