<?php
// src/controllers/HomeController.php
class HomeController {
    public static function landing() {
        view('landing');
    }

    public static function dashboard($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        // Obtener posts de amigos y propios con información de interacciones
        $posts = $db->prepare("
            SELECT 
                p.id, 
                p.caption, 
                p.created_at, 
                ph.url, 
                u.username,
                u.avatar_url as author_avatar_url,
                u.id as author_id,
                (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
                (SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comment_count,
                (SELECT COUNT(*) FROM tags WHERE post_id = p.id) as tag_count,
                EXISTS(SELECT 1 FROM likes WHERE post_id = p.id AND user_id = ?) as is_liked
            FROM posts p
            JOIN photos ph ON ph.post_id = p.id
            JOIN users u ON u.id = p.author_id
            WHERE p.author_id = ? 
            OR p.author_id IN (
                SELECT CASE 
                    WHEN user1_id = ? THEN user2_id 
                    ELSE user1_id 
                END as friend_id
                FROM friends 
                WHERE (user1_id = ? OR user2_id = ?) 
                AND status = 'accepted'
            )
            ORDER BY p.created_at DESC
            LIMIT 20
        ");
        $posts->execute([$uid, $uid, $uid, $uid, $uid]);
        
        // Obtener tags para cada post
        $postsWithData = $posts->fetchAll();
        foreach ($postsWithData as &$post) {
            $tags_stmt = $db->prepare("SELECT name FROM tags WHERE post_id = ?");
            $tags_stmt->execute([$post['id']]);
            $post['tags'] = $tags_stmt->fetchAll(PDO::FETCH_COLUMN);
        }
        
        // Obtener anuncios activos - CORREGIDO: manejo de errores
        try {
            $activeAds = AdminController::getActiveAds($db, $uid);
        } catch (Exception $e) {
            error_log("Error obteniendo anuncios activos: " . $e->getMessage());
            $activeAds = [];
        }
        
        // Actualizar contador de notificaciones no leídas
        $notif_count = NotificationsController::count($db);
        $_SESSION['unread_notifications'] = $notif_count;
        
        // Pasar la conexión a la vista
        view('dashboard', [
            'postsWithPhotos' => $postsWithData,
            'activeAds' => $activeAds,
            'db' => $db
        ]);
    }

    public static function ranking($db) {
        // Consulta corregida - usar la columna type que YA EXISTE
        $stmt = $db->query("
            SELECT target_id, SUM(weight) as points 
            FROM interactions 
            WHERE type IN ('like', 'comment')  -- type YA EXISTE
            GROUP BY target_id 
            ORDER BY points DESC 
            LIMIT 10
        ");
        
        $rows = $stmt->fetchAll();
        $ranking = [];
        
        foreach ($rows as $r) {
            $u = $db->prepare("SELECT username, id FROM users WHERE id = ?");
            $u->execute([$r['target_id']]);
            $usr = $u->fetch();
            
            if ($usr) {
                $ranking[] = ['id'=>$usr['id'], 'username'=>$usr['username'], 'points'=>$r['points']];
            }
        }
        
        // Cumpleaños de AMIGOS solamente (corregido) - usar birth_date en lugar de birthday
        $b = $db->query("
            SELECT u.username, u.birth_date
            FROM users u
            JOIN friends f ON (f.user1_id = u.id OR f.user2_id = u.id)
            WHERE (f.user1_id = '" . $_SESSION['user']['id'] . "' OR f.user2_id = '" . $_SESSION['user']['id'] . "')
            AND f.status = 'accepted'
            AND u.id != '" . $_SESSION['user']['id'] . "'
            AND DATE_FORMAT(u.birth_date, '%m-%d') BETWEEN DATE_FORMAT(CURDATE(), '%m-%d') AND DATE_FORMAT(DATE_ADD(CURDATE(), INTERVAL 30 DAY), '%m-%d')
            ORDER BY DATE_FORMAT(u.birth_date, '%m-%d')
            LIMIT 10
        ")->fetchAll();
        
        view('ranking', ['ranking'=>$ranking, 'birthdays'=>$b]);
    }
}