<?php

namespace Botble\Portfolio\Http\Controllers;

use Botble\Base\Events\BeforeEditContentEvent;
use Botble\Base\Events\CreatedContentEvent;
use Botble\Base\Events\DeletedContentEvent;
use Botble\Base\Events\UpdatedContentEvent;
use Botble\Base\Facades\PageTitle;
use Botble\Base\Forms\FormBuilder;
use Botble\Base\Http\Controllers\BaseController;
use Botble\Base\Http\Responses\BaseHttpResponse;
use Botble\Portfolio\Forms\ProjectForm;
use Botble\Portfolio\Http\Requests\ProjectRequest;
use Botble\Portfolio\Models\Project;
use Botble\Portfolio\Tables\ProjectTable;
use Illuminate\Http\Request;

class ProjectController extends BaseController
{
    public function __construct(protected BaseHttpResponse $response)
    {
    }

    public function index(ProjectTable $dataTable)
    {
        PageTitle::setTitle(trans('plugins/portfolio::portfolio.project.name'));

        return $dataTable->renderTable();
    }

    public function create(FormBuilder $formBuilder)
    {
        PageTitle::setTitle(trans('plugins/portfolio::portfolio.project.create'));

        return $formBuilder->create(ProjectForm::class)->renderForm();
    }

    public function edit(Project $project, Request $request, FormBuilder $formBuilder): string
    {
        event(new BeforeEditContentEvent($request, $project));

        PageTitle::setTitle(trans('core/base::forms.edit_item', ['name' => $project->name]));

        return $formBuilder->create(ProjectForm::class, ['model' => $project])->renderForm();
    }

    public function store(ProjectRequest $request): BaseHttpResponse
    {
        $project = Project::query()->create($request->validated());

        event(new CreatedContentEvent('projects', $request, $project));

        return $this->response
            ->setNextUrl(route('portfolio.projects.edit', $project))
            ->setMessage(trans('core/base::notices.create_success_message'));
    }

    public function update(Project $project, ProjectRequest $request): BaseHttpResponse
    {
        $project->update($request->validated());

        event(new UpdatedContentEvent('services', $request, $project));

        return $this->response
            ->setPreviousUrl(route('portfolio.projects.index'))
            ->setNextUrl(route('portfolio.projects.edit', $project))
            ->setMessage(trans('core/base::notices.update_success_message'));
    }

    public function destroy(Project $project, Request $request): BaseHttpResponse
    {
        $project->delete();

        event(new DeletedContentEvent('services', $request, $project));

        return $this->response->setMessage(trans('core/base::notices.delete_success_message'));
    }
}
