<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");

$chatDir = 'data/chats/';
if (!file_exists($chatDir)) {
    mkdir($chatDir, 0777, true);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

if ($method === 'POST') {
    // Send Message
    // Expecting JSON body: { sender, receiver, itemId, text, timestamp }
    $data = json_decode(file_get_contents('php://input'), true);

    if (!$data || !isset($data['sender']) || !isset($data['itemId'])) {
        echo json_encode(['success' => false, 'error' => 'Invalid data']);
        exit;
    }

    $itemId = $data['itemId'];
    $sender = $data['sender'];
    $receiver = $data['receiver'] ?? 'Seller';
    $chatFile = $chatDir . 'chat_' . $itemId . '.json';

    // Structure: Array of messages
    $messages = [];
    if (file_exists($chatFile)) {
        $messages = json_decode(file_get_contents($chatFile), true) ?? [];
    }

    // New Message
    $msg = [
        'id' => uniqid(),
        'sender' => $sender,
        'receiver' => $receiver, // Vital for inbox filtering
        'text' => htmlspecialchars($data['text']),
        'timestamp' => $data['timestamp'] ?? time(),
        'replyTo' => $data['replyTo'] ?? null
    ];

    $messages[] = $msg;

    if (file_put_contents($chatFile, json_encode($messages))) {
        echo json_encode(['success' => true, 'message' => $msg]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to write to file']);
    }
    exit;
} elseif ($method === 'GET') {
    if ($action === 'load') {
        // Load Chat History for an Item
        $itemId = $_GET['itemId'] ?? '';
        if (!$itemId) {
            echo json_encode(['success' => false, 'error' => 'No Item ID']);
            exit;
        }

        $chatFile = $chatDir . 'chat_' . $itemId . '.json';
        if (file_exists($chatFile)) {
            $messages = json_decode(file_get_contents($chatFile), true);
            echo json_encode(['success' => true, 'messages' => $messages]);
        } else {
            echo json_encode(['success' => true, 'messages' => []]);
        }
        exit;
    } elseif ($action === 'inbox' || $action === 'list_all') {
        // List Chats (Inbox)
        // If 'user' param exists, filter by that user (Sender or Receiver)
        $user = $_GET['user'] ?? '';

        $files = glob($chatDir . 'chat_*.json');
        $chats = [];

        foreach ($files as $file) {
            $content = json_decode(file_get_contents($file), true);
            if (!empty($content)) {
                $lastMsg = end($content);
                // Check participants
                // We check if ANY message involves the user, or just check the last/first?
                // Ideally check all, but let's check first and last for efficiency or scan all unique participants.
                // Better: Scan all to be sure.

                $isParticipant = false;
                if (!$user) {
                    $isParticipant = true; // list_all (Admin/Debug)
                } else {
                    foreach ($content as $m) {
                        if (($m['sender'] ?? '') === $user || ($m['receiver'] ?? '') === $user) {
                            $isParticipant = true;
                            break;
                        }
                    }
                }

                if ($isParticipant) {
                    $basename = basename($file);
                    $id = str_replace(['chat_', '.json'], '', $basename);

                    $chats[] = [
                        'itemId' => $id,
                        'lastMessage' => $lastMsg,
                        'count' => count($content),
                        'participants' => array_unique(array_merge(array_column($content, 'sender'), array_column($content, 'receiver')))
                    ];
                }
            }
        }
        echo json_encode(['success' => true, 'chats' => $chats]);
        exit;
    }
}

echo json_encode(['success' => false, 'error' => 'Unknown Request']);
