<?php
namespace Thirty\controllers;

use Thirty\services\Notifications;

class CommentController {
    public static function add(){
        require_auth(); verify_csrf(); global $DB;
        $uid=user()['id']; $postId=(int)($_POST['post_id']??0);
        $body=trim($_POST['body']??'');
        $parentId=isset($_POST['parent_id'])?(int)$_POST['parent_id']:null;

        if($postId<=0 || $body===''){
            header('Location: '.($_SERVER['HTTP_REFERER']??base_url('/feed'))); exit;
        }

        $can=$DB->prepare('SELECT user_id,visibility FROM posts WHERE id=? LIMIT 1');
        $can->execute([$postId]); $po=$can->fetch();
        if(!$po){ header('Location: '.($_SERVER['HTTP_REFERER']??base_url('/feed'))); exit; }

        if($po['user_id'] != $uid){
            if($po['visibility']==='private'){
                header('Location: '.($_SERVER['HTTP_REFERER']??base_url('/feed'))); exit;
            }
            $f=$DB->prepare('SELECT 1 FROM friendships WHERE user_id=? AND friend_id=?');
            $f->execute([$uid,$po['user_id']]);
            if(!$f->fetchColumn()){ header('Location: '.($_SERVER['HTTP_REFERER']??base_url('/feed'))); exit; }
        }

        // Si es una respuesta, verificar que el comentario padre existe
        if($parentId){
            $parent=$DB->prepare('SELECT id,user_id FROM post_comments WHERE id=? AND post_id=?');
            $parent->execute([$parentId,$postId]);
            if(!$parent->fetch()){
                header('Location: '.($_SERVER['HTTP_REFERER']??base_url('/feed'))); exit;
            }
        }

        $DB->prepare('INSERT INTO post_comments (post_id,user_id,body,parent_id) VALUES (?,?,?,?)')
           ->execute([$postId,$uid,$body,$parentId]);

        $commentId = $DB->lastInsertId();

        // 🔔 Notificaciones
        if ((int)$po['user_id'] !== $uid) {
            // Notificar al dueño del post (si no soy yo)
            Notifications::create($DB, (int)$po['user_id'], 'comment', [
                'post_id'=>$postId,
                'from_user_id'=>$uid,
                'body'=>$body,
                'comment_id'=>$commentId
            ]);
        }

        // Si es respuesta, notificar al autor del comentario padre (si no soy yo y no es el dueño del post)
        if($parentId){
            $parent=$DB->prepare('SELECT user_id FROM post_comments WHERE id=?');
            $parent->execute([$parentId]);
            $parentAuthor = $parent->fetchColumn();
            
            if($parentAuthor && $parentAuthor != $uid && $parentAuthor != $po['user_id']){
                Notifications::create($DB, (int)$parentAuthor, 'comment_reply', [
                    'post_id'=>$postId,
                    'from_user_id'=>$uid,
                    'body'=>$body,
                    'comment_id'=>$commentId,
                    'parent_comment_id'=>$parentId
                ]);
            }
        }

        header('Location: '.($_SERVER['HTTP_REFERER']??base_url('/feed'))); exit;
    }
}