<?php

namespace App\Http\Controllers;

use App\Exports\SeoRedirectExport;
use App\Http\Requests\ImportSeoDataRequest;
use App\Http\Requests\StoreSeoRedirectRequest;
use App\Imports\SeoRedirectImport;
use App\Jobs\VerifyRedirects;
use App\Models\BulkImportLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Mtc\MercuryDataModels\SeoData;
use Mtc\MercuryDataModels\SeoRedirect;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

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

    /**
     * List Seo Data entries
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function index(Request $request)
    {
        $data = SeoRedirect::query()
            ->when($request->input('filters') == 'verified', fn($query) => $query->where('verified', 1))
            ->when($request->input('filters') == 'failing', fn($query) => $query->where('verified', 0))
            ->when(
                $request->filled('search_term'),
                fn($query) => $query->where('from', 'like', "%" . $request->input('search_term') . "%")
            )
            ->paginate()
            ->toArray();

        $data['has_issues'] = SeoRedirect::query()
            ->whereNull('verified')
            ->orWhere('verified', 0)
            ->count();

        return $data;
    }

    /**
     * Store seo entry
     *
     * @param StoreSeoRedirectRequest $request
     * @param SeoRedirect $redirect
     * @return array
     */
    public function store(StoreSeoRedirectRequest $request, SeoRedirect $redirect)
    {
        $redirect->fill($request->input())->save();
        Cache::tags(tenant('id') . '-seo-redirects')->flush();
        return $redirect->toArray();
    }


    public function show(SeoRedirect $redirect)
    {
        return $redirect;
    }

    /**
     * Update seo entry
     *
     * @param StoreSeoRedirectRequest $request
     * @param SeoRedirect $redirect
     * @return array
     */
    public function update(StoreSeoRedirectRequest $request, SeoRedirect $redirect)
    {
        $redirect->update($request->input());
        Cache::tags(tenant('id') . '-seo-redirects')->flush();
        Cache::forget(tenant('id') . '-seo-redirects');
        return $redirect->toArray();
    }

    /**
     * Delete seo entry
     *
     * @param SeoData $seoData
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function destroy(Request $request, SeoRedirect $redirect)
    {
        $redirect->delete();
        Cache::tags(tenant('id') . '-seo-redirects')->flush();
        Cache::forget(tenant('id') . '-seo-redirects');
        return $this->index($request);
    }

    /**
     * Bulk delete seo entry
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function bulkDestroy(Request $request)
    {
        if ($request->has('ids')) {
            SeoRedirect::query()
                ->whereIn('id', $request->input('ids'))
                ->delete();
            Cache::tags(tenant('id') . '-seo-redirects')->flush();
            Cache::forget(tenant('id') . '-seo-redirects');

            return response()->json([
                'success' => true,
            ]);
        }

        return response()->json([
            'success' => false,
        ]);
    }

    public function verify(): Response
    {
        $this->dispatch(new VerifyRedirects());
        return \response('ok');
    }

    /**
     * Import seo data from file
     *
     * @param ImportSeoDataRequest $request
     * @return bool[]
     */
    public function import(ImportSeoDataRequest $request)
    {
        $tmpName = 'redirect-import-' . Carbon::now()->format('Y_m_d_H_i_s') . '.'
            . $request->file('file')->getClientOriginalExtension();
        $path_to_file = 'redirect-import/' . $tmpName;

        Storage::disk('file-storage')->put($path_to_file, $request->file('file')->getContent());
        BulkImportLog::query()
            ->create([
                'user_id' => Auth::id(),
                'object_type' => 'seo-redirects',
                'automations' => collect([
                    'remove-existing' => $request->input('truncate'),
                ])->filter(),
                'filename' => $path_to_file,
            ]);

        if ($request->input('truncate')) {
            SeoRedirect::query()->truncate();
        }

        Excel::import(new SeoRedirectImport(), $path_to_file, 'file-storage');
        Cache::tags(tenant('id') . '-seo-redirects')->flush();
        Cache::forget(tenant('id') . '-seo-redirects');
        return [
            'success' => true,
        ];
    }

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