<?php
/**
 * @author  Magediary
 * @package Magediary_ProductQuestion
 */

namespace Magediary\ProductQuestion\Model\ResourceModel;

use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class Question extends AbstractDb
{
    /**
     * Define resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('magediary_question', 'question_id');
    }

    /**
     * Set question product_id mapping
     *
     * @param AbstractModel $object
     * @return AbstractDb|void
     */
    protected function _afterSave(AbstractModel $object)
    {
        /* Prepare relative links */
        $links = [];
        $oldIds = [];
        $items = [];

        /* Save product links from backend product grid */
        if (isset($object['data']['links']['product'])) {
            $items = $object['data']['links']['product'];
        }

        $table = $this->getTable('magediary_question_product');

        if (!empty($items)) {
            foreach ($items as $item) {
                $links[$item['id']] = [];
            }

            $oldIds = $this->_lookupIds($object->getId(), $table, 'product_id');
        }

        /* Save product links from frontend product view page */
        if ($object->isObjectNew() && $object->getProductId()) {
            $links[$object->getProductId()] = [];
        }

        if (count($links) > 0) {
            $this->_updateLinks(
                $object,
                array_keys($links),
                $oldIds,
                $table,
                'product_id',
                $links
            );
        }
    }

    /**
     * Update post connections
     *
     * @param AbstractModel $object
     * @param array $newRelatedIds
     * @param array $oldRelatedIds
     * @param string $table
     * @param string $field
     * @param array $rowData
     */
    protected function _updateLinks(
        \Magento\Framework\Model\AbstractModel $object,
        array $newRelatedIds,
        array $oldRelatedIds,
        $table,
        $field,
        $rowData = []
    ) {
        $insert = $newRelatedIds;
        $delete = $oldRelatedIds;

        if ($delete) {
            $delCondition = [
                'question_id  = ?' => $object->getId(),
                $field.' IN(?)' => $delete,
            ];
            $this->getConnection()->delete($table, $delCondition);
        }

        if ($insert) {
            $data = [];

            foreach ($insert as $id) {
                $id = (int)$id;
                $data[] = array_merge(
                    [ 'question_id' => (int)$object->getId(), $field => $id],
                    (isset($rowData[$id]) && is_array($rowData[$id])) ? $rowData[$id] : []
                );
            }
            $this->getConnection()->insertMultiple($table, $data);
        }
    }

    /**
     * Get ids to which specified item is assigned
     *
     * @param  int $questionId
     * @param  string $tableName
     * @param  string $field
     * @return array
     */
    protected function _lookupIds($questionId, $tableName, $field)
    {
        $adapter = $this->getConnection();

        $select = $adapter->select()->from(
            $this->getTable($tableName),
            $field
        )->where(
            'question_id = ?',
            (int)$questionId
        );

        return $adapter->fetchCol($select);
    }
}
