<?php
require_once '../includes/db.php';
header('Content-Type: application/json');
if (!isset($_SESSION['admin_logged_in'])) { exit; }

$notifications = [];
$ids_to_update = [ 'users'=>[], 'transactions'=>[], 'withdrawals'=>[], 'partner_documents'=>[], 'contact_messages'=>[], 'messages'=>[], 'tours'=>[], 'hotels'=>[] ];

// Master query for all actionable notifications where is_notified = 0
$sql = "
    (SELECT id, 'New Partner' as type, full_name as detail, NULL as item, created_at FROM users WHERE role LIKE '%_partner' AND status = 'pending' AND is_notified = 0)
    UNION ALL
    (SELECT id, 'Top-Up Request' as type, (SELECT full_name FROM users u WHERE u.id = t.user_id) as detail, NULL as item, created_at FROM transactions t WHERE transaction_type = 'Top-up' AND status = 'Pending' AND is_notified = 0)
    UNION ALL
    (SELECT id, 'Withdrawal Request' as type, (SELECT full_name FROM users u WHERE u.id = w.partner_id) as detail, NULL as item, created_at FROM withdrawals w WHERE status = 'Pending' AND is_notified = 0)
    UNION ALL
    (SELECT id, 'New Document' as type, (SELECT full_name FROM users u WHERE u.id = pd.partner_id) as detail, NULL as item, upload_date as created_at FROM partner_documents pd WHERE status = 'Submitted' AND is_notified = 0)
    UNION ALL
    (SELECT id, 'New Message' as type, name as detail, subject as item, created_at FROM contact_messages WHERE is_read = 0 AND is_notified = 0)
    UNION ALL
    (SELECT id, 'New Chat Message' as type, (SELECT full_name FROM users u WHERE u.id = m.sender_id) as detail, NULL as item, created_at FROM messages m WHERE recipient_id = 1 AND is_read = 0 AND is_notified = 0)
    UNION ALL
    (SELECT id, 'New Listing: Tour' as type, (SELECT full_name FROM users u WHERE u.id = t.partner_id) as detail, title as item, NOW() as created_at FROM tours t WHERE partner_id IS NOT NULL AND is_notified = 0)
    UNION ALL
    (SELECT id, 'New Listing: Hotel' as type, (SELECT full_name FROM users u WHERE u.id = h.partner_id) as detail, name as item, NOW() as created_at FROM hotels h WHERE partner_id IS NOT NULL AND is_notified = 0)
    ORDER BY created_at ASC
";

$result = $conn->query($sql);
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $notifications[] = $row;
        // Store IDs to be updated
        if (strpos($row['type'], 'New Partner') !== false) $ids_to_update['users'][] = $row['id'];
        if (strpos($row['type'], 'Top-Up') !== false) $ids_to_update['transactions'][] = $row['id'];
        if (strpos($row['type'], 'Withdrawal') !== false) $ids_to_update['withdrawals'][] = $row['id'];
        if (strpos($row['type'], 'Document') !== false) $ids_to_update['partner_documents'][] = $row['id'];
        if (strpos($row['type'], 'New Message') !== false) $ids_to_update['contact_messages'][] = $row['id'];
        if (strpos($row['type'], 'Chat') !== false) $ids_to_update['messages'][] = $row['id'];
        if (strpos($row['type'], 'Listing: Tour') !== false) $ids_to_update['tours'][] = $row['id'];
        if (strpos($row['type'], 'Listing: Hotel') !== false) $ids_to_update['hotels'][] = $row['id'];
    }
}

// If we found new notifications, immediately flag them
if (!empty($notifications)) {
    foreach ($ids_to_update as $table => $ids) {
        if (!empty($ids)) {
            $id_list = implode(',', array_map('intval', $ids));
            $conn->query("UPDATE `$table` SET is_notified = 1 WHERE id IN ($id_list)");
        }
    }
}

echo json_encode(['success' => true, 'notifications' => $notifications]);
?>
