<?php

namespace Bongo\Builder\Http\Controllers\Api;

use Bongo\Framework\Http\Controllers\AbstractApiController;
use Bongo\Project\Models\Project;
use Bongo\Project\Models\ProjectCategory;
use Illuminate\Http\Request;
use Throwable;

class ProjectController extends AbstractApiController
{
    /**
     * @throws Throwable
     */
    public function index(Request $request)
    {
        $projects = $this->getProjects($request);
        $data = [
            'projects' => $projects,
            '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.projects.{$style}")) {
            return view("builder::frontend.projects.{$style}")
                ->with($data)
                ->render();
        }

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

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

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

        $projectCategory = ProjectCategory::query()
            ->whereUuid($request->get('ref'))
            ->firstOrFail();

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