<?php

namespace FSPoster\App\Pages\ContentIdeas\Repositories;
use FSPoster\App\Models\ContentIdea;

class ContentIdeaRepository
{
    public function getAll($filters)
    {
        $query = ContentIdea::orderBy('id DESC');

        if (!empty($filters['search'])) {
            $query->where(function ($q) use ($filters) {
                $q->where('title', 'like', '%' . $filters['search'] . '%')
                    ->orWhere('content', 'like', '%' . $filters['search'] . '%');
            });
        }

        if (!empty($filters['starred'])) {
            $query->where('is_starred', $filters['starred'] === 'starred' ? 1 : 0);
        }

        if (!empty($filters['created_by_ids'])) {
            $query->where('created_by', 'in', array_map('intval', $filters['created_by_ids']));
        }

        $total = $query->count();

        $ideas = $query
            ->offset(($filters['page'] - 1) * $filters['per_page'])
            ->limit($filters['per_page'])
            ->fetchAll();

        return [$ideas, $total];
    }

    public function find($id)
    {
        return ContentIdea::get($id);
    }

    public function update($id, array $data)
    {
        return ContentIdea::where('id', $id)->update($data);
    }

    public function insert(array $data)
    {
        return ContentIdea::insert($data);
    }

    public function deleteByIds(array $ids)
    {
        return ContentIdea::where('id', 'in', array_map('intval', $ids))->delete();
    }

    public function deleteExcept(array $ids)
    {
        return ContentIdea::where('id', 'not in', array_map('intval', $ids))->delete();
    }

    public function deleteAll()
    {
        return ContentIdea::where('id', '>', 0)->delete();
    }
}
