<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Repositories\GalleryRepositoryEloquent;
use App\Repositories\RecoveryGalleryRepository;
use Illuminate\Http\Request;

class GalleryController extends Controller
{
    protected $recoveryRepo;
    public function __construct(GalleryRepositoryEloquent $recoveryRepository)
    {
        $this->recoveryRepo = $recoveryRepository;
    }


    public function index()
    {

        return $this->recoveryRepo->indexPage();
    }

    public function createPage()
    {
        return $this->recoveryRepo->createPage();

    }

    public function edit($id)
    {
        return $this->recoveryRepo->editPage($id);

    }

    public function store(Request $request)
    {
        $request->validate([
            'gallery_image' => 'required|image'
        ]);
        try {
            $recovery = $this->recoveryRepo->create($request->all());
            if ($request->hasFile('gallery_image')) {
                $recovery->addMediaFromRequest('gallery_image')->toMediaCollection('gallery_image');
            }
            return redirect()->route('admin.recovery.list')->with('success', 'Gallery Successfully Added');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }

    }

    public function update(Request $request, $id)
    {
        try {
            $update = $this->recoveryRepo->update($request->all(), $id);
            if ($request->hasFile('gallery_image')) {
                $update->clearMediaCollection('gallery_image');
                $update->addMediaFromRequest('gallery_image')->toMediaCollection('gallery_image');
            }
            return redirect()->route('admin.recovery.list')->with('success', 'Gallery Successfully Updated');
        } catch (\Exception $e) {

            return redirect()->back()->with('error', $e->getMessage());

        }

    }

    public function delete(Request $request)
    {
        $this->recoveryRepo->delete($request->id);
        return response()->json(['success' => 'Record successfully deleted!']);
    }
}
