<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Repositories\ResponseRepository;
use App\Models\CrEndUser;

class CrEndUserController extends Controller
{
    //
    public function __construct(ResponseRepository $response){
        $this->response = $response;
        $this->storeRules = [
            'cr_end_user_mt' => 'required',
            'cr_end_user_icon' => 'required',
            'cr_end_user_st' => 'required',
        ];
    }

    public function indexCrEndUser() {
        return $this->response->jsonResponse(false,"Cr End User Details Fetched Successfully", CrEndUser::orderBy('id', 'desc')->get(), 300);
    }

    public function store(Request $request) {
        $validate = $this->response->validate($request->all(), $this->storeRules);
        if($validate === true) {
            return $this->response->jsonResponse(false, $this->response->message('Cr End User', 'store'), CrEndUser::create($request->all()), 301);
        } else {
            return $validate;
        }
    }

    public function show($id) {
        return $this->response->jsonResponse(false, $this->response->message('Cr End User', 'show'), $this->findCrEndUser($id), 302);
    }

    public function updateCrEndUser(Request $request) {
        $validate = $this->response->validate($request->all(), [
            'cr_end_user_mt' => ['required'],
            'cr_end_user_icon' => ['required'],
            'cr_end_user_st' => ['required'],
        ]);
        if($validate === true) {
            return $this->response->jsonResponse(false, $this->response->message('Cr End User', 'update'), $this->findCrEndUser($request->id)->update($request->all()), 303);
        } else {
            return $validate;
        }
    }

    public function destroy($id) {
        $size = $this->findCrEndUser($id);
        if($size) {
            return $this->response->jsonResponse(false, $this->response->message('Cr End User', 'destroy'), $size->delete(), 304);
        }
        return $this->response->jsonResponse(true, 'Cr End User Not Exists', [], 305);
    }

    public function findCrEndUser($id) {
        return CrEndUser::find($id);
    }

    public function crEndUserSwitch($id) {
        $size = $this->findCrEndUser($id);
        if($size) {
            $value = $size->active_status === 1 ? 0 : 1;
            $msg = $value === 0 ? 'Deactivated': 'Activated';
            return $this->response->jsonResponse(false, 'Cr End User '.$msg.' SuccessFully', $size->update(['active_status' => $value]), 306);
        }
        return $this->response->jsonResponse(true, 'Cr End User Not Exists', [], 307);
    }

}
