<?php

namespace App\Http\Controllers;

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

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

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

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

            $result['id']='';

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

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

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

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

    public function show(Certificate $certificate)
    {
        $data['certificates'] = Certificate::all();
        return view('backend/certificate', $data);
    }

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

}
