<?php
/**
 * tambah.php
 * Terima form POST (judul, isi, gambar, link) -> simpan ke data.json
 * -> trigger broadcast ke push_info_baru.php
 */
date_default_timezone_set('Asia/Jakarta');

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

// ===== CONFIG =====
$DATA_FILE  = __DIR__ . '/data.json';
$PUSH_URL   = 'https://mdcjombang.my.id/siap/push_info_baru.php';
$AUTH_TOKEN = 'eyJhcHAiOiIxMjkwNjgiLCJhdXRoIjoiMjAyMzAzMTQiLCJzaWduIjoiS1R1QytIS2o0d25EbkZwRGZuT0tzQT09In0=';
// ==================

function read_json($file) {
  if (!file_exists($file)) return [];
  $txt = file_get_contents($file);
  $arr = json_decode($txt, true);
  return is_array($arr) ? $arr : [];
}

function write_json($file, $arr) {
  $fp = fopen($file, 'c+');
  if (!$fp) return false;
  flock($fp, LOCK_EX);
  ftruncate($fp, 0);
  fwrite($fp, json_encode($arr, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT));
  fflush($fp);
  flock($fp, LOCK_UN);
  fclose($fp);
  return true;
}

// Validasi input
$judul = trim($_POST['judul'] ?? '');
$isi   = trim($_POST['isi'] ?? '');
$gambar = trim($_POST['gambar'] ?? '');
$link   = trim($_POST['link'] ?? '');

if ($judul === '' || $isi === '') {
  echo json_encode(['error' => 'Judul dan isi wajib diisi.']);
  exit;
}

// Siapkan record baru
$now = new DateTime('now', new DateTimeZone('Asia/Jakarta'));
$record = [
  'judul'   => $judul,
  'isi'     => $isi,
  'gambar'  => $gambar,
  'link'    => $link,
  'tanggal' => $now->format('c') // ISO 8601
];

// Baca data lama, prepend data baru (biar paling atas)
$data = read_json($DATA_FILE);
array_unshift($data, $record);

if (!write_json($DATA_FILE, $data)) {
  echo json_encode(['error' => 'Gagal menyimpan data. Pastikan permission file/folder.']);
  exit;
}

// ==== TRIGGER PUSH KE BUKAOLSHOP via push_info_baru.php ====
$payload = [
  'title'   => $judul,
  'message' => $isi,
  'link'    => $link,
  'image'   => $gambar
];

$ch = curl_init();
curl_setopt_array($ch, [
  CURLOPT_URL => $PUSH_URL,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_POST => true,
  CURLOPT_HTTPHEADER => [
    'Content-Type: application/json',
    'X-Auth-Token: ' . $AUTH_TOKEN,
    'Authorization: Bearer ' . $AUTH_TOKEN // fallback jika proxy hapus header custom
  ],
  CURLOPT_POSTFIELDS => json_encode($payload),
  CURLOPT_TIMEOUT => 60
]);

$pushRes = curl_exec($ch);
$err = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

$decoded = json_decode($pushRes, true);

if ($pushRes === false || $httpCode < 200 || $httpCode >= 300) {
  echo json_encode([
    'message'      => 'Informasi tersimpan. (Note: push gagal/kosong, cek server.)',
    'push_http'    => $httpCode,
    'push_raw'     => $pushRes,
    'push_error'   => $err,
    'push_decoded' => $decoded
  ]);
  exit;
}

echo json_encode([
  'message'      => 'Informasi berhasil ditambah & notifikasi dikirim.',
  'push_http'    => $httpCode,
  'push_decoded' => $decoded
]);