<?php

namespace App\Http\Controllers;

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\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class PortfolioProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param PortfolioProject $portfolioProject
     * @return Response
     */
    public function show(PortfolioProject $portfolioProject)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param PortfolioProject $portfolioProject
     * @return Response
     */
    public function edit(PortfolioProject $portfolioProject)
    {
        //
    }

    public function update(Request $request)
    {
        $portfolioProject = PortfolioProject::find($request->id);
        try {
            $transaction = DB::transaction(function () use ($request, $portfolioProject) {
                $portfolioProject->update($this->validatePortfolioProjectRequest($request, true));
                foreach ($portfolioProject->images()->get() as $image) {
                    if (!in_array($image->id, array_column($request->file('images')??[], 'id'))) {
                        $image->delete();
                    }
                }
                if (($request->file('images') != null) && (count($request->file('images')) > 0)) {
                    foreach ($request->file('images') as $item) {
                        PortfolioImage::create([
                            'portfolio_project_id' => $request->id,
                            'url' => FileUploader::store('portfolios/', $item),
                        ]);
                    }
                }
                $portfolioProject->skills()->sync($request->skills);
            });
            return is_null($transaction) ? back(303)->with(['success' => 'success']) : $transaction;
        } catch (Exception $exception) {
            dd($exception);
            return redirect()->back()->withErrors(['error' => $exception->getMessage()])->with(["error" => $exception->getMessage()]);
        }
    }

    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 $this->validate($request, [
            'title' => 'required',
            'description' => 'required',
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    public function destroy(Request $request)
    {
        $portfolioProject = PortfolioProject::find($request->id);
        $portfolioProject->delete();
        return back(303)->with(['success' => 'success']);
    }
}
