<?php

namespace App\Traits;

use App\Http\Helpers\FileUploader;
use App\Http\Helpers\UploadedFiles;
use App\Models\PortfolioImage;
use App\Models\PortfolioProject;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

trait HasPortfolios
{

    public function createPortfolio(Request $request)
    {
        try {
            $transaction = DB::transaction(function () use ($request) {
                $project = $this->portfolioProjects()->create($this->validatePortfolioProjectRequest($request, false));
                $project->skills()->attach($request->skills);
                foreach ($request->file('images') as $item) {
                    PortfolioImage::create([
                        'portfolio_project_id' => $project->id,
                        'url' => FileUploader::store('engineers/' . $this->slug . '/portfolio-projects/' . $project->id . '/', $item),
                    ]);
                }
            });

            return is_null($transaction) ? back(303)->with(['success' => 'success']) : $transaction;
        } catch (Exception $exception) {
            return back(303)->with(['error' => $exception->getMessage()]);
        }
    }

    public function portfolioProjects()
    {
        return $this->morphMany(PortfolioProject::class, 'portfolioable');
    }

    protected function validatePortfolioProjectRequest(Request $request, bool $update)
    {
        if (!$update) {
            $request->validate([
                'images' => 'required|array',
                'images.*' => UploadedFiles::getRules($update),
                'skills' => ['required', 'array'],
                'skills.*' => ['integer', Rule::exists('skills', 'id')],
            ]);
        }

        return $request->validate([
            'title' => 'required',
            'description' => 'required',
        ]);
    }
}
