<?php
/**
 * Created by PhpStorm.
 * User: Gold
 * Date: 2024/1/24
 * Time: 8:41
 */

namespace app\api\controller;

use app\admin\model\books\Books; //教材
use app\admin\model\books\Certificate as CertificateModel;
use app\common\controller\Api;

class Certificate extends Api
{
    protected $noNeedRight = [];

    /**
     *  我的体验卡
     *
     */
    public function getMyCertificate(){
        $data = input();
        if(!isset($data['page']) || $data['page'] == '' || $data['page'] == null){
            $page = 1;
        }else{
            $page = $data['page'];
        }
        if(!isset($data['limit']) || $data['limit'] == '' || $data['limit'] == null){
            $limit = 20;
        }else{
            $limit = $data['limit'];
        }
        $where = [];
        if(isset($data['is_expire']) && $data['is_expire'] !== '' && $data['is_expire'] !== null){
            $where['is_expire'] = $data['is_expire'];
        }

        $uid = $this->auth->id;
        $CertificateModel = new CertificateModel();
        $list = $CertificateModel->where($where)->with(['goods'=>function($query){
            $query->field('id,title,image');
        }])->where('user_id',$uid)->paginate([
            'list_rows'=> $limit,
            'page' => $page,
        ]);
        $this->success('操作成功',$list);
    }

    /**
     *  使用体验卡
     *
     */
    public function useCertificate(){
        $data = input();
        $uid = $this->auth->id;
        $date = date('Y-m-d H:i:s');
        $date_end = date("Y-m-d H:i:s", strtotime("3 day"));
        $CertificateModel = new CertificateModel();
        $find = $CertificateModel->where('user_id',$uid)->where('id',$data['id'])->where('is_deleted',1)->find();
        if(!$find){
            $this->error('体验卡不存在');
        }
        if($find['effective_time'] < $date){
            $this->error('体验卡已过期');
        }
        if($find['status'] == 1){
            $this->error('该体验卡已使用');
        }
        $arr = [
            'free_start_time' => $date,
            'free_end_time' => $date_end,
            'status' => 1
        ];
        if($CertificateModel->where('id',$data['id'])->update($arr)){
            $this->success('操作成功');
        }
    }
}
