<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\BannerModel;

class BannerController extends Controller
{

    private $bannerModel;


    public function __construct()
    {
        $this->bannerModel = new BannerModel();
    }

    /**
     * 添加广告
     * @param  Request  $request
     * @return array
     */
    public function store(Request $request)
    {
        $banner = $this->bannerModel->create($request->all());
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => [
                'banner_id' => $banner->id
            ]
        ]);
    }

    /**
     * 更新广告
     * @param  Request  $request
     * @param  int  $banner_id
     * @return array
     */
    public function update(Request $request, int $banner_id)
    {
        $banner = $this->bannerModel->findOrFail($banner_id);
        $banner->fill($request->all());
        $banner->save();
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 删除广告
     * @param  int  $banner_id
     * @return array
     * @throws \Exception
     */
    public function delete(int $banner_id)
    {
        $banner = $this->bannerModel->findOrFail($banner_id);
        $banner->delete();
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 获取广告信息
     * @param  int  $banner_id
     * @return array
     */
    public function get(int $banner_id)
    {
        $banner = $this->bannerModel->findOrFail($banner_id);
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $banner
        ]);
    }

    /**
     * 获取某位置的广告
     * @param $position
     * @return array
     */
    public function listByPosition($position)
    {
        $banners = $this->bannerModel->where('position', $position)
            ->orderBy('sort', 'desc')
            ->get();
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $banners
        ]);
    }
}
