<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ProductCollection;
use App\Models\Product;

class ProductCollectionController extends Controller
{

    /**
     * 添加收藏
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $id = $request->input('id');
        //$user = session('wechat.oauth_user.default');
        //$wechat_id = $user->getId();
        $wechat_id = $request->input("openid");
        if ($id && $wechat_id) {
            $product = Product::find($id);
            if ($product->collect_num == null) {
                $product->collect_num = 1;
            } else {
                $product->collect_num = $product->collect_num + 1;
            }
            $product . save();
            // 获取微信id
            $wechat_id = "";
            $productCollection = new ProductCollection;
            $productCollection->wechat_id = $wechat_id;
            $productCollection->product_id = $id;
            $productCollection->save();

            return Response()->json([
                "status" => 0,
                "message" => "保存成功!"
            ]);
        } else {
            return Response()->json([
                "status" => -1,
                "message" => "id不能为空!"
            ]);
        }
    }

    /**
     * 删除收藏夹
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        $product_id = $request->input('product_id');
        //$user = session('wechat.oauth_user.default');
        //$wechat_id = $user->getId();
        $wechat_id = $request->header("openid");
        if(!$wechat_id) {
            $wechat_id = $request->input("openid");
        }
        if ($product_id) {
            $product = Product::find($product_id);
            $product->collect_num = $product->collect_num - 1;
            $product->save();
            $productCollection = ProductCollection::where("product_id", $product_id)
                ->where("wechat_id", $wechat_id)->first();
            $productCollection->delete();
            return Response()->json([
                "status" => 0,
                "message" => "删除成功!"
            ]);
        } else {
            return Response()->json([
                "status" => -1,
                "message" => "id不能为空!"
            ]);
        }
    }

}
