<?php
declare(strict_types=1);

/* =========================
   CORS (FIXED)
   ========================= */

// In case Apache/Nginx already injected something like '*'
header_remove('Access-Control-Allow-Origin');
header_remove('Access-Control-Allow-Headers');
header_remove('Access-Control-Allow-Methods');
header_remove('Access-Control-Allow-Credentials');

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

$allowed = [
  'http://localhost:5174',
  'http://127.0.0.1:5174',
];

if ($origin && in_array($origin, $allowed, true)) {
  header("Access-Control-Allow-Origin: {$origin}");
  header("Vary: Origin");
  header("Access-Control-Allow-Credentials: true");
}

header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, Accept");
header("Access-Control-Max-Age: 86400");

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

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


/* =========================================================
   LOGGING
   ========================================================= */

function log_error(string $message, array $context = []): void {
    $entry = [
        'ts' => date('c'),
        'endpoint' => 'conversations/create.php',
        'message' => $message,
        'context' => $context,
    ];
    error_log('[SUPPORT_API] ' . json_encode($entry, JSON_UNESCAPED_SLASHES));
}

/* =========================================================
   HELPERS
   ========================================================= */

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)) {
        log_error('Invalid JSON body', [
            'raw_len' => strlen($raw ?: ''),
            'content_type' => $_SERVER['CONTENT_TYPE'] ?? null,
            'ip' => $_SERVER['REMOTE_ADDR'] ?? null,
            'ua' => $_SERVER['HTTP_USER_AGENT'] ?? null,
        ]);
        respond(400, ['ok' => false, 'error' => 'Invalid JSON body']);
    }

    return $data;
}

function clean(?string $s): ?string {
    $s = trim((string)$s);
    return $s === '' ? null : $s;
}

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

/* =========================================================
   DB
   ========================================================= */

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

/* =========================================================
   SESSION (BEST-EFFORT)
   ========================================================= */

session_name(pickSessionName());
session_start();

$userId = getUserId();

/* =========================================================
   INPUT
   ========================================================= */

$data = jsonBody();

$sessionId     = clean($data['sessionId'] ?? null);
$source        = clean($data['source'] ?? null) ?? 'chatbot';
$visitorName   = clean($data['visitorName'] ?? null);
$visitorEmail  = clean($data['visitorEmail'] ?? null);
$visitorPhone  = clean($data['visitorPhone'] ?? null);

if (!$sessionId) {
    log_error('Missing sessionId', [
        'userId' => $userId,
        'cookies_present' => array_keys($_COOKIE ?? []),
        'ip' => $_SERVER['REMOTE_ADDR'] ?? null,
        'ua' => $_SERVER['HTTP_USER_AGENT'] ?? null,
    ]);
    respond(400, ['ok' => false, 'error' => 'Missing required field: sessionId']);
}

/* =========================================================
   MAIN LOGIC
   ========================================================= */

try {
    $db->beginTransaction();

    // Reuse existing conversation
    $sel = $db->prepare("
        SELECT id
        FROM pth_support_conversations
        WHERE client_session_id = :sid
        ORDER BY id DESC
        LIMIT 1
    ");
    $sel->execute([':sid' => $sessionId]);
    $existingId = (int)($sel->fetchColumn() ?: 0);

    if ($existingId > 0) {
        $_SESSION['support_conversations'] ??= [];
        $_SESSION['support_conversations'][(string)$existingId] = true;

        $db->commit();
        respond(200, [
            'ok' => true,
            'conversationId' => (string)$existingId,
            'reused' => true,
        ]);
    }

    // Create new conversation
    $ins = $db->prepare("
        INSERT INTO pth_support_conversations
          (visitor_id, client_session_id, source, visitor_name, visitor_email, visitor_phone, state, last_message_at, created_at)
        VALUES
          (:vid, :sid, :source, :vname, :vemail, :vphone, 'BOT', NOW(), NOW())
    ");

    $ins->execute([
        ':vid'    => $userId > 0 ? $userId : null,
        ':sid'    => $sessionId,
        ':source' => $source,
        ':vname'  => $visitorName,
        ':vemail' => $visitorEmail,
        ':vphone' => $visitorPhone,
    ]);

    $conversationId = (int)$db->lastInsertId();

    $_SESSION['support_conversations'] ??= [];
    $_SESSION['support_conversations'][(string)$conversationId] = true;

    $db->commit();

    respond(200, [
        'ok' => true,
        'conversationId' => (string)$conversationId,
        'reused' => false,
    ]);

} catch (Throwable $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }

    log_error('Failed to create conversation', [
        'exception' => get_class($e),
        'message' => $e->getMessage(),
        'code' => $e->getCode(),
        'userId' => $userId,
        'sessionId' => $sessionId,
        'source' => $source,
        'visitorEmail' => $visitorEmail,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? null,
        'ua' => $_SERVER['HTTP_USER_AGENT'] ?? null,
    ]);

    respond(500, [
        'ok' => false,
        'error' => 'Failed to create conversation',
        'message' => $e->getMessage(),
    ]);
}
