<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;
use App\Models\VideoInterviewCategories;
use App\Models\VideoInterviewCategoriesVideos;
use Illuminate\Http\Request;

class VideoInterviewCategoriesController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        define('PAGE_LIMIT', 30);
    }

    public function index(Request $request)
    {
        if ($request->isMethod('post')) {
            $requestData = $request->all();

            VideoInterviewCategories::destroy($requestData['id']);

            VideoInterviewCategoriesVideos::where('category_id', $requestData['id'])->delete();

            return redirect()->route('admin.videos.categories')->with('flash_message', 'Category deleted successfully!');
        } else {
            $records = VideoInterviewCategories::orderBy('sort_no', 'asc')
                ->paginate(PAGE_LIMIT);
        }
        $data = array();
        $data['active_menu'] = 'categories';
        $data['sub_active_menu'] = 'categories-list';
        $data['title'] = 'Categories';
        $data['records'] = $records;
        return view('backend.categories.list', $data);
    }

    public function addNewCategories(Request $request, $id = null)
    {

        if ($request->isMethod('post')) {

            $requestData = $request->all();


            $this->validate(request(), [
                'name' => 'required'
            ], [

                'name.required' => 'Enter title'
            ]);


            if ($requestData['id'] == '') {


                VideoInterviewCategories::create($requestData);

                $mes = 'Category added successfully!';
            } else {

                $record = VideoInterviewCategories::findOrFail($requestData['id']);
                $record->update($requestData);
                $mes = 'Category updated successfully!';
            }
            return redirect()->route('admin.videos.categories')->with('flash_message', $mes);

        } else {
            $data = array();
            $data['id'] = '';
            $data['record'] = '';
            if ($id) {
                $data['id'] = $id;
                $data['record'] = VideoInterviewCategories::findOrFail($id);
            }
            $data['active_menu'] = 'categories';
            $data['sub_active_menu'] = 'manage-categories';
            $data['title'] = 'Manage categories';
            return view('backend.categories.add', $data);
        }
    }
}
