<?php
declare(strict_types=1);

require_once __DIR__ . '/../_cors.php';
header('Content-Type: application/json; charset=utf-8');

function respond(int $status, array $payload): void {
  http_response_code($status);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}

function jsonBody(): array {
  $raw = file_get_contents('php://input');
  $data = json_decode($raw ?: '', true);
  if (!is_array($data)) respond(400, ['error' => 'Invalid JSON body']);
  return $data;
}

function pickSessionName(): ?string {
  if (!empty($_COOKIE['PHPSESSADM'])) return 'PHPSESSADM';
  if (!empty($_COOKIE['PHPSESSCLI'])) return 'PHPSESSCLI';
  if (!empty($_COOKIE['PHPSESSAFF'])) return 'PHPSESSAFF';
  return null;
}

function getUserId(): int {
  $uid = (int)($_SESSION['user_id'] ?? 0);
  if ($uid <= 0) $uid = (int)($_SESSION['SESS_MEMBER_ID'] ?? 0);
  return $uid;
}

require_once __DIR__ . '/../conn.php';
require_once __DIR__ . '/../config/pusher.php';

/** Must be authenticated staff/admin */
$sessionName = pickSessionName();
if (!$sessionName) respond(401, ['error' => 'Not authenticated (no valid session cookie)']);

session_name($sessionName);
session_start();

$agentId = getUserId();
if ($agentId <= 0) respond(401, ['error' => 'Not authenticated']);

$data = jsonBody();
$conversationId = (string)($data['conversationId'] ?? '');
if ($conversationId === '' || !ctype_digit($conversationId)) respond(400, ['error' => 'conversationId is required']);

try {
  $db->beginTransaction();

  // ensure queue is waiting
  $qStmt = $db->prepare("SELECT status FROM pth_support_queue WHERE conversation_id=:cid LIMIT 1");
  $qStmt->execute([':cid' => (int)$conversationId]);
  $qStatus = (string)($qStmt->fetchColumn() ?: '');

  if ($qStatus === '') {
    $db->rollBack();
    respond(404, ['error' => 'Conversation is not in queue']);
  }
  if ($qStatus !== 'WAITING') {
    $db->rollBack();
    respond(409, ['error' => 'Conversation already accepted/closed', 'status' => $qStatus]);
  }

  // agent name from `user` table (same as your staff chat)
  $nameStmt = $db->prepare("SELECT name FROM `user` WHERE id=:id LIMIT 1");
  $nameStmt->execute([':id' => $agentId]);
  $agentName = (string)($nameStmt->fetchColumn() ?: 'Agent');

  // assign agent + move state
  $upd = $db->prepare("
    UPDATE pth_support_conversations
    SET state='AGENT', agent_id=:aid, agent_name=:aname, updated_at=NOW()
    WHERE id=:cid AND state <> 'CLOSED'
  ");
  $upd->execute([
    ':aid' => $agentId,
    ':aname' => $agentName,
    ':cid' => (int)$conversationId,
  ]);

  // update queue
  $qUpd = $db->prepare("
    UPDATE pth_support_queue
    SET status='ACCEPTED', accepted_by=:aid, accepted_at=NOW()
    WHERE conversation_id=:cid AND status='WAITING'
  ");
  $qUpd->execute([':aid' => $agentId, ':cid' => (int)$conversationId]);

  if ($qUpd->rowCount() < 1) {
    $db->rollBack();
    respond(409, ['error' => 'Race condition: someone else accepted it']);
  }

  $db->commit();

} catch (Throwable $e) {
  if (isset($db) && $db->inTransaction()) $db->rollBack();
  respond(500, ['error' => 'Failed to accept handoff', 'message' => $e->getMessage()]);
}

/** Broadcast */
$pusher = pusher_instance();
$pusher->trigger("private-support.$conversationId", "handoff.accepted", [
  'conversationId' => (string)$conversationId,
  'agentId' => (string)$agentId,
  'ts' => date('c'),
]);

respond(200, ['ok' => true, 'status' => 'AGENT', 'agentId' => (string)$agentId]);
