Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/portal/api/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/portal/api/chat_start.php

<?php
require_once '../config/config.php';
require_once '../classes/MemberAuth.php';

header('Content-Type: application/json');

try {
    $db = Database::getInstance()->getConnection();

    // Determine member or guest
    $memberId = null;
    if (class_exists('MemberAuth') && MemberAuth::isMemberLoggedIn()) {
        $currentMember = MemberAuth::getCurrentMember();
        $memberId = $currentMember['member_id'] ?? null;
    }

    if (!isset($_SESSION['chat_guest_token'])) {
        $_SESSION['chat_guest_token'] = bin2hex(random_bytes(16));
    }
    $guestToken = $_SESSION['chat_guest_token'];

    // Find existing open conversation
    if ($memberId) {
        $stmt = $db->prepare("SELECT * FROM chat_conversations 
                              WHERE type = 'public' AND member_id = :member_id AND is_closed = 0
                              ORDER BY id DESC LIMIT 1");
        $stmt->execute(['member_id' => $memberId]);
    } else {
        $stmt = $db->prepare("SELECT * FROM chat_conversations 
                              WHERE type = 'public' AND guest_token = :guest_token AND is_closed = 0
                              ORDER BY id DESC LIMIT 1");
        $stmt->execute(['guest_token' => $guestToken]);
    }

    $conversation = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$conversation) {
        // Create new conversation
        $ins = $db->prepare("INSERT INTO chat_conversations (type, guest_token, member_id, created_at) 
                             VALUES ('public', :guest_token, :member_id, NOW())");
        $ins->execute([
            'guest_token' => $memberId ? null : $guestToken,
            'member_id' => $memberId
        ]);
        $conversationId = (int)$db->lastInsertId();
    } else {
        $conversationId = (int)$conversation['id'];
    }

    echo json_encode([
        'success' => true,
        'conversation_id' => $conversationId,
        'guest_token' => $guestToken,
        'is_member' => (bool)$memberId
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to start chat.'
    ]);
}

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists