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

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$pdo = db();

// Action for admin notification count
if (isset($_GET['action']) && $_GET['action'] === 'count_unread') {
    $unread_msgs = $pdo->query("SELECT COUNT(*) FROM messages WHERE sender = 'user' AND is_read = 0")->fetchColumn();
    $pending_orders = $pdo->query("SELECT COUNT(*) FROM fiat_orders WHERE status IN ('matching', 'submitting')")->fetchColumn();
    echo json_encode(['total' => (int)($unread_msgs + $pending_orders)]);
    exit;
}

// Support both regular user and admin polling for specific user
$user_id = isset($_GET['user_id']) ? $_GET['user_id'] : $_SESSION['user_id'];

// If fetch_all is provided, return all messages for this user
if (isset($_GET['fetch_all'])) {
    $stmt = $pdo->prepare("SELECT * FROM messages WHERE user_id = ? ORDER BY id ASC");
    $stmt->execute([$user_id]);
    $msgs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['success' => true, 'data' => $msgs]);
    exit;
}

// If last_id is provided, return new messages since then
if (isset($_GET['last_id'])) {
    $last_id = (int)$_GET['last_id'];
    $stmt = $pdo->prepare("SELECT * FROM messages WHERE user_id = ? AND id > ? ORDER BY id ASC");
    $stmt->execute([$user_id, $last_id]);
    $msgs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['success' => true, 'data' => $msgs]);
    exit;
}

// Default action: return count and last_id, and if requested, full data
$stmt = $pdo->prepare("SELECT COUNT(*), MAX(id) FROM messages WHERE user_id = ?");
$stmt->execute([$user_id]);
$res = $stmt->fetch();
$count = $res[0];
$last_id = $res[1];

$stmt = $pdo->prepare("SELECT * FROM messages WHERE user_id = ? ORDER BY id DESC LIMIT 20");
$stmt->execute([$user_id]);
$msgs = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'success' => true,
    'count' => (int)$count,
    'last_id' => (int)$last_id,
    'data' => $msgs
]);