<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\EntriesCollection;
use App\Http\Resources\EventCollection;
use App\Models\GenericBackoffice\Entry;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Facades\Services\BackendUserService;
use App\Http\Requests\Api\BaseShow;
use App\Http\Controllers\Api\SearchController;
use App\Http\Resources\Entries as EntryResource;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

class EntryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(BaseShow $request)
    {
        // Retrieve the validated input data...
        $data = $request->validated();
        if ($data['slug'] === 'search' || $data['slug'] === 'searchQuery') {
            $searchParam = array_key_exists('sub_entity', $data) ? $data['sub_entity'] : '';
            $searchController = new SearchController;
            $results = $searchController->search($searchParam) ?? [];
            $currentPage = LengthAwarePaginator::resolveCurrentPage();
            $perPage = 7;
            $currentItems = array_slice($results, $perPage * ($currentPage - 1), $perPage);
            $items = new LengthAwarePaginator($currentItems, count($results), $perPage, $currentPage);
            return [
                'results' => $items,
                'searchParam' => $searchParam,
                'count' => count($results),
                'slug' => 'search',
            ];
        } else {
            $user = BackendUserService::getLoggedUser();
            $entryQuery = Entry::full()
                ->select('*')
                ->with([
                    'metaImage',
                    'blocks' => function ($query) use ($user) {
                        $query->full()
                            ->select('*')
                            ->orderBy('entry_block.position', 'asc');
                        if (!$user) {
                            $query->with('websites')->where('status', 'published');
                        }
                        $query->with([
                            'blockPageTabs' => function ($query) {
                                $query->full()->select('*')->orderBy('block_page_tab.position', 'asc')->with([
                                    'tabBlocks' => function ($query) {
                                        $query->full()->select('*')->orderBy('page_tab_block.position', 'asc')->with(
                                            $this->blockRelationQueries()
                                        );
                                    },
                                ]);
                            },
                        ])
                        ->with($this->blockRelationQueries())
                        ->withCount([
                            'blockFaq' => function ($query) {
                                $query->where('type', 'blockFaq');
                            }
                        ]);
                    },
                ]);
            if (!$user) {
                $entryQuery->with('websites')->where('status', 'published');
            };

            if ($data['sub_entity'] !== "") {
                $slug = '/'.$data['slug'].'/'.$data['sub_entity'];
                $entryQuery->where('lang_uri', $slug);
            } else {
                $entryQuery->where('lang_slug', $data['slug']);
            }

            $entry = $entryQuery->first();
            return new EntryResource($entry, true);
        }
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    private function blockRelationQueries()
    {
        return [
            'blockHeroWebLinks' => function ($query) {
                $query->orderBy('position');
            },
            'blockTabsContainer' => $this->loadBlocksRelations(),
            'blockTutorialsList' => function ($query) {
                $query->full()->select('*')->orderBy('block_normal_tab.position', 'asc');
            },
            'blockGeneralCards' => function ($query) {
                $query->full()->select('*')->orderBy('block_general_card.position', 'asc')->with([
                    'imageLinks' => function ($query) {
                        $query->full()->select('*')->orderBy('general_card_image_link.position', 'asc');
                    }
                ]);
            },
            'blockEvents' => function ($query) {
                $query->full()->select('*')->orderBy('block_event.position', 'asc');
            },
            'blockAddons' => function ($query) {
                $query->full()->select('*')->orderBy('addon_block.position', 'asc');
            },
            'blockSliderQuote' => function ($query) {
                $query->full()->select('*')->orderBy('block_quotes.position', 'asc');
            },
            'blockProducts' => function ($query) {
                $query->full()->select('*')->orderBy('block_highlight_product.position', 'asc');
            },
            'blockProjects' => function ($query) {
                $query->full()->select('*')->orderBy('block_project.position', 'asc');
            },
            'blockListBoxItems' => function ($query) {
                $query->full()->select('*')->orderBy('block_list_box_items.position', 'asc')->with([
                    'rows' => function ($query) {
                        $query->full()->select('*')->orderBy('list_box_item_row.position', 'asc');
                    }
                ]);
            },
        ];
    }

    private function loadBlocksRelations()
    {
        return function ($query) {
            $query->full()->select('*')->orderBy('block_tab.position', 'asc')->with([
                'tabItems' => function ($query) {
                    $query->full()->select('*')->orderBy('tab_tab_item.position', 'asc')->with([
                        'versions' => function ($query) {
                            $query->full()->select('*')->orderBy('single_version_tab_item.position', 'asc')->with([
                                'versionDownloads' => function ($query) {
                                    $query->full()->select('*')->orderBy('single_version_downloads.position', 'asc');
                                },
                            ]);
                        }
                    ]);
                },
            ]);
        };
    }
}
