<?php

namespace App\Repositories\Customers;

use App\Modules\Enums\FeedbackStatus;
use App\Modules\Models\Feedback\Feedback;
use App\Modules\Models\Feedback\FeedbackImage;
use App\Modules\Repositories\Feedback\BaseFeedbackRepository;
use Illuminate\Support\Facades\DB;

/**
 * Class FeedbackRepository
 * @package App\Repositories\UserGuide
 */
class FeedbackRepository extends BaseFeedbackRepository
{
    /**
     * @param $input
     * @return mixed
     */
    public function create($input)
    {
        $feedback = $this->createFeedbackStub($input);

        if ($feedback != null)
        {
            DB::transaction(function () use ($feedback, $input)
            {
                $feedback->save();

                $pics = isset($input['pics']) ? $input['pics'] : array();

                if (count($pics) > 0)
                {
                    $pics_array = array();

                    foreach ($pics as $pic)
                    {
                        if (!empty($pic))
                        {
                            array_push($pics_array, $this->createFeedbackImage($pic));
                        }
                    }

                    if (count($pics_array) > 0)
                    {
                        $feedback->images()->saveMany($pics_array);
                    }
                }
            });
        }

        return $feedback;
    }

    /**
     * @param $pic
     * @return FeedbackImage
     */
    private function createFeedbackImage($pic)
    {
        $feedbackImage = new FeedbackImage();
        $feedbackImage->url = $pic;

        return $feedbackImage;
    }

    /**
     * @param $input
     * @return Feedback
     */
    private function createFeedbackStub($input)
    {
        $feedback = new Feedback();
        $feedback->customer_id = $input['customer_id'];
        $feedback->remark = $input['remark'];
        $feedback->telephone = isset($input['telephone']) ? $input['telephone'] : "";
        $feedback->status = FeedbackStatus::UNPROCESSED;

        return $feedback;
    }

    /**
     * @param $customerId
     * @return mixed
     */
    public function getReplay($customerId)
    {
        $data = Feedback::where('customer_id',$customerId)
            ->groupBy('feedbacks.id','feedbacks.remark', 'feedbacks.status', 'feedbacks.reply','feedbacks.created_at')
            ->leftjoin('feedback_images', 'feedback_images.feedback_id', '=', 'feedbacks.id')
            ->select('feedbacks.remark', 'feedbacks.status', 'feedbacks.reply','feedbacks.created_at', DB::raw('group_concat(feedback_images.url) as urls'))
            ->whereNotNull('feedbacks.reply')
            ->orderBy('feedbacks.created_at', 'desc')
            ->get();

        return $data;
    }

}
