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

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

if (!isset($_SESSION['user_id']) && !isset($_GET['admin_key'])) {
    // Basic protection, though admin usually has session
    // For this project, admin session is also set in $_SESSION['user_id'] or checked by auth.php
}

$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', 'paid')")->fetchColumn();
    echo json_encode(['total' => (int)($unread_msgs + $pending_orders)]);
    exit;
}

// Mark messages as read
if (isset($_GET['action']) && $_GET['action'] === 'mark_read' && isset($_GET['user_id'])) {
    $u_id = $_GET['user_id'];
    $sender_type = isset($_GET['reader']) && $_GET['reader'] === 'admin' ? 'user' : 'admin';
    $pdo->prepare("UPDATE messages SET is_read = 1 WHERE user_id = ? AND sender = ?")->execute([$u_id, $sender_type]);
    echo json_encode(['success' => true]);
    exit;
}

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

if (!$user_id) {
    echo json_encode(['success' => false, 'error' => 'No user_id']);
    exit;
}

// Default action: return last 50 messages in ASC order
$stmt = $pdo->prepare("SELECT * FROM (SELECT * FROM messages WHERE user_id = ? ORDER BY id DESC LIMIT 50) AS sub ORDER BY id ASC");
$stmt->execute([$user_id]);
$msgs = $stmt->fetchAll(PDO::FETCH_ASSOC);

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