<?php

namespace App\Repositories\Crm;

use App\Models\Survey;
use App\Models\SurveyFeedback;
use App\Models\SurveyFeedbackDetail;
use App\Models\SurveyQuestion;
use App\Notifications\Crm\SurveyRespond;
use App\Repositories\Member\VoucherEvent\VoucherEventRepository;
use Carbon\Carbon;
use Illuminate\Support\Str;
use DB;

class SurveyRepository
{

    var $voucherEventRepository;

    public function __construct(
        VoucherEventRepository $voucherEventRepository) {
        $this->voucherEventRepository = $voucherEventRepository;
    }

    public function getList(array $params = [])
    {
        $limit = @$params["limit"] ? (int) @$params["limit"] : 10;
        $sortColumn = @$params["sort"]["column"] ? $params["sort"]["column"] : "id";
        $sortDir = @$params["sort"]["dir"] ? $params["sort"]["dir"] : "desc";

        $results = Survey::when(@$params["search"], function($query) use ($params){
            $query->where("name","ilike","%". $params["search"] . "%")
                ->where("code","ilike","%". $params["search"] . "%");
        })
        ->orderBy($sortColumn, $sortDir)
        ->paginate($limit);

        return $results;
    }

    public function getListDetail(Survey $survey, array $params = [])
    {
        $limit = @$params["limit"] ? (int) @$params["limit"] : 10;
        $sortColumn = @$params["sort"]["column"] ? $params["sort"]["column"] : "id";
        $sortDir = @$params["sort"]["dir"] ? $params["sort"]["dir"] : "desc";

        $results = SurveyQuestion::where('survey_id', $survey->id)
        ->when(@$params["search"], function($query) use ($params){
            $query->where("description","ilike","%". $params["search"] . "%");
        })
        ->orderBy($sortColumn, $sortDir)
        ->paginate($limit);

        return $results;
    }

    public function createFeedback(Survey $survey, array $data) {
        do {
             $code = md5(Str::random(40));
        } while(SurveyFeedback::where('code', $code)->first());

        $feedback = SurveyFeedback::create([
            'code' => $code,
            'survey_id' => $survey->id,
            'channel' => @$data['channel'],
            'customer_id' => @$data['customer_id'],
            'invoice_id' => @$data['invoice_id'],
            'ip_address' => @$data['ip_address'],
            'agent' => @$data['agent'],
            'time' => Carbon::now()
        ]);

        foreach($data['details'] as $detail) {
            $surveyDetail = $survey->detail->where('id', $detail['survey_question_id'])->first();

            $feedback->detail()->create([
                'description' => @$surveyDetail->description,
                'value' => $detail['value'],
                'survey_question_id' => $detail['survey_question_id']
            ]);
        }

        if ($feedback->customer){
            $notif = new SurveyRespond($feedback);
            $feedback->customer->notify($notif);
        }

        return $feedback;
    }

    public function generateFeedback(Survey $survey, array $data) {
        do {
             $code = md5(Str::random(40));
        } while(SurveyFeedback::where('code', $code)->first());

        if (@$data['customer_id'])
        {
            $last_feedback = SurveyFeedback::where("customer_id", @$data['customer_id'])
                ->whereDate("created_at",">=", Carbon::now()->subMonth(1))
                ->first();
            if ($last_feedback)
            {
                return null;
            }
        }

        $feedback = SurveyFeedback::create([
            'code' => $code,
            'survey_id' => $survey->id,
            'channel' => @$data['channel'],
            'customer_id' => @$data['customer_id'],
            'invoice_id' => @$data['invoice_id']
        ]);

        return $feedback;
    }

    public function create(array $data)
    {
        do {
             $code = md5(Str::random(40));
        } while(Survey::where('code', $code)->first());

        $item = Survey::create([
            'name' => $data['name'],
            'code' => md5(Str::random(40)),
            'title' => @$data['title'],
            'content' => @$data['content'],
            'voucher_event_id' => @$data['voucher_event_id']
        ]);

        return $item;
    }

    public function createDetail(Survey $survey, array $data)
    {
        $item = SurveyQuestion::create([
            'survey_id' => $survey->id,
            'description' => $data['description'],
            'type' => $data['type'],
            'data' => $data['data'],
            'order' => $data['order']
        ]);

        return $item;
    }

    public function update(Survey $item, array $data)
    {
        $item->update($data);
        return $item;
    }

    public function updateDetail(SurveyQuestion $item, array $data)
    {
        $item->update($data);
        return $item;
    }

    public function updateFeedbackDetail(SurveyFeedback $item, array $data)
    {
        if ($item->time == null){
            $invoice = @$item->invoice;
            $voucherEvent = @$item->survey->voucherEvent;
            if ($invoice && $voucherEvent){
                $expired = Carbon::now()->addDay(30);
                $voucher = $this->voucherEventRepository->createVoucher($voucherEvent, $invoice->customer, $invoice->customer->user, "FREE VOUCHER SURVEY GIFT", $expired, 400000);

                if ($voucher){

                    $notif = new SurveyRespond($item, $voucher);
                    $invoice->customer->notify($notif);
                }
            }
        }
        $item->update([
            "time" => Carbon::now(),
            'ip_address' => @$data['ip_address'],
            'agent' => @$data['agent'],
        ]);

        foreach($data['details'] as $detail) {
            $feedbackDetail = $item->detail()->where('survey_question_id', $detail['survey_question_id'])->first();
            $surveyDetail = SurveyQuestion::where('id', $detail['survey_question_id'])->first();

            if($feedbackDetail) {
                $feedbackDetail->update([
                    'description' => @$surveyDetail->description,
                    'value' => $detail['value']
                ]);
            } else {
                $item->detail()->create([
                    'survey_question_id' => $detail['survey_question_id'],
                    'description' => @$surveyDetail->description,
                    'value' => $detail['value']
                ]);
            }
        }

        return $item;
    }

    public function delete(Survey $item)
    {
        $item->delete();
    }

    public function deleteDetail(SurveyQuestion $item)
    {
        $item->delete();
    }

    public function findBy($column, $value)
    {
        $item = Survey::where($column, $value)->firstOrFail();
        return $item;
    }

}
