<?php

namespace App\Http\Controllers\Web;

use App\Helpers\ImageHelper;
use App\Http\Controllers\Controller;
use App\WebsitePhoto;
use App\WebsiteCategory;
use App\WebsiteCategoryDescription;
use Illuminate\Http\Request;
use \Illuminate\Support\Str;
use Illuminate\View\View;

class WebsiteController extends Controller
{
    private $viewDirectory = 'web.websites.';
     /**
     * Show the Websites of category.
     * @param WebsiteCategory $category
     * @param Request $request
     * @return View
     */
    public function index(WebsiteCategory $category, Request $request): View
    {
        $categoryDescription= $category->currentDescription;
        // Check Slug is the same
        if ($request->slug && $request->slug != str_slug($categoryDescription->slug)) {
            abort(404);
        }
        //
        $websites= WebsitePhoto::orderby('id', 'DESC')
            ->where('website_category_id', $category->id)
            ->paginate(30);

        $title= $categoryDescription->name ;
        $keywords= $categoryDescription->keywords ;
        $meta_description= $categoryDescription->meta_description ;

        return view($this->viewDirectory.'index', compact( 'websites', 'title', 'keywords', 'meta_description'));
    }

   
    /**
     * Show the Websites of category.
     * @return View
     */
    public function categories(): View
    {
        $query= WebsiteCategory::latest()->with(['currentDescription'])->get();

        $categories= [];

        if ($query) {
            $categories= $query->toArray();
        }

        foreach ($query as $key => $category) {
            $query= WebsitePhoto::orderby('id', 'DESC')
            ->where('website_category_id', $category->id)
            ->select(['image'])->limit(1)->first();

            $website=['image'=>''];
            if ($query) {
                $website= $query->toArray();
            }
            $categories[$key]['image']= ImageHelper::get($website['image']);
            $categories[$key]['url']= $category->url;
        }
        return view($this->viewDirectory.'categories', compact( 'categories' ));
    }
}
