<?php

namespace App\Http\Controllers;

use App\Models\Type;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Validator;
use Log;
use RealRashid\SweetAlert\Facades\Alert;

class TypeController extends Controller
{

    public function index(Request $request)
    {

        $page = $request->page;

        if(isset($page) && is_numeric($page) && $page>0) {

            $records_to_show = 25;
            $records_to_skip = ($page - 1) * $records_to_show;

            $query = Type::query();

            $all_records_count = $query->count();

            $num_of_pages = (int) ceil($all_records_count / $records_to_show);
            
            $types = $query->skip($records_to_skip)
            ->take($records_to_show)
            ->get();

            return view('types.index', compact('types','num_of_pages', 'page'));

            
        } else {
            return redirect()->route('types.index', ['page'=>1]);
        }

    }

    public function create() {

        if(session()->has('success')) {
            Alert::success('success', session()->get('success'));
        }

        if(session()->has('error')) {
            Alert::error('error', session()->get('error'));
        }

        return view('types.form');
    }

    public function store(Request $request) {
        $insert = 0;
        $error = '';

        try {

            $this->requestValidations();

            $inputs = $request->all();

            // Store
            $insert = Type::create($inputs);

        } catch (ValidationException $e) {
            return redirect()->back()->withErrors($e->errors())->withInput();

        } catch (\Exception $e) {
            $error = $e->getMessage();
        }

        if($insert) {
            session()->flash('success' , 'Record Created Successfully !');
        } else {
            Log::error($error);
            session()->flash('error' , 'Something went wrong.');
        }
       
        return redirect()->back();
    }

    public function show($id) {
        
        if(session()->has('success')) {
            Alert::success('success', session()->get('success'));
        }

        if(session()->has('error')) {
            Alert::error('error', session()->get('error'));
        }

        $type = Type::findOrFail($id);

        return view('types.form', compact('type'));
    }

    public function update(Request $request, Type $type, $id)
    {

        $status = 0;
        $error = '';

        try {

            $this->requestValidations($id);
            $type = Type::findOrFail($id);

            $inputs = $request->all();

            $type->fill($inputs);

            if($type->save()) {
                $status = 1;
            }
            
        } catch (ValidationException $e) {
            return redirect()->back()->withErrors($e->errors())->withInput();

        } catch (\Exception $e) {
            $error = $e->getMessage();
        }

        if($status) {
            session()->flash('success' , 'Record Updated Successfully !');
        } else {
            Log::error($error);
            session()->flash('error' , 'Something went wrong.');
        }
       
        return redirect()->back();
        
    }

    public function destroy(Request $request)
    {
        $status = 0;
        $message = 'Something went wrong !';

        $delete = Type::where('id', $request->record_id)->delete();

        if($delete) {

            $status = 1;
            $message = "Record Deleted Successfully !";
        }

        return response()->json([
            'status'=>$status,
            'message'=>$message
        ]);
    }

    public function requestValidations($record_id = null) {

        $slugUniqueRule = Rule::unique('types', 'slug')->ignore($record_id);

        return request()->validate([
            'name' => ['required', 'string', 'max:128'],
        ]);
    }
    

}
