<?php

namespace App\Http\Controllers;

use App\Exports\SeoHeadingExport;
use App\Http\Requests\ImportSeoDataRequest;
use App\Http\Requests\StoreSeoHeadingRequest;
use App\Http\Requests\UpdateSeoHeadingRequest;
use App\Imports\SeoHeadingImport;
use Maatwebsite\Excel\Facades\Excel;
use Mtc\MercuryDataModels\SeoData;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class SeoHeadingController extends Controller
{
    public function __construct()
    {
        $this->middleware([
            'permission:edit-seo',
        ]);
    }

    /**
     * List Seo Heading entries
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function index()
    {
        return SeoData::query()
            ->select(['id', 'path', 'heading'])
            ->whereNotNull('heading')
            ->paginate();
    }

    /**
     * Store seo heading entry
     *
     * @param StoreSeoHeadingRequest $request
     * @param SeoData $seoData
     * @return array
     */
    public function store(StoreSeoHeadingRequest $request, SeoData $data)
    {
        $data->fill($request->input())->save();
        return $data->toArray();
    }

    /**
     * Update seo entry
     *
     * @param UpdateSeoHeadingRequest $request
     * @param SeoData $seoData
     * @return array
     */
    public function update(UpdateSeoHeadingRequest $request, SeoData $heading)
    {
        $heading->update($request->input());
        return $heading->toArray();
    }

    /**
     * Delete seo entry
     *
     * @param SeoData $seoData
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function destroy(SeoData $heading)
    {
        $heading->update([
            'heading' => null
        ]);
        return $this->index();
    }

    /**
     * Import seo data from file
     *
     * @param ImportSeoDataRequest $request
     * @return bool[]
     */
    public function import(ImportSeoDataRequest $request)
    {
        if ($request->input('truncate')) {
            SeoData::query()->truncate();
        }

        Excel::import(new SeoHeadingImport(), $request->file('file'));
        return [
            'success' => true,
        ];
    }

    /**
     * Export seo data to excel file
     *
     * @return BinaryFileResponse
     */
    public function export()
    {
        return Excel::download(new SeoHeadingExport(), 'seo_headings.xlsx');
    }
}
