<?php
/**
 * @package   Gridbox
 * @author    Balbooa http://www.balbooa.com/
 * @copyright Copyright @ Balbooa
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace Balbooa\Component\Gridbox\Administrator\Trait;

trait BulkActionsModelTrait
{
    public function clearMapsTable(string $table, array $cid): void
    {
        $ids = implode(',', $cid);
        $db = $this->getDatabase();
        $query = $db->getQuery(true)
            ->delete($table)
            ->where('page_id IN (' . $ids . ')');
        $db->setQuery($query)
            ->execute();
    }

    public function updateMapsTable(string $table, array $cid, string $value, string $key): void
    {
        if (empty($value)) {
            return;
        }
        $db = $this->getDatabase();
        $items = explode(',', $value);
        foreach ($cid as $id) {
            foreach ($items as $item_id) {
                $obj = (object) [
                    'page_id' => $id
                ];
                $obj->{$key} = $item_id;
                $db->insertObject($table, $obj);
            }
        }
    }

    public function bulkCategories(array $cid, string $value): void
    {
        $data = json_decode($value);
        $this->setBulkValue($cid, $data->default, 'page_category');
        $this->clearMapsTable('#__gridbox_category_page_map', $cid);
        $this->updateMapsTable('#__gridbox_category_page_map', $cid, $data->categories, 'category_id');
    }

    public function bulkAuthor(array $cid, string $value): void
    {
        $this->clearMapsTable('#__gridbox_authors_map', $cid);
        $this->updateMapsTable('#__gridbox_authors_map', $cid, $value, 'author_id');
    }

    public function bulkTags(array $cid, string $value): void
    {
        $this->clearMapsTable('#__gridbox_tags_map', $cid);
        $this->updateMapsTable('#__gridbox_tags_map', $cid, $value, 'tag_id');
    }

    public function bulkLanguage(array $cid, string $value): void
    {
        $this->setBulkValue($cid, $value, 'language');
    }

    public function bulkTheme(array $cid, string $value): void
    {
        $this->setBulkValue($cid, $value, 'theme');
    }

    public function bulkAccess(array $cid, int $value): void
    {
        $property = $this->tableName == '#__gridbox_pages' ? 'page_access' : 'access';
        $this->setBulkValue($cid, $value, $property);
    }

    public function setBulkValue(array $cid, string|int $value, string $property): void
    {
        $db = $this->getDatabase();
        $ids = implode(',', $cid);
        $query = $db->getQuery(true)
            ->update($this->tableName)
            ->set($db->quoteName($property) . ' = ' .$db->quote($value))
            ->where('id IN (' . $ids . ')');
        $db->setQuery($query)
            ->execute();
    }
}