<?php

namespace App\Http\Controllers;

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

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

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

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

            $result['id']='';

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

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

        $request->validate([
            'title'=>'required',
            'image'=>$image_validation,
        ]);
        
        
        if ($request->post('id')>0) {
            $model=Planning::find($request->post('id'));
            $msg="Planning updated succesfuly";
        }else {
            $model=new Planning();
            $msg="Planning added succesfuly";
        }
        if ($request->hasfile('image')) {
            if ($request->post('id')>0) {
                $arrImage=DB::table('plannings')->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->title=$request->title;
        $model->descr=$request->descr;
        $model->short_descr=$request->short_descr;
        $model->save();
        if ($model->save()) {
            return redirect()->route('plannings')->with(['msg'=>$msg]);
        }else {
            return back()->with(['msg'=>'Something went wrong']);
        }
    }

    public function show(Planning $planning)
    {
        $data['plannings'] = Planning::all();
        return view('backend/planning', $data);
    }

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