<?php
namespace Thirty\controllers;
class FeedController {
    public static function index(){
        require_auth(); global $DB; $uid=user()['id'];
        $friends=$DB->prepare('SELECT friend_id FROM friendships WHERE user_id=?'); $friends->execute([$uid]); $ids=array_map('intval', array_column($friends->fetchAll(),'friend_id')); $ids[]=$uid;
        $in=implode(',', array_fill(0,count($ids),'?'));
        $sql="SELECT po.id as post_id, po.user_id, po.text, po.visibility, po.created_at, u.nick, p.storage_rel_path, (SELECT COUNT(*) FROM post_likes pl WHERE pl.post_id=po.id) AS like_count, EXISTS(SELECT 1 FROM post_likes WHERE post_id=po.id AND user_id=?) AS i_like FROM posts po JOIN users u ON u.id=po.user_id LEFT JOIN photos p ON p.post_id=po.id WHERE po.user_id IN ($in) AND (po.visibility='friends' OR po.user_id=?) ORDER BY po.created_at DESC LIMIT 50";
        $params=$ids; array_unshift($params,$uid); $params[]=$uid;
        $st=$DB->prepare($sql); $st->execute($params); $feed=$st->fetchAll();
        $comments=[]; if(!empty($feed)){ $postIds=array_map(function($r){return (int)$r['post_id'];}, $feed); $place=implode(',', array_fill(0,count($postIds),'?')); $cst=$DB->prepare("SELECT c.id,c.post_id,c.body,c.created_at,u.nick FROM post_comments c JOIN users u ON u.id=c.user_id WHERE c.post_id IN ($place) ORDER BY c.created_at ASC"); $cst->execute($postIds); foreach($cst->fetchAll() as $c){ $comments[(int)$c['post_id']][]=$c; } }
        view('feed/index', ['feed'=>$feed, 'comments_by_post'=>$comments]);
    }
}