<?php

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

class TestimonyController extends Controller
{
    public function __construct(ResponseRepository $response){
        $this->response = $response;
        $this->storeRules = [
            'title' => 'required',
            'author_name' => 'required',
            'testimony_description' => 'required',
        ];
    }

    public function indexTestimony() {
        return $this->response->jsonResponse(false,"Testimony Details Fetched Successfully", Testimony::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('Testimony', 'store'), Testimony::create($request->all()), 301);
        } else {
            return $validate;
        }
    }

    public function show($id) {
        return $this->response->jsonResponse(false, $this->response->message('Testimony', 'show'), $this->findTestimony($id), 302);
    }

    public function updateTestimony(Request $request) {
        $validate = $this->response->validate($request->all(), [
            'author_name' => ['required'],
            'title' => ['required'],
            'testimony_description' => ['required'],
        ]);
        if($validate === true) {
            return $this->response->jsonResponse(false, $this->response->message('Testimony', 'update'), $this->findTestimony($request->id)->update($request->all()), 303);
        } else {
            return $validate;
        }
    }

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

    public function findTestimony($id) {
        return Testimony::find($id);
    }

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