<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Traits\CsvImportTrait;
use App\Http\Requests\MassDestroyChecklistReportRequest;
use App\Http\Requests\StoreChecklistReportRequest;
use App\Http\Requests\UpdateChecklistReportRequest;
use App\Models\ChecklistReport;
use App\Models\FusionType;
use App\Models\ServiceComplaint;
use Gate;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\Response;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\URL;


class ChecklistReportController extends Controller
{
    use CsvImportTrait;

    public function index(Request $request)
    {
        abort_if(Gate::denies('checklist_report_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        if ($request->ajax()) {
            $query = ChecklistReport::with(['complaint', 'checklist_name', 'checklist_status_fusion_types_1', 'checklist_status_fusion_types_2', 'team'])->select(sprintf('%s.*', (new ChecklistReport)->table));
            $table = Datatables::of($query);

            $table->addColumn('placeholder', '&nbsp;');
            $table->addColumn('actions', '&nbsp;');

            $table->editColumn('actions', function ($row) {
                $viewGate      = 'checklist_report_show';
                $editGate      = 'checklist_report_edit';
                $deleteGate    = 'checklist_report_delete';
                $crudRoutePart = 'checklist-reports';

                return view('partials.datatablesActions', compact(
                    'viewGate',
                    'editGate',
                    'deleteGate',
                    'crudRoutePart',
                    'row'
                ));
            });

            $table->editColumn('id', function ($row) {
                return $row->id ? $row->id : '';
            });
            $table->addColumn('complaint_complaint', function ($row) {
                return $row->complaint ? $row->complaint->complaint : '';
            });

            $table->addColumn('checklist_name_name', function ($row) {
                return $row->checklist_name ? $row->checklist_name->name : '';
            });

            $table->editColumn('checklist_status', function ($row) {
                return $row->checklist_status ? $row->checklist_status : '';
            });
            $table->editColumn('checklist_value_text_1', function ($row) {
                return $row->checklist_value_text_1 ? $row->checklist_value_text_1 : '';
            });
            $table->editColumn('checklist_value_text_2', function ($row) {
                return $row->checklist_value_text_2 ? $row->checklist_value_text_2 : '';
            });
            $table->addColumn('checklist_status_fusion_types_1_name', function ($row) {
                return $row->checklist_status_fusion_types_1 ? $row->checklist_status_fusion_types_1->name : '';
            });

            $table->addColumn('checklist_status_fusion_types_2_name', function ($row) {
                return $row->checklist_status_fusion_types_2 ? $row->checklist_status_fusion_types_2->name : '';
            });

            $table->rawColumns(['actions', 'placeholder', 'complaint', 'checklist_name', 'checklist_status_fusion_types_1', 'checklist_status_fusion_types_2']);

            return $table->make(true);
        }

        return view('admin.checklistReports.index');
    }

    public function create()
    {
        abort_if(Gate::denies('checklist_report_create'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $complaints = ServiceComplaint::pluck('complaint', 'id')->prepend(trans('global.pleaseSelect'), '');

        $checklist_names = FusionType::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $checklist_status_fusion_types_1s = FusionType::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $checklist_status_fusion_types_2s = FusionType::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        return view('admin.checklistReports.create', compact('checklist_names', 'checklist_status_fusion_types_1s', 'checklist_status_fusion_types_2s', 'complaints'));
    }

    public function store(StoreChecklistReportRequest $request)
    {
        $checklistReport = ChecklistReport::create($request->all());

        return redirect()->route('admin.checklist-reports.index');
    }

    public function edit(ChecklistReport $checklistReport)
    {
        abort_if(Gate::denies('checklist_report_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $complaints = ServiceComplaint::pluck('complaint', 'id')->prepend(trans('global.pleaseSelect'), '');


        $checklist_names = FusionType::where('fusioncategory_id',5)->pluck('name', 'id');
        $fusion_types      = FusionType::where('fusioncategory_id',7)->get();
        $checklist_status_fusion_types_1s = FusionType::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');
        $checklist_status_fusion_types_2s = FusionType::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        //ddd($checklist_names);
        if(request()->comp_id){
        $existing_val = ChecklistReport::where('complaint_id',request()->comp_id)->get(['checklist_name_id','checklist_value_text_1','checklist_value_text_2','checklist_status','remarks']);
        }else{
            $existing_val = [];
        }

        //dd($checklist_names,$existing_val);

        $checklistReport->load('complaint', 'checklist_name', 'checklist_status_fusion_types_1', 'checklist_status_fusion_types_2', 'checklist_single_line_remarks','team');

        return view('admin.checklistReports.edit', compact('existing_val','checklistReport', 'checklist_names', 'checklist_status_fusion_types_1s', 'checklist_status_fusion_types_2s', 'complaints'));
    }

    public function update(UpdateChecklistReportRequest $request, ChecklistReport $checklistReport)
    {

        $fsr_request = $request->post();

        foreach($fsr_request as $key => $value ) {


                $checklist_name_id=Str::afterLast($key,"_");
                if (ctype_digit($checklist_name_id)) {
                    $fsr_values[$checklist_name_id]['checklist_name_id']=$checklist_name_id;
                    $fsr_values[$checklist_name_id]['complaint_id']=$fsr_request['complaint_id'];
                }


        //checking if complaint_id is integer
        if (!empty($checklist_name_id) && ctype_digit($checklist_name_id)) {
          //  $fsr_values['checklist_status_fusion_types_1_id']=$checklist_name_id;
          //  $fsr_values['checklist_status_fusion_types_2_id']=$checklist_name_id;

            if(Str::contains($key, "checklist_value_text_1"))
                {
                    $fsr_values[$checklist_name_id]['checklist_value_text_1']=$value[0];
                }

            if(Str::contains($key, "checklist_value_text_2"))
                {
                    $fsr_values[$checklist_name_id]['checklist_value_text_2']=$value[0];
                }

                if(Str::contains($key, "remarks"))
                {
                    $fsr_values[$checklist_name_id]['remarks']=$value[0];
                }


               if(Str::contains($key, "checklist_status"))
               {
                   if(!empty($value[0])) {
                       // If checklist_status field exists and has a value, use that value
                       $fsr_values[$checklist_name_id]['checklist_status'] = $value[0];
                   } else {
                       // If checklist_status field exists but is empty, set to "Yes"
                       $fsr_values[$checklist_name_id]['checklist_status'] = "Yes";
                   }
               }


            } else {
                    // Do not convert print error message
                    //exit();
                            }
        //for loop end
            }
        //for loop end
// After processing all form fields, ensure every checklist has a status
foreach ($fsr_values as $checklist_name_id => $data) {
    if (!isset($data['checklist_status'])) {
        $fsr_values[$checklist_name_id]['checklist_status'] = "Yes";
    }
}

        if(!empty($fsr_values)){
            //$checklistReport::upsert($fsr_values,uniqueBy:['checklist_name_id','complaint_id'],update:['checklist_status','checklist_value_text_2','checklist_value_text_1']);

            foreach($fsr_values as $key => $value) {
                //var_dump($key['complaint_id']);
                if($checklistReport::where('complaint_id',$value['complaint_id'])->where('checklist_name_id',$value['checklist_name_id'])->exists()){
                        $checklistReport::where('complaint_id',$value['complaint_id'])
                                          ->where('checklist_name_id',$value['checklist_name_id'])
                                          ->update($value,['remarks','checklist_value_text_2','checklist_value_text_1'])
                                            ;

                }else{
                    $checklistReport::insert($value);

                }



                //Inserting the Signature Pad Sign if not empty
                //Laravel Upsert will not work for mysql, so use normal query
                if(!empty($fsr_request['remarks_1201']))    {
                    //Insert Signature
                    $checklistReport::updateOrCreate(
                        ['complaint_id'=>$value['complaint_id'],'checklist_name_id'=>1201],
                        ['remarks'=>$fsr_request['remarks_1201']]);

                        //Close Complaint
                        ServiceComplaint::where('id',$value['complaint_id'])->update(['status_id'=>34]);
                }


                }

            }
        //$checklistReport->update($request->all());
        //return view('admin.serviceComplaints.show', compact('serviceComplaint'));
        //return redirect()->route('admin.serviceComplaints.show',[$fsr_request['complaint_id']]);



        //Closinng the Complaint

        return back()->withInput();

    }

    public function show(ChecklistReport $checklistReport)
    {
        abort_if(Gate::denies('checklist_report_show'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $checklistReport->load('complaint', 'checklist_name', 'checklist_status_fusion_types_1', 'checklist_status_fusion_types_2', 'team');

        return view('admin.checklistReports.show', compact('checklistReport'));
    }

    public function destroy(ChecklistReport $checklistReport)
    {
        abort_if(Gate::denies('checklist_report_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $checklistReport->delete();

        return back();
    }

    public function massDestroy(MassDestroyChecklistReportRequest $request)
    {
        $checklistReports = ChecklistReport::find(request('ids'));

        foreach ($checklistReports as $checklistReport) {
            $checklistReport->delete();
        }

        return response(null, Response::HTTP_NO_CONTENT);
    }
}
