<?php
/**
 * Created by PhpStorm.
 * User: zilongs
 * Date: 20-10-24
 * Time: 上午11:14
 */

namespace App\Http\Controllers\Api\V1;

use App\Models\Coupon;
use App\Models\UserCoupon;

class CouponController extends AuthController
{
    public function couponList()
    {
        $data = Coupon::orderBy('id', 'desc')->paginate();

        return out($data);
    }

    public function receiveCoupon()
    {
        $req = request()->post();
        $this->validate(request(), [
            'coupon_id' => 'required|integer'
        ]);
        $user = $this->user;

        if (UserCoupon::where('user_id', $user['id'])->where('coupon_id', $req['coupon_id'])->exists()) {
            return out(null, 10001, '您已经领取过该优惠券了');
        }

        $add = Coupon::select(['id as coupon_id', 'name', 'title', 'desc', 'rules', 'icon', 'type', 'usable_type', 'money', 'discount', 'min_consume_amount', 'max_reduce_amount', 'expire_type', 'effective_days', 'start_time', 'end_time'])->where('id', $req['coupon_id'])->first()->getOriginal();
        $add['user_id'] = $user['id'];
        $expire_time = $add['end_time'];
        if ($add['expire_type'] == 1) {
            $expire_time = time() + $add['effective_days']*24*3600;
        }
        $add['expire_time'] = $expire_time;
        UserCoupon::create($add);

        return out();
    }

    public function userCouponList()
    {
        $user = $this->user;

        $data = UserCoupon::with('couponType')->where('user_id', $user['id'])->where('status', 1)->where('expire_time', '>', time())->orderBy('id', 'desc')->paginate();

        return out($data);
    }
}
