<?php

namespace App\Repositories\Crm;

use App\Models\Survey;
use App\Models\SurveyFeedback;
use App\Models\SurveyFeedbackDetail;
use App\Models\SurveyQuestion;
use Carbon\Carbon;
use Illuminate\Support\Str;
use DB;

class SurveyFeedbackRepository
{
    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 = SurveyFeedback::with([
            'survey',
            'detail'
        ])->select('survey_feedback.*')
        ->leftJoin('customers', 'survey_feedback.customer_id', 'customers.id')
        ->leftJoin('survey', 'survey_feedback.survey_id', 'survey.id')
        ->when(@$params["filter"]['start'], function($query) use ($params){
            $query->whereDate("survey_feedback.time", '>=', $params['filter']['start']);
        })
        ->when(@$params["filter"]['end'], function($query) use ($params){
            $query->whereDate("survey_feedback.time", '<=', $params['filter']['end']);
        })
        ->when(@$params["filter"]['survey_id'], function($query) use ($params){
            $query->where("survey_id", $params['filter']['survey_id']);
        })
         ->when(@$params["filter"]['status'], function($query) use ($params){
            if($params['filter']['status'] == 'BELUM DIISI') {
                $query->whereNull("survey_feedback.time");
            }

            if($params['filter']['status'] == 'SUDAH DIISI') {
                $query->whereNotNull("survey_feedback.time");
            }
        }) 
        ->when(@$params["search"], function($query) use ($params){
            $query->where(function($query) use ($params) {
                 $query->where("survey.name","ilike","%". $params["search"] . "%")
                    ->orWhere("customers.name","ilike","%". $params["search"] . "%");
            });
        })
        ->where("survey_feedback.customer_id", auth()->user()->customer->id)
        ->orderBy($sortColumn, $sortDir)
        ->paginate($limit);
        
        return $results;
    }
}