<?php

namespace App\Http\Controllers;

use App\Ranges;
use App\RangeConfiguration;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use phpDocumentor\Reflection\Types\Integer;

class RangesController extends Controller
{

    public function index()
    {
        $ranges = DB::table('ranges')->get();
        return view('Ranges.ranges', compact('ranges'));
    }


    #Display the form that creates a range

    public function create()
    {
        return view('Ranges.create');
    }

    #Store/save a range
    public function store(Request $request)
    {
        try {
            DB::beginTransaction();

            $this->validate($request, [
                'range-name' => 'required|min:3',
                'payroll-item' => 'required',
                'calculation-method' => 'required'
            ]);

            $id = DB::table('ranges')->insertGetId([
                'range_name' => $request['range-name'],
                'payroll_item' => $request['payroll-item'],
                'calculation_method' => $request['calculation-method'],
                'created_at' => DB::raw('NOW()'),
                'updated_at' => DB::raw('NOW()')
            ]);

            for ($i = 0; $i < sizeof($request['range-lower-limit']); $i++) {
                $range_data[] = array(
                    'range_id' => $id,
                    'lower_limit' => $request['range-lower-limit'][$i],
                    'upper_limit' => $request['range-upper-limit'][$i],
                    'rate' => $request['range-rate'][$i]
                );
            }

            DB::table('range_config')->insert($range_data);

            DB::commit();

            return redirect('/ranges');
        }catch(\Exception $e){
            DB::rollback();

            throw $e;
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Ranges  $ranges
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $results = DB::table('ranges')->where('id', $id)->first();
        $range_config = DB::table('range_config')
            ->where('range_id', $id)
            ->orderBy('lower_limit', 'asc')
            ->get();

        return view('Ranges.show', compact(['results', 'range_config']));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Ranges  $ranges
     * @return \Illuminate\Http\Response
     */
    public function edit($range_id)
    {
        #Get a range
        $range = DB::table('ranges')
            ->where('id', $range_id)
            ->first();

        #Get the range's data/configuration
        $range_config = DB::table('range_config')
            ->where('range_id', $range_id)
            ->orderBy('lower_limit', 'asc')
            ->get();

        return view('Ranges.edit', compact(['range', 'range_config']));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Integer  $range_id
     * @param  \Illuminate\Http\Request  $request
     * @return  \Illuminate\Http\Response
     * @throws \Exception $e
     */

    public function update($range_id, Request $request)
    {
        try {
            DB::beginTransaction();

            #Validate the range data
            $this->validate($request, [
                'range-name' => 'required|min:3',
                'payroll-item' => 'required',
                'calculation-method' => 'required'
            ]);

            #Update the range record
            DB::table('ranges')
                ->where('id', $range_id)
                ->update([
                'range_name' => $request['range-name'],
                'payroll_item' => $request['payroll-item'],
                'calculation_method' => $request['calculation-method'],
                'created_at' => DB::raw('NOW()'),
                'updated_at' => DB::raw('NOW()')
                ]);

            #Delete the existing range config
            DB::table('range_config')
                ->where('range_id', $range_id)
                ->delete();

            #Insert the new range config
            for ($i = 0; $i < sizeof($request['range-lower-limit']); $i++) {
                $range_data[] = array(
                    'range_id' => $range_id,
                    'lower_limit' => $request['range-lower-limit'][$i],
                    'upper_limit' => $request['range-upper-limit'][$i],
                    'rate' => $request['range-rate'][$i]
                );
            }

            DB::table('range_config')->insert($range_data);

            DB::commit();

            return $this->show($range_id);
        }catch(\Exception $e){
            DB::rollback();

            throw $e;
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     * @throws \Exception $e
     */
    public function destroy(Request $request)
    {
        try{
            #Remove the range entry
            DB::table('ranges')
                ->where('id', $request->rangeId)
                ->delete();

            #Remove the range configuration
            DB::table('range_config')
                ->where('range_id', $request->rangeId)
                ->delete();

            return response()->json(['status' => 1], 200);
        }catch(\Exception $e){
            #Roll back any changes that were made
            DB::rollback();

            throw $e;
        }
    }
}
