<?php

namespace App\Http\Controllers\Admin;

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

class FormDataController extends Controller
{
    protected $redirect_index = '/admin/FormData/index';

    protected $view_path = 'admin.form-data.';

    protected $pre_uri = '/admin/FormData/';

    protected $model_name = '表单数据';

    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new FormData();
    }

    public function index(Request $request)
    {
        $list = $this->model->where('id', '>', 0)->orderBy('created_at', 'desc');

        if(!empty($request->input('keyword')) && !empty(trim($request->input('keyword')))) {
            $keyword = '%' . trim($request->input('keyword')) . '%';
            $list = $list->where('name', 'like', $keyword);
        }

        $list = $list->paginate()->withPath($this->getPaginateUrl());

        list($pre_uri, $model_name) = array($this->pre_uri, $this->model_name);
        return view($this->view_path . 'index', compact('list', 'pre_uri', 'model_name'));
    }

    public function show(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) {
            return $this->showWarning('参数错误');
        }
        $item->status = 2;
        $item->save();
        list($pre_uri, $model_name) = array($this->pre_uri, $this->model_name);
        return view($this->view_path . 'show', compact('list', 'pre_uri', 'model_name', 'item'));
    }

    public function delete(Request $request)
    {
        if(!$request->isMethod('POST')) {
            return $this->showWarning('访问错误');
        }
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) {
            return $this->showWarning('访问错误');
        }

        $res = $item->delete();
        if(!$res) {
            return $this->showWarning('数据库删除失败');
        }
        return $this->showMessage('操作成功');
    }
}
