<?php

namespace App\Http\Controllers\Admin;

use App\Http\Resources\Home\ArticleCollection;
use App\Models\ArticleModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{
    //

    public function index(Request $request)
    {
        $articles = ArticleModel::when($request->filled('delete'), function ($query) {
            $query->where('deleted_at', 0);
        })->orderBy('id', 'desc')->paginate($request->get('per_page', 20));
        return new ArticleCollection($articles);
    }


    /**
     * 创建
     * @param  Request  $request
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|max:32',
            'tag' => 'required|max:8',
            'cover' => 'required|max:256',
            'link' => 'required|max:256',
            'showed_at' => 'required',
        ]);
        ArticleModel::create($request->all());
        return response([
            'code' => 200,
            'message' => 'OK'
        ]);
    }


    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'max:32',
            'tag' => 'max:8',
            'cover' => 'max:256',
            'link' => 'max:256',
            'showed_at' => '',
        ]);
        $article = ArticleModel::find($id);
        $article->update($request->all());
        return response([
            'code' => 200,
            'message' => 'OK'
        ]);
    }


    /**
     * 删除
     * @param  Request  $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(Request $request, $id)
    {
        $article = ArticleModel::find($id);
        $article->delete();
        return response([
            'code' => 200,
            'message' => 'OK'
        ]);
    }
}
