<?php

namespace App\Http\Controllers\admin;

use App\Models\Event;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Company\StorePostRequest;
use App\Http\Requests\Company\UpdatePostRequest;
use App\Http\Requests\Post\StorePostRequest as PostStorePostRequest;
use App\Http\Requests\Post\UpdatePostRequest as PostUpdatePostRequest;
use Exception;

class EventController extends Controller
{
    public function index(Request $request)
    {
        if($search = $request->search){
          $posts =  Event::where('title','LIKE',"%{$search}%")->paginate(config('aictcms.pageNumber'))->withQueryString();
        }else{
        $posts = Event::latest()->paginate(config('aictcms.pageNumber'))->withQueryString();
        }
        return view('Admin.events.index',compact('posts'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('Admin.events.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(PostStorePostRequest $request)
    {

          Event::create($request->requestHandler());
           return redirect()->route('events.index')->with('message',show_success());
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $post = Event::find($id);
        return view('Admin.events.show',compact('post'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Event::find($id);
        return view('Admin.events.edit',compact('post'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(PostUpdatePostRequest $request, $id)
    {
           $event = Event::findOrFail($id);
           $event->update($request->requestHandler());
            return redirect()->route('events.index')->with('message',
            show_success());


    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Event $event)
    {
        if($event->image){
           delete_file($event->image);
        }

        if($event->delete()){
            return redirect()->route('events.index')->with('message',show_success());
        }
    }


}