<?php

namespace Modules\Seo\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Seo\Models\Faq;

class FaqController extends Controller
{
    public function find(Request $request)
    {
        $pageId = $request->has("page_id") ? $request->input("page_id") : 0;
        $pageSize = $request->has("page_size") ? $request->input("page_size") : 20;

        $query = Faq::query();
        if ($request->has('keyword')) {
            $keyword = $request->input("keyword");
            $query->where(function($query) use ($keyword) {
                $query->where("question", "like", "%" . $keyword . "%")
                    ->orWhere("answer", "like", "%" . $keyword . "%");
            });
        }
        $queryCount = clone $query;
        if ($pageSize > 0) {
            $query->offset($pageId);
            $query->limit($pageSize);
        }
        $items = $query->get();
        $count = DB::table(DB::raw("(" . $queryCount->toSql() . ") AS x"))
            ->mergeBindings($queryCount->getQuery())
            ->count();
        $pageCount = $this->recordsCountToPagesCount($count, $pageSize);
        $response = array(
            "status" => 'successful',
            'pagesCount' => $pageCount,
            'pageId' => $pageId,
            "items" => $items,
            "count" => $count,
        );
        return response()->json($response);
    }

    public function save(Request $request)
    {
        $data = $this->buildData($request);
        if ($request->has("id")) {
            $faq = Faq::where("id", $request->input("id"))->first();
        } else {
            $faq = new Faq();
        }
        $faq->fill($data);
        $faq->save();
        return response()->json(["status" => "successful"]);
    }

    private function buildData($request)
    {
        $data = [];
        $columns = ['question', 'answer', 'status'];
        foreach ($columns as $column) {
            if ($request->has($column)) {
                $data[$column] = $request->input($column);
            }
        }
        return $data;
    }

    public function delete(Request $request)
    {
        $retVal = [
            'status' => 'failed',
            'result' => []
        ];
        if ($request->has("id")) {
            $faq = Faq::where("id", $request->input("id"))->delete();
            if ($faq) {
                $retVal['status'] = 'successful';
            }
        }

        return response()->json($retVal);
    }
}