<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Resps\Interfaces\Administrator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;

class AdministratorController extends Controller
{
    protected $administrator;

    public function __construct(Administrator $administrator)
    {
        $this->administrator = $administrator;
    }

    public function login()
    {
        $username = trim(request()->get('username'));
        $password = trim(request()->get('password'));
        if (!$username || !$password) {
            return redirect('/login');
        }
        $validate = $this->administrator->login(['username' => $username, 'password' => $password]);
        if ($validate['code'] || !Auth::check()) {
            return redirect('/login');
        }
        return redirect('/news/news');
    }

    public function logout()
    {
        return redirect($this->administrator->logout() ? '/login' : '/admin');
    }

    public function index()
    {
        $fillables = [
            'page',
            'username',
            'status',
            'is_ajax'
        ];
        $params = request()->only($fillables);

        return $params['is_ajax'] ? $this->administrator->index($params) : view('admin.user_index');
    }

    public function userForm($id = "")
    {

        return view('admin.user_form', $id ? ['id' => $id] : []);
    }

    public function show($id)
    {
        return Response::auto($this->administrator->show($id));
    }


    public function store()
    {
        $fillable = ['username', 'password', 'status', 'avatar', 'role_ids'];

        return Response::auto($this->administrator->create(request()->only($fillable)));
    }

    public function destroy($id)
    {
        return Response::auto($this->administrator->destroy($id));
    }
}
