<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\Product;
use App\Exceptions\Handler;

class AdminFashionController extends Controller
{
    public function index(Request $request)
    {
        $items = Product::paginate(15);
        if($request->page==''){
            return redirect('admin-fashion?page='.$items->lastPage());
        }else{
            return view('admin.admin_fashion',compact('items'));
        }
    }
    
    public function show(Request $request)
    {
        //$item = Product::find($request->id);
        if($item = Product::find($request->id)){
            return response()->json([
                'error'=>false,
                'data'=>$item
            ]);
        }
    }

    public function store(Request $request)
    {
        if($request->hasFile('photo'))
        {
            $file = $request->file('photo');
            $fileName = $file->getClientOriginalName();

            $file->move('imgs/polosh',$fileName);

            $values = array(
                'name'=>$request->name,
                'img'=>$fileName
            );

            $insertedId = Product::insertGetId($values);
            $values['id'] = $insertedId;
            $values['img'] = $fileName;

            return response()->json([
                'error' => false,
                'data' => "",
            ]);
    
        }else{
            return response()->json([
                'error' => true,
                'message' => "Insert data gagal! Photo produk belum di siapkan.",
            ]);
        }
    }
    
    public function update(Request $request)
    {
        $fileName = '';
        $values = array(
            'id'=>$request->id,
            'name'=>$request->name,
        );

        if($request->hasFile('photo')){
            $file = $request->file('photo');
            $fileName = $file->getClientOriginalName();
            $file->move('imgs/polosh',$fileName);
            $values['img'] = $fileName;
        }else{
            $values['img'] = $request->image_file;
        }

        Product::where('id',$request->id)->update($values);

        return response()->json([
            'success' => true,
            'message' => 'Data Berhasil Diperbaharui',
            'data'    => $values
        ]);
    }
    
    public function destroy(Request $request){
        Product::where('id',$request->id)->delete();

        return response()->json([
            'success' => true,
            'message' => 'Hapus Data Berhasil',
            'data'    => $request->id
        ]);
    }
    
}

?>