<?php
session_start();
require_once __DIR__ . '/../db/config.php';

$action = $_GET['action'] ?? '';

if ($action === 'upload_image' || (isset($_POST['action']) && $_POST['action'] === 'upload_image')) {
    if (!isset($_FILES['file'])) {
        echo json_encode(['success' => false, 'error' => 'No file uploaded']);
        exit;
    }

    $file = $_FILES['file'];
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    
    if (!in_array(strtolower($ext), $allowed)) {
        echo json_encode(['success' => false, 'error' => 'Invalid file type']);
        exit;
    }

    $filename = time() . '_' . uniqid() . '.' . $ext;
    $targetDir = __DIR__ . '/../assets/images/chat/';
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0777, true);
    }
    
    $targetPath = $targetDir . $filename;
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        $imageUrl = '/assets/images/chat/' . $filename;
        $message = '<img src="' . $imageUrl . '" class="img-fluid rounded cursor-pointer" style="max-width: 100%; max-height: 250px; object-fit: contain; margin: 5px 0;" onclick="window.open(\'' . $imageUrl . '\')">';
        
        if (isset($_SESSION['admin_id'])) {
            $user_id = (int)($_POST['user_id'] ?? 0);
            $ip = $_POST['ip_address'] ?? '';
            $sender = 'admin';
            $admin_id = $_SESSION['admin_id'];
            $stmt = db()->prepare("INSERT INTO messages (user_id, admin_id, sender, message, ip_address) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$user_id, $admin_id, $sender, $message, $ip]);
        } else {
            $user_id = (int)($_SESSION['user_id'] ?? 0);
            $ip = getRealIP();
            $sender = 'user';
            $stmt = db()->prepare("INSERT INTO messages (user_id, sender, message, ip_address) VALUES (?, ?, ?, ?)");
            $stmt->execute([$user_id, $sender, $message, $ip]);
        }
        
        $newId = db()->lastInsertId();
        $createdAt = date('Y-m-d H:i:s');
        echo json_encode([
            'success' => true, 
            'url' => $imageUrl, 
            'message' => [
                'id' => $newId, 
                'sender' => $sender, 
                'message' => $message, 
                'created_at' => $createdAt
            ]
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to move uploaded file']);
    }
    exit;
}

if ($action === 'get_messages') {
    $user_id = $_SESSION['user_id'] ?? 0;
    $target_user_id = $_GET['user_id'] ?? $user_id;
    $target_ip = $_GET['ip'] ?? getRealIP();
    
    // If admin is requesting, we use the provided user_id and ip
    if (isset($_SESSION['admin_id'])) {
        $stmt = db()->prepare("SELECT * FROM messages WHERE (user_id = ? AND user_id != 0) OR (user_id = 0 AND ip_address = ?) ORDER BY created_at ASC");
        $stmt->execute([$target_user_id, $target_ip]);
    } else {
        // User requesting their own messages
        $stmt = db()->prepare("SELECT * FROM messages WHERE (user_id = ? AND user_id != 0) OR (user_id = 0 AND ip_address = ?) ORDER BY created_at ASC");
        $stmt->execute([$user_id, getRealIP()]);
    }
    
    $messages = $stmt->fetchAll();
    echo json_encode($messages);
    exit;
}

if ($action === 'send_message') {
    $message = $_POST['message'] ?? '';
    if (!$message) exit(json_encode(['success' => false, 'error' => 'Empty message']));

    $user_id = (int)($_SESSION['user_id'] ?? 0);
    $ip = getRealIP();

    $stmt = db()->prepare("INSERT INTO messages (user_id, sender, message, ip_address) VALUES (?, ?, ?, ?)");
    $stmt->execute([$user_id, 'user', $message, $ip]);
    $newId = db()->lastInsertId();
    
    // Also update visitors table to ensure immediate visibility
    $user_time = date('H:i:s');
    $stmt = db()->prepare("INSERT INTO chat_visitors (user_id, ip_address, user_time) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE last_ping = CURRENT_TIMESTAMP");
    $stmt->execute([$user_id, $ip, $user_time]);

    echo json_encode(['success' => true, 'id' => $newId, 'message' => ['id' => $newId, 'sender' => 'user', 'message' => $message, 'created_at' => date('Y-m-d H:i:s')]]);
    exit;
}

if ($action === 'admin_send') {
    if (!isset($_SESSION['admin_id'])) exit(json_encode(['success' => false, 'error' => 'Unauthorized']));
    
    $message = $_POST['message'] ?? '';
    $user_id = (int)($_POST['user_id'] ?? 0);
    $target_ip = $_POST['ip_address'] ?? '';
    
    if (!$message) exit(json_encode(['success' => false, 'error' => 'Empty message']));

    $admin_id = $_SESSION['admin_id'] ?? 1; 
    $sender = 'admin';

    $stmt = db()->prepare("INSERT INTO messages (user_id, admin_id, sender, message, ip_address) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$user_id, $admin_id, $sender, $message, $target_ip]);
    $newId = db()->lastInsertId();
    echo json_encode(['success' => true, 'id' => $newId, 'message' => ['id' => $newId, 'sender' => $sender, 'message' => $message, 'created_at' => date('Y-m-d H:i:s')]]);
    exit;
}


if ($action === 'ping') {
    $user_id = $_SESSION['user_id'] ?? 0;
    $ip = getRealIP();
    $user_time = $_GET['user_time'] ?? '';
    $stmt = db()->prepare("INSERT INTO chat_visitors (user_id, ip_address, user_time) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE last_ping = CURRENT_TIMESTAMP, user_time = ?");
    $stmt->execute([$user_id, $ip, $user_time, $user_time]);
    echo json_encode(['success' => true]);
    exit;
}

if ($action === 'admin_get_all') {
    header('Content-Type: application/json');
    
    if (!isset($_SESSION['admin_id'])) {
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
    try {
        // Robust query to get all active chat sessions
        $stmt = db()->query("
            SELECT 
                v.user_id, 
                v.ip_address, 
                CASE 
                    WHEN m.message LIKE '<img%' THEN '[图片消息]' 
                    WHEN (m.message IS NULL OR m.message = '') AND v.has_recharge = 1 THEN '[充值申请]'
                    ELSE COALESCE(m.message, '新会话') 
                END as message, 
                COALESCE(m.created_at, v.last_activity) as created_at,
                COALESCE(u.username, u.email, CONCAT('访客 ', COALESCE(v.ip_address, '0.0.0.0'))) as username, 
                IFNULL(u.uid, '---') as uid, 
                IFNULL(r.remark, '') as remark,
                IFNULL(v.user_time, '---') as user_time
            FROM (
                SELECT 
                    user_id,
                    ip_address,
                    MAX(last_activity) as last_activity,
                    MAX(user_time) as user_time,
                    MAX(has_recharge) as has_recharge
                FROM (
                    SELECT COALESCE(user_id, 0) as user_id, IFNULL(ip_address, '') as ip_address, created_at as last_activity, NULL as user_time, 0 as has_recharge FROM messages
                    UNION ALL
                    SELECT COALESCE(user_id, 0) as user_id, IFNULL(ip_address, '') as ip_address, last_ping as last_activity, user_time, 0 as has_recharge FROM chat_visitors
                    UNION ALL
                    SELECT COALESCE(user_id, 0) as user_id, IFNULL(ip_address, '') as ip_address, created_at as last_activity, NULL as user_time, 1 as has_recharge FROM finance_requests
                ) t1
                GROUP BY (CASE WHEN user_id = 0 THEN 0 ELSE user_id END), (CASE WHEN user_id = 0 THEN ip_address ELSE '0' END)
            ) v
            LEFT JOIN (
                SELECT m1.* FROM messages m1
                INNER JOIN (
                    SELECT MAX(id) as max_id FROM messages GROUP BY COALESCE(user_id, 0), (CASE WHEN COALESCE(user_id, 0) = 0 THEN ip_address ELSE '0' END)
                ) m2 ON m1.id = m2.max_id
            ) m ON (v.user_id = COALESCE(m.user_id, 0) AND (v.user_id != 0 OR IFNULL(v.ip_address, '') = IFNULL(m.ip_address, '')))
            LEFT JOIN users u ON (v.user_id = u.id AND v.user_id != 0)
            LEFT JOIN chat_remarks r ON (v.user_id = COALESCE(r.user_id, 0) AND (v.user_id != 0 OR IFNULL(v.ip_address, '') = IFNULL(r.ip_address, '')))
            WHERE v.last_activity > DATE_SUB(NOW(), INTERVAL 720 HOUR)
            ORDER BY created_at DESC
        ");
        echo json_encode($stmt->fetchAll());
    } catch (Exception $e) {
        error_log("Chat API Error: " . $e->getMessage());
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'save_remark') {
    if (!isset($_SESSION['admin_id'])) exit(json_encode(['success' => false, 'error' => 'Unauthorized']));
    
    $user_id = $_POST['user_id'] ?? 0;
    $ip = $_POST['ip_address'] ?? '';
    $remark = $_POST['remark'] ?? '';
    
    $stmt = db()->prepare("INSERT INTO chat_remarks (user_id, ip_address, remark) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE remark = ?");
    $stmt->execute([$user_id, $ip, $remark, $remark]);
    
    echo json_encode(['success' => true]);
    exit;
}

if ($action === 'get_remark') {
    if (!isset($_SESSION['admin_id'])) exit(json_encode(['success' => false, 'error' => 'Unauthorized']));
    
    $user_id = $_GET['user_id'] ?? 0;
    $ip = $_GET['ip'] ?? '';
    
    $stmt = db()->prepare("SELECT remark FROM chat_remarks WHERE user_id = ? AND ip_address = ?");
    $stmt->execute([$user_id, $ip]);
    $remark = $stmt->fetchColumn() ?: '';
    
    echo json_encode(['success' => true, 'remark' => $remark]);
    exit;
}

if ($action === 'admin_delete_user') {
    if (!isset($_SESSION['admin_id'])) exit(json_encode(['success' => false, 'error' => 'Unauthorized']));
    $user_id = $_POST['user_id'] ?? 0;
    $ip = $_POST['ip_address'] ?? '';
    
    if ($user_id != 0) {
        $stmt = db()->prepare("DELETE FROM messages WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $stmt = db()->prepare("DELETE FROM chat_visitors WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $stmt = db()->prepare("DELETE FROM chat_remarks WHERE user_id = ?");
        $stmt->execute([$user_id]);
    } else {
        $stmt = db()->prepare("DELETE FROM messages WHERE user_id = 0 AND ip_address = ?");
        $stmt->execute([$ip]);
        $stmt = db()->prepare("DELETE FROM chat_visitors WHERE user_id = 0 AND ip_address = ?");
        $stmt->execute([$ip]);
        $stmt = db()->prepare("DELETE FROM chat_remarks WHERE user_id = 0 AND ip_address = ?");
        $stmt->execute([$ip]);
    }
    echo json_encode(['success' => true]);
    exit;
}

if ($action === 'admin_recall_message') {
    if (!isset($_SESSION['admin_id'])) exit(json_encode(['success' => false, 'error' => 'Unauthorized']));
    $message_id = $_POST['message_id'] ?? 0;
    $stmt = db()->prepare("DELETE FROM messages WHERE id = ? AND sender = 'admin'");
    $stmt->execute([$message_id]);
    echo json_encode(['success' => true]);
    exit;
}
