<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use \App\categories;
class CategoriesController extends Controller
{
    
    public function index()
    {
        $categories = categories::all(); // Select
        return view('admin.categories.list' , compact('categories')); // while query
    }


    public function create()
    {

        return view('admin.categories.create');
    }


    public function store()
    {


        $categories = categories::create($this->validateData()); // insert
        $this->storeImage($categories);
        return redirect('/admin/categories/create')->with("success","Created Successfully"); // send id of inserted

    }

    public function show(categories $categories)
    {
        //
    }


    public function edit(categories $categories)
    {

        return view('admin.categories.edit',compact('categories'));
    }


    public function update(Request $request, categories $categories)
    {


        $categories->update($this->validateData());
        $this->storeImage($categories);
        return redirect('/admin/categories/'. $categories->id . "/edit")->with('success', 'successfully updated');

    }


    public function destroy(categories $categories) {


        $categories->delete();
        return redirect('/admin/categories');
    }




    private function storeImage($categories) {


        if (request()->hasFile('img')) {
           // $image_path = $request->file('image')->store('products', 'public');


     $file = request()->file('img');
     $extension = $file->getClientOriginalExtension(); // you can also use file name
     $fileName = time().'.'.$extension;
     $image_path = public_path().'/storage/categories';
     $uplaod = $file->move($image_path,$fileName);

          $image_path = 'categories/'.$fileName;


        }


        if(request()->hasFile('img')) {
            $categories->update([


            'img'=>$image_path



            ]);
        }

    }



    protected function validateData() {


        $mydata =  [
            'title'=>'required' ,
        ];

        if(request()->hasFile('img')) {
            $mydata['img'] = 'file|image';
        }

        $validatedData = request()->validate($mydata);



        return $validatedData;


    }

}
