<?php
/**
 * push_info_baru.php
 * Terima payload info baru -> ambil daftar member BukaOlshop (pagination) -> kirim notifikasi per-member.
 */
date_default_timezone_set('Asia/Jakarta');

/* =========================[ KONFIGURASI ]========================= */
const BUKAOLSHOP_API_BASE = 'https://bukaolshop.com/api/v1';
const BUKAOLSHOP_API_KEY  = 'cUZ2bGNpY3ZNYlMwanB0U1laKzRCampUWHBHRlpPT1A2MEFKcFZ5aUFRRTNJWjhObFVQUDBXb0k4dFVCMWdNeWlzTXpCUmJYMHo3MnFQRUhZcHhNYUxHQzhqZlBRQ1d5bUR3dU50QnVSM2RobXFjWmFQOGFoaGZSM0NLRjVMS0I5cHE4NXMxUkhxeElwMmdyTzNuckl5WFByTnk4UU95cUt1cTUrdjZISjBQMlpjSnpNNkp5UTN0Rlk2WFFFbjl2';
const AUTH_SHARED_TOKEN   = 'eyJhcHAiOiIxMjkwNjgiLCJhdXRoIjoiMjAyMzAzMTQiLCJzaWduIjoiS1R1QytIS2o0d25EbkZwRGZuT0tzQT09In0=';

const LAST_HASH_FILE      = __DIR__ . '/last_info_hash.txt'; // cache anti-duplikat konten
const BATCH_SIZE          = 100;   // ukuran batch kirim
const DELAY_MS            = 400;   // jeda antar request (ms) antisipasi rate-limit
const ONLY_ACTIVE_MEMBER  = true;  // hanya member aktif
const PER_PAGE            = 200;   // page size untuk /member/list
/* ================================================================= */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: https://mdcjombang.my.id'); // sesuaikan jika perlu
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Authorization');

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

// --- Ambil header auth secara robust ---
function get_header_case_insensitive($name) {
  $key = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
  if (!empty($_SERVER[$key])) return $_SERVER[$key];
  if (function_exists('getallheaders')) {
    $h = getallheaders();
    foreach ($h as $k => $v) if (strcasecmp($k, $name) === 0) return $v;
  }
  return null;
}

$provided = get_header_case_insensitive('X-Auth-Token');
if (!$provided) {
  $auth = get_header_case_insensitive('Authorization');
  if ($auth && stripos($auth, 'Bearer ') === 0) $provided = trim(substr($auth, 7));
}

if (!$provided || !hash_equals(AUTH_SHARED_TOKEN, trim($provided))) {
  http_response_code(401);
  echo json_encode(['ok' => false, 'error' => 'unauthorized']);
  exit;
}

// --- Validasi payload ---
$raw = file_get_contents('php://input');
$payload = json_decode($raw, true);
$title   = trim($payload['title']   ?? 'Informasi baru');
$message = trim($payload['message'] ?? '');
$link    = trim($payload['link']    ?? '');
$image   = trim($payload['image']   ?? ''); // opsional

if ($message === '') {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'message required']);
  exit;
}

// --- Anti-duplikat berdasarkan hash konten terbaru ---
$hash_input = $title . '|' . $message . '|' . $link . '|' . $image;
$now_hash = hash('sha256', $hash_input);
$prev_hash = is_file(LAST_HASH_FILE) ? trim(@file_get_contents(LAST_HASH_FILE)) : '';
if ($prev_hash === $now_hash) {
  echo json_encode(['ok' => true, 'skipped' => true, 'reason' => 'same_content']);
  exit;
}

// =================== Helper HTTP ===================
function http_get($url, $query = []) {
  $ch = curl_init();
  if (!empty($query)) $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($query);
  curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 45,
    CURLOPT_HTTPHEADER => [
      'Authorization: Bearer ' . BUKAOLSHOP_API_KEY,
      'Accept: application/json',
    ],
  ]);
  $res = curl_exec($ch);
  $err = curl_error($ch);
  $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
  curl_close($ch);
  return [$status, $res, $err];
}

function http_post_form($url, $fields) {
  $ch = curl_init();
  curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 60,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
      'Authorization: Bearer ' . BUKAOLSHOP_API_KEY,
      'Accept: application/json',
    ],
    CURLOPT_POSTFIELDS => $fields, // multipart/form-data otomatis
  ]);
  $res = curl_exec($ch);
  $err = curl_error($ch);
  $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
  curl_close($ch);
  return [$status, $res, $err];
}

function msleep($ms) { usleep(max(0, intval($ms * 1000))); }
// ====================================================

// ====== Ambil semua member (pagination) ======
$allMembers = [];
$page = 1;

do {
  $params = ['page' => $page, 'per_page' => PER_PAGE];
  if (ONLY_ACTIVE_MEMBER) $params['status'] = 'active';

  list($stMember, $resMember, $errMember) = http_get(BUKAOLSHOP_API_BASE . '/member/list', $params);
  if ($stMember < 200 || $stMember >= 300) {
    http_response_code(502);
    echo json_encode([
      'ok' => false,
      'error' => 'member_list_failed',
      'status' => $stMember,
      'detail' => $resMember ?: $errMember,
      'page' => $page
    ]);
    exit;
  }

  $memberJson = json_decode($resMember, true);
  $chunk = $memberJson['data'] ?? $memberJson['members'] ?? $memberJson ?? [];
  if (!is_array($chunk)) $chunk = [];

  $allMembers = array_merge($allMembers, $chunk);

  $hasMore = count($chunk) >= PER_PAGE;
  $page++;
} while ($hasMore);

$members = $allMembers;

$total = count($members);
$sent = 0; $fail = 0; $results = [];

if ($total === 0) {
  @file_put_contents(LAST_HASH_FILE, $now_hash);
  echo json_encode(['ok' => true, 'targets' => 0, 'sent' => 0, 'fail' => 0]);
  exit;
}

// ====== Kirim notifikasi per-member ======
$chunks = array_chunk($members, BATCH_SIZE);
foreach ($chunks as $batchIndex => $chunk) {
  foreach ($chunk as $m) {
    $idUser = $m['id_user'] ?? $m['id'] ?? null;
    $email  = $m['email']   ?? null;

    $form = [
      'judul_notifikasi' => $title,
      'pesan_notifikasi' => $message . ($link ? "\n\nSelengkapnya: $link" : ''),
    ];
    if (!empty($idUser)) {
      $form['id_user'] = (string)$idUser;
    } elseif (!empty($email)) {
      $form['email_user'] = $email;
    } else {
      $fail++;
      $results[] = ['target' => null, 'ok' => false, 'reason' => 'no_id_or_email'];
      continue;
    }

    if (!empty($image)) $form['url_gambar'] = $image;

    list($st, $res, $err) = http_post_form(BUKAOLSHOP_API_BASE . '/member/notifikasi', $form);
    if ($st >= 200 && $st < 300) {
      $sent++;
      $results[] = ['target' => $form['id_user'] ?? $form['email_user'], 'ok' => true];
    } else {
      $fail++;
      // log error ringkas (hapus bila sudah stabil)
      @file_put_contents(__DIR__.'/push_debug.log', date('c')." | target=".($form['id_user'] ?? $form['email_user'])." | HTTP:$st | ".$res." | err:$err\n", FILE_APPEND);

      $results[] = [
        'target' => $form['id_user'] ?? $form['email_user'],
        'ok' => false,
        'status' => $st,
        'detail' => $res ?: $err
      ];
      if ($st == 429 || $st >= 500) { msleep(1200); }
    }

    msleep(DELAY_MS);
  }

  if ($batchIndex < (count($chunks) - 1)) msleep(2000);
}

@file_put_contents(LAST_HASH_FILE, $now_hash);

echo json_encode([
  'ok' => true,
  'targets' => $total,
  'sent' => $sent,
  'fail' => $fail,
  'sample' => array_slice($results, 0, 5)
]);