<?php

namespace App\Daylight\Http\Controllers\Content;

use App\Daylight\Http\Requests\Content\Testimonials\StoreTestimonialRequest;
use App\Daylight\Http\Requests\Content\Testimonials\UpdateTestimonialRequest;
use App\Http\Controllers\Controller;
use App\Models\Testimonial;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class TestimonialController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:create:pages', only: ['create', 'store']),
            new Middleware('can:read:pages', only: ['index', 'show']),
            new Middleware('can:update:pages', only: ['edit', 'update']),
            new Middleware('can:delete:pages', only: ['destroy']),
        ];
    }

    public function index()
    {
        return view('daylight.content.testimonials.index');

    }

    public function create()
    {
        return view('daylight.content.testimonials.create');
    }

    public function store(StoreTestimonialRequest $request)
    {
        $testimonial = Testimonial::create($request->only('name', 'company', 'location', 'rating'));

        $testimonial->translations()->create([
            'locale' => $request->input('locale'),
            'title' => $request->input('title'),
            'content' => $request->input('content'),
        ]);

        return redirect()
            ->route('daylight.content.testimonials.edit', [
                'testimonial' => $testimonial,
                'locale' => $request->get('locale'),
            ])
            ->with('success', __('Testimonial created'));
    }

    public function edit(Testimonial $testimonial)
    {
        $testimonial->load([
            'translations' => function ($query) {
                $query->where('locale', request()->get('locale', app()->getLocale()));
            },
        ]);

        return view('daylight.content.testimonials.edit', [
            'testimonial' => $testimonial,
        ]);
    }

    public function update(UpdateTestimonialRequest $request, Testimonial $testimonial)
    {
        $testimonial->update($request->only('name', 'company', 'location', 'rating'));

        $testimonial->translations()->updateOrCreate(
            ['locale' => $request->input('locale')],
            $request->only('title', 'content')
        );

        return redirect()
            ->route('daylight.content.testimonials.edit', [
                'testimonial' => $testimonial,
                'locale' => $request->get('locale'),
            ])
            ->with('success', __('Testimonial updated'));
    }

    public function destroy(Testimonial $testimonial)
    {
        $testimonial->delete();

        return redirect()->route('daylight.content.testimonials.index')
            ->with('success', __('Testimonial deleted'));
    }
}
