<?php

namespace Autogedal\Extend\Model\ResourceModel;
use Magediary\ProductQuestion\Model\ActivityLog as ActivityLogModel;

class Answer extends \Magediary\ProductQuestion\Model\ResourceModel\Answer
{
    /**
     * Verify that an answer belongs to a specific product
     *
     * @param int $answerId
     * @param int $productId
     * @return bool
     */
    public function verifyAnswerProductRelation(int $answerId, int $productId): bool
    {
        $connection = $this->getConnection();
        
        $select = $connection->select()
            ->from(['a' => $this->getMainTable()], ['answer_id'])
            ->join(
                ['q' => $this->getTable('magediary_question')],
                'a.question_id = q.question_id',
                []
            )
            ->where('a.answer_id = ?', $answerId)
            ->where('q.product_id = ?', $productId)
            ->limit(1);

        $result = $connection->fetchOne($select);
        return (bool) $result;
    }

    /**
     * Verify that an answer belongs to a specific product
     *
     * @param int $answerId
     * @param int $productId
     * @return bool
     */
    public function isAlreadyLikedByThisUser(int $answerId, int $userId, int $productId): bool
    {
        $connection = $this->getConnection();
        
        $select = $connection->select()
            ->from(['a' => 'magediary_answer_activitylog'], ['log_id'])
            ->where('a.answer_id = ?', $answerId)
            ->where('a.customer_id = ?', $userId)
            ->where('a.product_id = ?', $productId)
            ->where('a.activity_type = ?', ActivityLogModel::ACTIVITY_LIKE);

        $result = $connection->fetchOne($select);
        return (bool) $result;
    }
}
