<?php

namespace App\Http\Controllers;

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

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

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

        }else {
            $result['descr']='';
            $result['image']='';

            $result['id']='';

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

    public function manage_about_process(Request $request)
    {
        if ($request->post('id')>0) {
            $image_validation="mimes:jpg,jpeg,png";
        }else {
            $image_validation="required|mimes:jpg,jpeg,png";
        }

        $request->validate([
            'descr'=>'required',
            'image'=>$image_validation,
        ]);
        
        
        if ($request->post('id')>0) {
            $model=About::find($request->post('id'));
            $msg="Section updated succesfuly";
        }else {
            $model=new About();
            $msg="Section added succesfuly";
        }
        if ($request->hasfile('image')) {
            if ($request->post('id')>0) {
                $arrImage=DB::table('abouts')->where(['id'=>$request->post('id')])->get();
                if (Storage::exists('/public/media/'.$arrImage[0]->image)) {
                    Storage::delete('/public/media/'.$arrImage[0]->image);
                }
            }

            $image=$request->file('image');
            $ext=$image->extension();
            $image_name=time().'.'.$ext;
            $image->storeAs('./public/media', $image_name);
            $model->image=$image_name;
        }
        $model->descr=$request->descr;
        $model->save();
        if ($model->save()) {
            return redirect()->route('abouts')->with(['msg'=>$msg]);
        }else {
            return back()->with(['msg'=>'Something went wrong']);
        }
    }

    public function show(About $about)
    {
        $data['abouts'] = About::all();
        return view('backend/about', $data);
    }

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