<?php

namespace App\Http\Controllers;

use App\Handlers\ImageHandler;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class GiftController extends Controller
{

    public function show_gift()
    {
        $data = DB::table('gift')->get();
        $count=DB::table('gift')->count();
        $da=[];
        if ($data){
            foreach ($data as $k=>$v){
                $da[$k]=$v;
                unset($da['created_at']);
                unset($da['updated_at']);
                if ($v->status==1){
                    $data[$k]->status=true;
                }else{
                    $data[$k]->status=false;
                }
            }
        }
        return $this->success_list($da, 200, $count);
    }

    /*
     * 修改礼品
     */

    public function update_gift(Request $request, ImageHandler $imageHandler)
    {
        $data = $request->all();
        if ($request->has('img')) {
            // 保存图片到本地
            $result = $imageHandler->save($request->img, 'img', $request->id, 1024);
            // 图片保存成功的话
            if ($result) {
                $data['imgurl'] = $result['path'];
                unset($data['img']);
            }
        }
        unset($data['created_at']);
        unset($data['updated_at']);
        $re = DB::table('gift')->where('id', $request->id)->update($data);
        if ($re) {
            return $this->success([]);
        }
        return $this->error(400, [], false);
    }


    /*
     * 增加礼品
     */

    public function add_gift(Request $request, ImageHandler $imageHandler)
    {
        $id = Auth::user()->id;
        if ($file = $request->img) {
            // 保存图片到本地
            $result = $imageHandler->save($request->img, 'img', $id, 1024);
            // 图片保存成功的话
            if ($result) {
                $path = $result['path'];
            }
        } else {
            //上传图片失败
            return $this->error(300, [], false);
        }
        $s=DB::table('gift')->where('name',$request->name)->first();
        if ($s){
            return $this->error(600);
        }
        $data = $request->all();
        $data['imgurl'] = $path;
        unset($data['img']);
        $re = DB::table('gift')->insert($data);
        if ($re) {
            return $this->success([]);
        }
        //保存失败
        return $this->error(400, [], false);
    }

    /*
     * 删除礼品
     */
    public function del_gift(Request $request){
        $re=DB::table('gift')->where('id',$request->id)->delete();
        if ($re){
            return $this->success([]);
        }
        return $this->error(300);
    }

}