<?php

namespace App\Http\Controllers\Admin\Pages\Pastblogs;

use App\Http\Controllers\Controller;
use App\Http\Requests\Pastblogs\PastblogStoreRequest;
use App\Http\Requests\Pastblogs\PastblogUpdateRequest;
use App\Models\Category;
use App\Models\Media;
use App\Models\MediaGallery;
use App\Models\Pastblog;
use App\Traits\Description;
use App\Traits\FileUploader;
use App\Traits\ImageCompressor;
use App\Traits\Slug;
use App\Traits\Title;
use DataTables;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\File;

class PastblogController extends Controller
{

    use ImageCompressor ,FileUploader,Slug ,Title,Description;

    public function __construct()
    {
        $this->middleware('permission:view pastblogs')->only('index', 'ajax');
        $this->middleware('permission:create pastblog')->only('create');
        $this->middleware('permission:store pastblog')->only('store');
        $this->middleware('permission:edit pastblog')->only('edit');
        $this->middleware('permission:update pastblog')->only('update');
        $this->middleware('permission:destroy pastblog')->only('destroy');
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $categories =Category::all();
      return view('app.admin.pages.pastblogs.all-pastblog',compact([
          'categories'
      ]));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $categories =Category::all();
        return view('app.admin.pages.pastblogs.create-pastblog',compact([
            'categories'
        ]));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(PastblogStoreRequest $request)
    {
        try {
            $validatedData = $request->validated();

            if ($request->hasFile('image')) {
                $validatedData['image'] = self::compressImage($request->file('image'), 'PastblogImage');
            }



            $category_id = $request->input('category_id');

            $validatedData['category_id'] = $category_id;

            $pastblog =Pastblog::create($validatedData);

            if ($request->hasFile('partners')) {
                foreach ($request->file('partners') as $image) {
                    MediaGallery::create([
                        'pastblog_id' => $pastblog->id,
                        'partners' => self::compressImage($image, 'PostBlogGallery')
                    ]);
                }
            }

            return back()->with('success', __('Data successfully created!'));
        } catch (\Exception $e) {
            return back()->withErrors([$e->getMessage()]);
        }
    }



    /**
     * Display the specified resource.
     */
    public function show(Pastblog $pastblog)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Pastblog $pastblog)
    {
        $pastblogs=Pastblog::all();
        $pastblogGalleries =MediaGallery::where('pastblog_id',$pastblog->id)->get();
        return view('app.admin.pages.pastblogs.edit-pastblog',compact([
            'pastblog',
            'pastblogs',
            'pastblogGalleries'
        ]));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(PastblogUpdateRequest $request, Pastblog $pastblog)
    {
        $validatedData = $request->safe();
        try {
            if ($request->hasFile('image')) {
                File::delete('/storage/images/' . $pastblog->getAttribute('image'));
                $validatedData['image'] = self::compressImage($request->file('image'), 'PastBlogImage');
            } else {
                $validatedData['image'] = $pastblog->getAttribute('image');
            }


            $pastblog->update($validatedData->except('partners'));

            if ($request->hasFile('partners')) {
                foreach ($request->file('partners') as $image) {
                    MediaGallery::create([
                        'blog_id' => $pastblog->id,
                        'partners' => self::compressImage($image, 'PastBlogImage')
                    ]);
                }
            }

            return back()->with('success', __('Data successfully updated!'));
        } catch (Exception $e) {
            return back()->withErrors([$e->getMessage()]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            $pastblog=Pastblog::find($id);
            $pastblog->delete();
            $pastblog->gallery()->delete();
            return back()->with('success', __('Data successfully deleted!'));
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * @return JsonResponse
     * @throws Exception
     */
    public function ajax()
    {
        $pastblogs = Pastblog::query();
        return DataTables::of($pastblogs)->editColumn('image', function (PastBlog $pastblogs) {
            return view('app.admin.includes.table-elements.image', [
                'image' => $pastblogs->image()
            ]);
        })->addColumn('options', function (Pastblog $pastblog) {
            return view('app.admin.includes.table-elements.action-buttons', [
                'modelName' => 'pastblog',
                'editUrl' => route('admin:pastblogs.edit', $pastblog->getAttribute('id')),
                'deleteUrl' => route('admin:pastblogs.destroy', $pastblog->getAttribute('id'))
            ]);
        })->toJson();
    }
}
