<?php

namespace App\Http\Controllers;

use App\Models\Testimonial;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Storage;

class TestimonialController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id='')
    {
        if($id>0){
            $arr=Testimonial::where(['id'=>$id])->get();
            $result['name']=$arr['0']->name;
            $result['post']=$arr['0']->post;
            $result['descr']=$arr['0']->descr;

            $result['id']=$arr['0']->id;

        }else {
            $result['name']='';
            $result['post']='';
            $result['descr']='';

            $result['id']='';

        }
        
        return view('backend/testimonial_add',$result);
    }

    public function manage_testimonial_process(Request $request)
    {

        $request->validate([
            'name'=>'required',
            'post'=>'required',
        ]);
        
        
        if ($request->post('id')>0) {
            $model=Testimonial::find($request->post('id'));
            $msg="Testimonial updated succesfuly";
        }else {
            $model=new Testimonial();
            $msg="Testimonial added succesfuly";
        }
        
        $model->name=$request->name;
        $model->post=$request->post;
        $model->descr=$request->descr;
        $model->save();
        if ($model->save()) {
            return redirect()->route('testimonials')->with(['msg'=>$msg]);
        }else {
            return back()->with(['msg'=>'Something went wrong']);
        }
    }

    public function show(Testimonial $testimonial)
    {
        $data['testimonials'] = Testimonial::all();

        return view('backend/testimonial', $data);
    }

    public function delete(Request $request){
        $id = $request->id;
        $query = Testimonial::find($id)->delete();
        if ($query) {
            return back()->with(['msg'=>'Testimonial deleted succesfuly']);
        } else {
            return back()->with(['msg'=>'Something went wrong']);
        }
        
    }
}
