<?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 'PHPSESSID';
}

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';

session_name(pickSessionName());
session_start();
$userId = getUserId();

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

try {
  $db->beginTransaction();

  $convStmt = $db->prepare("SELECT * FROM pth_support_conversations WHERE id = :cid LIMIT 1");
  $convStmt->execute([':cid' => (int)$conversationId]);
  $conv = $convStmt->fetch(PDO::FETCH_ASSOC);
  if (!$conv) { $db->rollBack(); respond(404, ['error' => 'Conversation not found']); }

  $cid = (string)$conv['id'];
  $visitorId = (int)($conv['visitor_id'] ?? 0);
  $agentId = (int)($conv['agent_id'] ?? 0);

  $allowed = false;
  if (!empty($_SESSION['support_conversations'][$cid])) $allowed = true;
  if ($userId > 0 && $visitorId > 0 && $userId === $visitorId) $allowed = true;
  if ($userId > 0 && $agentId > 0 && $userId === $agentId) $allowed = true;
  if (!empty($_COOKIE['PHPSESSADM']) && $userId > 0) $allowed = true;

  if (!$allowed) { $db->rollBack(); respond(403, ['error' => 'Not allowed']); }

  $upd = $db->prepare("UPDATE pth_support_conversations SET state='CLOSED', updated_at=NOW() WHERE id=:cid");
  $upd->execute([':cid' => (int)$conversationId]);

  $qUpd = $db->prepare("UPDATE pth_support_queue SET status='CLOSED' WHERE conversation_id=:cid");
  $qUpd->execute([':cid' => (int)$conversationId]);

  $db->commit();

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

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

respond(200, ['ok' => true, 'status' => 'CLOSED']);
