<?php

namespace Linksy\SearchAndReplace\Plugli\Linksy\Common\Helpers\Keywords\Traits;

use Linksy\SearchAndReplace\Plugli\Standard\Helpers\Database\Database;
use Linksy\SearchAndReplace\Plugli\Standard\Helpers\Arr;
trait TableFilters
{
    private function apply_generic_filters($table)
    {
        // Only get post keywords whose post_id is in the post__in array
        if (count($this->opts['post__in']) > 0) {
            $table->whereIn('post_id', $this->opts['post__in']);
        }
        // Ignore any post keywords whose post_id is in the post__not_in array
        if (count($this->opts['post__not_in']) > 0) {
            $table->whereNotIn('post_id', $this->opts['post__not_in']);
        }
        return $table;
    }
    protected function apply_table_filters($key, $type)
    {
        $table = Database::table($type)->select(Arr::split($key));
        return $this->apply_generic_filters($table);
    }
    protected function apply_postmeta_filters($meta_keys)
    {
        $table = Database::table('postmeta')->select(['post_id', 'meta_key', 'meta_value'])->whereIn('meta_key', $meta_keys);
        return $this->apply_generic_filters($table);
    }
    protected function apply_squirrly_filters($key, $type)
    {
        $table = Database::table($type)->select(Arr::split($key));
        // check if post associated with keyword has id that is in post__in
        foreach ($this->opts['post__in'] as $idx => $post_id) {
            $pattern = "\"ID\";i:{$post_id}";
            $idx == 0 ? $table->whereLike('post', $pattern) : $table->orWhereLike('post', $pattern);
        }
        // check if post is not associated with the ids present in post__not_int
        foreach ($this->opts['post__not_in'] as $idx => $post_id) {
            $pattern = "\"ID\";i:{$post_id}";
            $idx == 0 ? $table->whereNotLike('post', $pattern) : $table->orWhereNotLike('post', $pattern);
        }
        return $table;
    }
    protected function apply_aioseo_filters($key, $type)
    {
        return $this->apply_table_filters($key, $type);
    }
}
