<?php

namespace App\Repositories;

use App\Models\Page;

class PageRepository
{
    public function __construct(Page $page)
    {
        $this->model = $page;
    }

    public function all()
    {
        $this->model->all();
    }

    public function paginate($perPage)
    {
        return $this->model->paginate($perPage);
    }

    public function filter($searchTerm, $is_published, $perPage)
    {
        $query = $this->model::latest('id');

        if ($searchTerm) {
            $query->where(function ($q) use ($searchTerm) {
                $q->where('title', 'LIKE', '%' . $searchTerm . '%');
            });
        }

        if ($is_published) {
            if($is_published == 1) {
                $query->where('is_published', 1);
            } else {
                $query->where('is_published', 0);
            }
        }

        return $query->paginate($perPage);
    }

    public function store(array $data)
    {
        return $this->model->create($data);
    }

    public function find($id)
    {
        return $this->model->findOrFail($id);
    }

    public function update($data, $id)
    {
        $page = $this->model->findOrFail($id);

        if (!array_key_exists('is_published', $data)) {
            $data['is_published'] = 0;
        } else {
            $data['is_published'] = $data['is_published'] ? 1 : 0;
        }

        $page->update($data);

        return $page;
    }

    public function destroy($id)
    {
        $page = $this->model->findOrFail($id);
        $page->delete();
        return true;
    }

    public function bulkDestroy($data)
    {
        $pages = $this->model->whereIn('id', $data['page_ids'])->get();

        foreach ($pages as $page) {
            $page->delete();
        }

        return true;
    }
}
