<?php
namespace Thirty\controllers;

class DashboardController 
{
    public static function show()
    {
        require_auth();
        global $DB;
        $uid = user()['id'];
        
        // Verificar si es cumpleaños del usuario
        $is_my_birthday = self::isMyBirthday($uid);
        
        // Obtener cumpleaños de amigos esta semana
        $birthdays = self::getThisWeekBirthdays($uid);
        
        // Obtener el feed de amigos
        $page = intval($_GET['page'] ?? 1);
        $limit = 10;
        $offset = ($page - 1) * $limit;
        
        $feed = self::getFriendFeed($uid, $limit, $offset);
        $comments_by_post = self::getCommentsForFeed(array_column($feed, 'post_id'));
        
        // Obtener contador de comentarios por post
        $comment_counts = self::getCommentCounts(array_column($feed, 'post_id'));
        
        view('dashboard', [
            'feed' => $feed,
            'comments_by_post' => $comments_by_post,
            'birthdays' => $birthdays,
            'is_my_birthday' => $is_my_birthday,
            'comment_counts' => $comment_counts,
            'current_page' => $page,
            'has_more' => count($feed) === $limit
        ]);
    }
    
    private static function isMyBirthday($userID)
    {
        global $DB;
        
        $st = $DB->prepare('
            SELECT id FROM users 
            WHERE id = ? 
            AND MONTH(dob) = MONTH(CURDATE()) 
            AND DAY(dob) = DAY(CURDATE())
            AND status = "active"
        ');
        $st->execute([$userID]);
        
        return $st->fetch() !== false;
    }
    
    private static function getThisWeekBirthdays($userID)
    {
        global $DB;
        
        $st = $DB->prepare('
            SELECT u.id, u.nick, u.first_name, u.last_name, u.dob,
                   DAYOFYEAR(u.dob) as day_of_year
            FROM users u
            INNER JOIN friendships f ON u.id = f.friend_id 
            WHERE f.user_id = ? 
            AND u.status = "active"
            AND (
                (MONTH(u.dob) = MONTH(CURDATE()) AND DAY(u.dob) >= DAY(CURDATE()))
                OR 
                (MONTH(u.dob) = MONTH(CURDATE()) + 1 AND DAY(u.dob) <= DAY(CURDATE() - INTERVAL 7 DAY))
            )
            AND DAYOFYEAR(u.dob) BETWEEN DAYOFYEAR(CURDATE()) AND DAYOFYEAR(CURDATE() + INTERVAL 7 DAY)
            ORDER BY DAYOFYEAR(u.dob) ASC
        ');
        $st->execute([$userID]);
        
        return $st->fetchAll();
    }
    
    private static function getFriendFeed($userID, $limit = 10, $offset = 0)
    {
        global $DB;
        
        // Solución: concatenar directamente los valores en la consulta
        $limit = intval($limit);
        $offset = intval($offset);
        
        $sql = '
            SELECT p.id as post_id,
                p.text,
                p.created_at,
                p.user_id,
                u.nick, pr.avatar_url, ph.storage_rel_path,
                (SELECT COUNT(*) FROM post_likes pl WHERE pl.post_id = p.id) as like_count,
                (SELECT COUNT(*) FROM post_likes pl WHERE pl.post_id = p.id AND pl.user_id = ?) as i_like
            FROM posts p
            INNER JOIN users u ON p.user_id = u.id
            LEFT JOIN profiles pr ON pr.user_id = u.id
            LEFT JOIN photos ph ON p.id = ph.post_id
            WHERE p.user_id = ? 
               OR p.user_id IN (
                   SELECT friend_id FROM friendships WHERE user_id = ?
               )
            ORDER BY p.created_at DESC
            LIMIT ' . $limit . ' OFFSET ' . $offset;
        
        $st = $DB->prepare($sql);
        $st->execute([$userID, $userID, $userID]);
        
        return $st->fetchAll();
    }
    
    private static function getCommentsForFeed($postIDs)
    {
        global $DB;
        
        if (empty($postIDs)) {
            return [];
        }
        
        $placeholders = str_repeat('?,', count($postIDs) - 1) . '?';
        $st = $DB->prepare("
            SELECT pc.post_id, pc.body, pc.created_at, u.nick, u.id as user_id
            FROM post_comments pc
            INNER JOIN users u ON pc.user_id = u.id
            WHERE pc.post_id IN ($placeholders)
            ORDER BY pc.created_at ASC
        ");
        $st->execute($postIDs);
        
        $comments = [];
        while ($row = $st->fetch()) {
            $comments[$row['post_id']][] = $row;
        }
        
        return $comments;
    }
    
    private static function getCommentCounts($postIDs)
    {
        global $DB;
        
        if (empty($postIDs)) {
            return [];
        }
        
        $placeholders = str_repeat('?,', count($postIDs) - 1) . '?';
        $st = $DB->prepare("
            SELECT post_id, COUNT(*) as comment_count
            FROM post_comments 
            WHERE post_id IN ($placeholders)
            GROUP BY post_id
        ");
        $st->execute($postIDs);
        
        $counts = [];
        while ($row = $st->fetch()) {
            $counts[$row['post_id']] = $row['comment_count'];
        }
        
        return $counts;
    }
}