<?php
require_once '../includes/init.php';

if (!isAuthenticated()) {
    jsonResponse(false, 'Not authenticated');
}

$userId = sanitizeInput($_GET['user'] ?? '');
$lastId = intval($_GET['last_id'] ?? 0);

if (empty($userId)) {
    jsonResponse(false, 'User not specified');
}

$db = getDB();
$currentUserId = $_SESSION['user_id'];

// Get chat partner ID
$stmt = $db->prepare("SELECT id FROM users WHERE unique_id = ? AND status = 'approved'");
$stmt->execute([$userId]);
$partner = $stmt->fetch();

if (!$partner) {
    jsonResponse(false, 'User not found');
}

$partnerId = $partner['id'];

// Get messages after last_id - only fetch messages FROM partner TO current user
$stmt = $db->prepare("
    SELECT m.*, u.unique_id as sender_unique_id, u.name as sender_name, u.profile_photo as sender_photo
    FROM messages m
    JOIN users u ON m.sender_id = u.id
    WHERE m.sender_id = ? 
    AND m.receiver_id = ?
    AND m.id > ?
    AND m.is_deleted_for_all = 0
    AND m.deleted_by_receiver = 0
    ORDER BY m.created_at ASC
");
$stmt->execute([$partnerId, $currentUserId, $lastId]);
$messages = $stmt->fetchAll();

// Mark messages as delivered
foreach ($messages as $msg) {
    $stmt = $db->prepare("
        INSERT INTO message_status (message_id, user_id, status) 
        VALUES (?, ?, 'delivered')
        ON DUPLICATE KEY UPDATE status = IF(status = 'sent', 'delivered', status)
    ");
    $stmt->execute([$msg['id'], $currentUserId]);
}

// Format message data for JavaScript
$formattedMessages = [];
foreach ($messages as $msg) {
    // Get message status
    $stmt = $db->prepare("SELECT status FROM message_status WHERE message_id = ? AND user_id = ?");
    $stmt->execute([$msg['id'], $currentUserId]);
    $status = $stmt->fetchColumn();
    
    $formattedMessages[] = [
        'id' => $msg['id'],
        'message' => $msg['message'],
        'message_type' => $msg['message_type'],
        'file_url' => $msg['file_url'],
        'sender_photo' => $msg['sender_photo'],
        'sender_unique_id' => $msg['sender_unique_id'],
        'sender_name' => $msg['sender_name'],
        'created_at' => $msg['created_at'],
        'read_status' => $status ?: 'sent'
    ];
}

jsonResponse(true, 'Messages retrieved', $formattedMessages);
?>
