<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\Corporate;
use App\Models\CorporateService;
use App\Models\CorporateServiceConfig;
use App\Models\CorporateServiceSpeciality;
use App\Models\Speciality;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Internal\Transformers\CorporateServiceConfigResource;
use Termwind\Components\Dd;

class CorporateServiceController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request, $corporate_id)
    {
        $services = CorporateService::with('configs', 'service')->where('corporate_id', $corporate_id)->filter($request->toArray())->paginate();

        return Helper::paginateResources(CorporateServiceConfigResource::collection($services));
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('internal::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        return view('internal::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('internal::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $corporate_id)
    {
        $corporateService = CorporateService::where('corporate_id', $corporate_id)->where('service_code', $request->service_code)->first();

        $corporateServiceConfig = $corporateService->configs()->updateOrCreate([
            'corporate_service_id' => $corporateService->id,
            'name' => $request->config_name
        ], [
            'name' => $request->config_name,
            'value' => $request->config_value
        ]);

        return $corporateServiceConfig;
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        //
    }

    public function corporateServiceIndex($corporate_id, $service_code)
    {
        $corporate = Corporate::findOrFail($corporate_id)->with(['plans'])->first();
        $plans = $corporate['plans']->map(function ($plan) {
            return [
                'id' => $plan['id'],
                'code' => $plan['code'],
                'corporate_id' => $plan['corporate_id'],
                'corporate_plan_id' => $plan['corporate_plan_id'],
            ];
        });

        unset($corporate['plans']);
        $corporate['plans'] = $plans;

        $corporateService = CorporateService::query()
            ->where('corporate_id', $corporate_id)
            ->where('service_code', $service_code)
            ->with([
                'configs', 'service',
                'corporateServiceSpecialities',
                'corporateServiceSpecialities.speciality',
                'corporateServiceSpecialities.exclusions.rules'
            ])
            ->first();
        // $service = CorporateServiceConfigResource::make($corporateService);
        $specialities = Speciality::get();

        return response()->json(
            [
                'corporate' => $corporate,
                'service' => CorporateServiceConfigResource::make($corporateService),
                'specialities' => $specialities,
            ]
        );
    }

    public function corporateServiceUpdate(Request $request, $corporate_id, $service_code)
    {
        // dd($request->all);
        // $corporate = Corporate::findOrFail($corporate_id);
        $corporateService = CorporateService::query()
            ->where('corporate_id', $corporate_id)
            ->where('service_code', $service_code)
            // ->with('configs', 'service')
            ->first();
        $corporateService->fill([
            'status' => $request->status == 'active' ? 'inactive' : 'active',
            'reason' => $request->reason
        ]);
        $corporateService->save();

        return response()->json($corporateService);
    }

    public function corporateServiceSpecialityUpdate(Request $request, $corporate_id, $service_code)
    {
        // return response()->json([$request->checked, $request->value, $request->speciality_id]);

        $corporateService = CorporateService::query()
            ->where('corporate_id', $corporate_id)
            ->where('service_code', $service_code)
            ->first();

        $corporateServiceSpeciality = CorporateServiceSpeciality::updateOrCreate([
            'corporate_service_id' => $corporateService->id,
            'speciality_id' => $request->speciality_id,
        ], [
            'corporate_service_id' => $corporateService->id,
            'speciality_id' => $request->speciality_id,
            'active' => $request->active
        ]);

        $exclusion =  $corporateServiceSpeciality->exclusions()->updateOrCreate([
            'corporate_id' => $corporate_id,
            'service_code' => $service_code,
        ], [
            'corporate_id' => $corporate_id,
            'service_code' => $service_code,
            'type' => 'speciality',
        ]);


        $selected_specialities = CorporateServiceSpeciality::query()
            ->where('corporate_service_id', $corporateService->id)
            ->where('active', true)
            ->with('speciality')
            ->get()
            ->pluck('speciality.name', 'speciality.id');

        return response()->json($selected_specialities);
    }

    public function corporateServiceSpecialityAllUpdate(Request $request, $corporate_id, $service_code)
    {
        // return response()->json([$request->checked, $request->value, $request->speciality_id]);

        $corporateService = CorporateService::query()
            ->where('corporate_id', $corporate_id)
            ->where('service_code', $service_code)
            ->first();
        
        $specialities = Speciality::get()->toArray();

        if ($specialities){
            foreach($specialities as $s){
                $corporateServiceSpeciality = CorporateServiceSpeciality::updateOrCreate([
                    'corporate_service_id' => $corporateService->id,
                    'speciality_id' => $s['id'],
                ], [
                    'corporate_service_id' => $corporateService->id,
                    'speciality_id' => $s['id'],
                    'active' => $request->active
                ]);

                $corporateServiceSpeciality = CorporateServiceSpeciality::updateOrCreate([
                    'corporate_service_id' => $corporateService->id,
                    'speciality_id' =>  $s['id'],
                ], [
                    'corporate_service_id' => $corporateService->id,
                    'speciality_id' =>  $s['id'],
                    'active' => $request->active
                ]);

                $corporateServiceSpecialityRule = CorporateServiceSpeciality::where('corporate_service_id', $corporateService->id)
                    ->where('speciality_id', $s['id'])
                    ->with('exclusions.rules')
                    ->first();

                // Exclusion Rules
                if (empty($corporateServiceSpecialityRule)) {
                    $corporateServiceSpecialityRule = CorporateServiceSpeciality::create([
                        'corporate_service_id' => $corporateService->id,
                        'speciality_id' => $s['id'],
                        'active' => false,
                    ]);
        
                    $corporateServiceSpecialityRule->exclusions()->updateOrCreate([
                        'corporate_id' => $corporate_id,
                        'service_code' => $service_code,
                    ], [
                        'corporate_id' => $corporate_id,
                        'service_code' => $service_code,
                        'type' => 'speciality',
                    ]);
                } else {
                    $corporateServiceSpecialityRule->exclusions()->updateOrCreate([
                        'corporate_id' => $corporate_id,
                        'service_code' => $service_code,
                    ], [
                        'corporate_id' => $corporate_id,
                        'service_code' => $service_code,
                        'type' => 'speciality',
                    ]);
                }
        
                $exclusion = $corporateServiceSpecialityRule->exclusions()->where('corporate_id', $corporate_id)->where('service_code', $service_code)->first();
                
                // if($exclusion){
                    $exclusion_rule = $exclusion->rules()->updateOrCreate([
                        'exclusion_id' => $exclusion->id,
                        'name' => 'msc',
                    ], [
                        'name' => 'msc',
                        'values' => $request->active ? 'm,s,c' : '',
                    ]);
    
                    $exclusion_rule = $exclusion->rules()->updateOrCreate([
                        'exclusion_id' => $exclusion->id,
                        'name' => 'gender',
                    ], [
                        'name' => 'gender',
                        'values' => $request->active ? 'male,female' : '',
                    ]);
                // }
            }

        }
       
        $exclusion =  $corporateServiceSpeciality->exclusions()->updateOrCreate([
            'corporate_id' => $corporate_id,
            'service_code' => $service_code,
        ], [
            'corporate_id' => $corporate_id,
            'service_code' => $service_code,
            'type' => 'speciality',
        ]);

        $selected_specialities = CorporateServiceSpeciality::query()
            ->where('corporate_service_id', $corporateService->id)
            ->where('active', true)
            ->with('speciality')
            ->get()
            ->pluck('speciality.name', 'speciality.id');

        // return response()->json($selected_specialities);
        return response()->json([
            'selected_specialities' => $selected_specialities,
            'service' => CorporateServiceConfigResource::make($corporateService),
        ]);
    }


    public function storeExclusion(Request $request, $corporate_id, $service_code)
    {

        $corporateService = CorporateService::query()
            ->where('corporate_id', $corporate_id)
            ->where('service_code', $service_code)
            ->first();

        $corporateServiceSpeciality = CorporateServiceSpeciality::where('corporate_service_id', $corporateService->id)
            ->where('speciality_id', $request->speciality_id)
            ->with('exclusions.rules')
            ->first();

        if (empty($corporateServiceSpeciality)) {
            $corporateServiceSpeciality = CorporateServiceSpeciality::create([
                'corporate_service_id' => $corporateService->id,
                'speciality_id' => $request->speciality_id,
                'active' => false,
            ]);

            $corporateServiceSpeciality->exclusions()->updateOrCreate([
                'corporate_id' => $corporate_id,
                'service_code' => $service_code,
            ], [
                'corporate_id' => $corporate_id,
                'service_code' => $service_code,
                'type' => 'speciality',
            ]);
        }

        $exclusion = $corporateServiceSpeciality->exclusions()->where('corporate_id', $corporate_id)->where('service_code', $service_code)->first();


        if ($request->type == 'msc') {
            $value_input = $request->value;
            $current_msc = $exclusion->rules()->where('name', 'msc')->first()->values ?? null;

            if (!empty($current_msc)) {
                $values = "";
                if ($request->value == 'm' && $request->checked == "1") {
                    $values = $current_msc . "," . $value_input;
                }

                if ($request->value == 's' && $request->checked == "1") {
                    $values = $current_msc . "," . $value_input;
                }

                if ($request->value == 'c' && $request->checked == "1") {
                    $values = $current_msc . "," . $value_input;
                }

                if ($request->value == 'm' && $request->checked == "0") {
                    $values = str_replace($value_input, "", $current_msc);
                    $values = str_replace(",,", ",", $values);
                    $values = trim($values, ",");
                }

                if ($request->value == 's' && $request->checked == "0") {
                    $values = str_replace($value_input, "", $current_msc);
                    $values = str_replace(",,", ",", $values);
                    $values = trim($values, ",");
                }

                if ($request->value == 'c' && $request->checked == "0") {
                    $values = str_replace($value_input, "", $current_msc);
                    $values = str_replace(",,", ",", $values);
                    $values = trim($values, ",");
                }

                $exclusion_rule = $exclusion->rules()->updateOrCreate([
                    'exclusion_id' => $exclusion->id,
                    'name' => 'msc',
                ], [
                    'name' => 'msc',
                    'values' => $values,
                ]);
            } else {
                if ($request->value == 'm' && $request->checked == "1") {
                    $values = $value_input;
                }

                if ($request->value == 's' && $request->checked == "1") {
                    $values = $value_input;
                }

                if ($request->value == 'c' && $request->checked == "1") {
                    $values = $value_input;
                }

                $exclusion_rule = $exclusion->rules()->updateOrCreate([
                    'exclusion_id' => $exclusion->id,
                    'name' => 'msc',
                ], [
                    'name' => 'msc',
                    'values' => $values,
                ]);
            }
        }

        if ($request->type == 'gender') {
            $value_input = $request->value;
            $current_gender = $exclusion->rules()->where('name', 'gender')->first()->values ?? null;

            if (!empty($current_gender)) {
                $values = "";
                if ($request->value == 'male' && $request->checked == "1") {
                    $values = $current_gender . "," . $value_input;
                }

                if ($request->value == 'female' && $request->checked == "1") {
                    $values = $current_gender . "," . $value_input;
                }

                if ($request->value == 'male' && $request->checked == "0") {
                    if (substr($current_gender, 0, 4) == "male") {
                        $values = str_replace($value_input, "", $value_input) . substr($current_gender, 5, 10);
                    } else {
                        $values = str_replace($value_input, "", $value_input) . substr($current_gender, 0, 6);
                    }
                }

                if ($request->value == 'female' && $request->checked == "0") {
                    $values = str_replace($value_input, "", $current_gender);
                    $values = str_replace(",,", ",", $values);
                    $values = trim($values, ",");
                }

                $exclusion_rule = $exclusion->rules()->updateOrCreate([
                    'exclusion_id' => $exclusion->id,
                    'name' => 'gender',
                ], [
                    'name' => 'gender',
                    'values' => $values,
                ]);
            } else {
                if ($request->value == 'male' && $request->checked == "1") {
                    $values = $value_input;
                }

                if ($request->value == 'female' && $request->checked == "1") {
                    $values = $value_input;
                }

                $exclusion_rule = $exclusion->rules()->updateOrCreate([
                    'exclusion_id' => $exclusion->id,
                    'name' => 'gender',
                ], [
                    'name' => 'gender',
                    'values' => $values,
                ]);
            }
        }

        if ($request->type == "min_age") {
            $exclusion_rule = $exclusion->rules()->updateOrCreate([
                'exclusion_id' => $exclusion->id,
                'name' => 'min_age',
            ], [
                'name' => 'min_age',
                'values' => $request->value,
            ]);
        }

        if ($request->type == "max_age") {
            $exclusion_rule = $exclusion->rules()->updateOrCreate([
                'exclusion_id' => $exclusion->id,
                'name' => 'max_age',
            ], [
                'name' => 'max_age',
                'values' => $request->value,
            ]);
        }

        if ($request->type == "plan") {
            $value = $request->value;
            foreach ($value as $key => $val) {
                $item[] = $val['value'];
            }

            $plan = implode(",", $item);

            $exclusion_rule = $exclusion->rules()->updateOrCreate([
                'exclusion_id' => $exclusion->id,
                'name' => 'plan',
            ], [
                'name' => 'plan',
                'values' => $plan ?? '',
            ]);
        }

        if ($request->type == "one_row") {
            $data = $request->one_row;

            $exclusion->rules()->updateOrCreate([
                'exclusion_id' => $exclusion->id,
                'name' => 'min_age',
            ], [
                'name' => 'min_age',
                'values' => $data['min_age'] ?? '',
            ]);


            $exclusion->rules()->updateOrCreate([
                'exclusion_id' => $exclusion->id,
                'name' => 'max_age',
            ], [
                'name' => 'max_age',
                'values' => $data['max_age'] ?? '',
            ]);

            $exclusion->rules()->updateOrCreate([
                'exclusion_id' => $exclusion->id,
                'name' => 'plan',
            ], [
                'name' => 'plan',
                'values' => $data['plan'] ?? '',
            ]);
        }


        $selected_specialities = CorporateServiceSpeciality::query()
            ->where('corporate_service_id', $corporateService->id)
            ->where('active', true)
            ->with('speciality')
            ->get()
            ->pluck('speciality.name', 'speciality.id');

        $corporateService = CorporateService::query()
            ->where('corporate_id', $corporate_id)
            ->where('service_code', $service_code)
            ->with([
                'configs', 'service',
                'corporateServiceSpecialities',
                'corporateServiceSpecialities.speciality',
                'corporateServiceSpecialities.exclusions.rules'
            ])
            ->first();

        return response()->json([
            'selected_specialities' => $selected_specialities,
            'service' => CorporateServiceConfigResource::make($corporateService),
        ]);
    }

    
}
