<?php

namespace App\Http\Controllers\Admin;

use App\Models\News;
use App\Models\CollectMedia;
use App\Models\NewsDescription;
use App\Models\CollectTitle;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CollectNewsController extends AdminController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = $request->except('page');

        $cids = CollectTitle::lists('cid')->toArray();

        $query = News::with(['cates', 'description'])->whereIn('pid', array_unique($cids));

        if ($title = $request->input('title')) {
            $ids   = NewsDescription::where('title', 'like', "%{$title}%")->where('lang', config('setting.lang'))->get()->pluck('news_id')->toArray();
            $query->whereIn('id', $ids);
        }

        if ($flag = $request->input('flag')) {
            $query->where('flag', $flag == 1 ? 1 : 0);
        }

        $data = $query->latest()->paginate($request->input('perPage', 20));

        return view('admin.collect_news.index', compact('data', 'where'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data  = News::find($id);
        $tags  = News::tagCount();
        $descriptions = NewsDescription::where('news_id', $id)->get()->groupBy('lang');

        if (!isset($descriptions[config('managerLang')])) $descriptions[config('managerLang')] = $descriptions[config('setting.lang')];

        return view('admin.collect_news.edit', compact('data', 'tags', 'descriptions'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->all();
        $news = News::find($id);
        if ($news->flag == 0 && $data['flag'] == 1) {
            $data['created_at'] = Carbon::now();
        }

        if (is_null($news->img_path)) {
            $media = CollectMedia::orderBy(DB::raw('RAND()'))->take(1)->first();
            if ($media) {
                $data['img_path'] = $media->path;
            }
        }

        $result  = $news->update($data);
        $news->retag($request->tags);
        NewsDescription::attachDescription($request->input('description'), $id, 'news_id');
        News::attachSlug($news, config('managerLang') == config('setting.lang') ? $request->input('description.' . config('setting.lang') . '.title') : NewsDescription::where('news_id', $id)->where('lang', config('setting.lang'))->value('title'));

        if ($result) {
            return redirect($request->input('referer') ?: 'admin/collect-news')->with('success', '新闻修改成功');
        }

        return back()->withInput()->with('error', '新闻修改失败');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $result = News::deletes($id, 'news_id');

        return response()->json(['status' => $result ? 'success' : 'error']);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function updateFlag(Request $request)
    {
        $ids = array_str($request->input('ids'));

        $result = News::whereIn('id', $ids)->update(['flag' => 1, 'created_at' => Carbon::now()]);

        return response()->json(['status' => $result ? 'success' : 'error']);
    }
}
