<?php

namespace MovieEngine\Frontend\Users;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class UserActions {

    public static function get_liked_content($user_id, $page = 1, $per_page = 12) {
        $liked_ids = get_user_meta($user_id, '_movie_engine_liked_posts', true);

        if (empty($liked_ids) || !is_array($liked_ids)) {
            return [];
        }

        $args = [
            'post_type' => ['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'],
            'post__in' => $liked_ids,
            'posts_per_page' => $per_page,
            'paged' => $page,
            'orderby' => 'post__in'
        ];

        return new \WP_Query($args);
    }


    public static function toggle_like($user_id, $post_id) {
        $likes = get_user_meta($user_id, '_movie_engine_liked_posts', true) ?: [];
        $likes_count = (int) get_post_meta($post_id, '_movie_engine_likes_count', true);

        if (($key = array_search($post_id, $likes)) !== false) {
            unset($likes[$key]);
            $action = 'removed';
            $likes_count = max(0, $likes_count - 1);
        } else {
            $likes[] = $post_id;
            $action = 'added';
            $likes_count++;
        }

        update_user_meta($user_id, '_movie_engine_liked_posts', array_values($likes));
        update_post_meta($post_id, '_movie_engine_likes_count', $likes_count);

        return $action;
    }

    public static function get_notifications($user_id) {

        Notifications::seed_if_empty($user_id);

        return Notifications::get($user_id);
    }
}
