<?php

namespace Bongo\Builder\Http\Controllers\Api;

use Bongo\Framework\Http\Controllers\AbstractApiController;
use Bongo\Post\Models\Post;
use Bongo\Post\Models\PostCategory;
use Illuminate\Http\Request;
use Throwable;

class PostController extends AbstractApiController
{
    /**
     * @throws Throwable
     */
    public function index(Request $request)
    {
        $posts = $this->getPosts($request);
        $data = [
            'posts' => $posts,
            'style' => $request->get('style'),
            'columns' => $request->get('columns'),
            'padding' => $request->get('padding'),
            'lazy' => (bool) $request->get('lazy', false),
            'showSummary' => (bool) $request->get('summary', false),
            'showButton' => (bool) $request->get('button', false),
            'randomise' => (bool) $request->get('randomise', false),
            'characters' => $request->get('characters', 100),
        ];

        $style = make_key($request->get('style', 'style_1'));

        if (view()->exists("builder::frontend.posts.{$style}")) {
            return view("builder::frontend.posts.{$style}")
                ->with($data)
                ->render();
        }

        return view('builder::frontend.posts.style_1')
            ->with($data)
            ->render();
    }

    private function getPosts(Request $request)
    {
        $limit = $request->get('limit', 3);
        $randomise = $request->filled('randomise') && $request->get('randomise') === 'true';

        if (! $request->filled('ref')) {
            return Post::query()
                ->with('images')
                ->active()
                ->limit($limit)
                ->when($randomise, function ($query) {
                    return $query->inRandomOrder();
                })
                ->when(! $randomise, function ($query) {
                    return $query->orderBy('created_at', 'desc');
                })
                ->get();
        }

        $postCategory = PostCategory::query()
            ->whereUuid($request->get('ref'))
            ->firstOrFail();

        return $postCategory
            ->posts()
            ->with('images')
            ->active()
            ->limit($limit)
            ->when($randomise, function ($query) {
                return $query->inRandomOrder();
            })
            ->when(! $randomise, function ($query) {
                return $query->orderBy('created_at', 'desc');
            })
            ->get();
    }
}
