<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db.php';

$TOKEN = "SUPER_SECRET_TOKEN"; // BUNU DEGISTIR

if($_SERVER['REQUEST_METHOD'] !== 'POST'){
  http_response_code(405);
  echo json_encode(["ok"=>false,"error"=>"Method not allowed"]); exit;
}

$token = $_POST['token'] ?? '';
if($token !== $TOKEN){
  http_response_code(403);
  echo json_encode(["ok"=>false,"error"=>"Forbidden"]); exit;
}

$client_id     = trim($_POST['client_id'] ?? '');
$party_count   = intval($_POST['party_count'] ?? 0);
$gold          = intval($_POST['gold'] ?? 0);
$dropped_slots = trim($_POST['dropped_slots'] ?? '');

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

$now = date('Y-m-d H:i:s');

// Önceki değer
$stmt = $pdo->prepare("SELECT party_count FROM clients WHERE client_id=?");
$stmt->execute([$client_id]);
$prev = $stmt->fetchColumn();
$prev = ($prev === false) ? null : intval($prev);

// clients tablosuna yaz (upsert)
$stmt = $pdo->prepare("
  INSERT INTO clients (client_id, party_count, gold, dropped_slots, last_seen)
  VALUES (?, ?, ?, ?, ?)
  ON DUPLICATE KEY UPDATE
    party_count=VALUES(party_count),
    gold=VALUES(gold),
    dropped_slots=VALUES(dropped_slots),
    last_seen=VALUES(last_seen)
");
$stmt->execute([$client_id, $party_count, $gold, $dropped_slots, $now]);

// Düşüş alerti
if($prev !== null && $party_count < $prev){
  $stmt = $pdo->prepare("
    INSERT INTO alerts (client_id, prev_count, new_count, dropped_slots, created_at)
    VALUES (?, ?, ?, ?, ?)
  ");
  $stmt->execute([$client_id, $prev, $party_count, $dropped_slots, $now]);
}

echo json_encode(["ok"=>true]);
