<?php
namespace Thirty\controllers;

use Thirty\services\Notifications;

class LikeController {
    public static function toggle(){
        require_auth(); verify_csrf(); global $DB;
        $uid=user()['id']; $postId=(int)($_POST['post_id']??0);
        if($postId<=0){ 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; }

        // Visibilidad / permisos
        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; }
        }

        // Toggle like
        $ex=$DB->prepare('SELECT 1 FROM post_likes WHERE post_id=? AND user_id=?');
        $ex->execute([$postId,$uid]);

        if($ex->fetchColumn()){
            $DB->prepare('DELETE FROM post_likes WHERE post_id=? AND user_id=?')->execute([$postId,$uid]);
        } else {
            $DB->prepare('INSERT INTO post_likes (post_id,user_id) VALUES (?,?)')->execute([$postId,$uid]);
            // 🔔 Notificación al dueño del post (si no soy yo)
            if ((int)$po['user_id'] !== $uid) {
                Notifications::create($DB, (int)$po['user_id'], 'like', [
                    'post_id'=>$postId,
                    'from_user_id'=>$uid
                ]);
            }
        }

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