<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class DeductionsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $deductions = DB::table('deduction_config')->get();
        $list_items = DB::table('list_items')->get();

        return view('Deductions.deductions', compact(['deductions', 'list_items']));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        #Retrieve all the types of range allowed for this deduction
        $ranges = DB::table('ranges')->where('payroll_item', 2)->get();

        #Retrieve list items for the select boxes
        $list_items = DB::table('list_items')->get();

        return view('Deductions.create', compact(['ranges', 'list_items']));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'deduction-name' => 'required|min:3|max:30',
            'deduction-type' => 'required',
            'tabulation-type' => 'required',
            'tax-option' => 'required'
        ]);

        if ($request['tabulation-type'] === '3'){
            $this->validate($request, [
                'range' => 'required'
            ]);
        }

        DB::table('deduction_config')
            ->insertGetId([
                'deduction_name' => $request['deduction-name'],
                'deduction_type' => $request['deduction-type'],
                'tabulation_type' => $request['tabulation-type'],
                'tax_option' => $request['tax-option'],
                'range' => $request['range'],
                'created_by' => 1,
                'created_at' => DB::raw('NOW()'),
            ]);

        return redirect('/deductions');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $deduction = DB::table('deduction_config')->where('id', $id)->first();
        $id = $deduction->id;

        $groups_in_deduction = DB::table('payroll_item_groups')
            ->where([
                ['payroll_item_id', $id],
                ['payroll_item', 'deduction']
            ])
            ->get();

        #Get the details of the employees in the group(s)
        $employee_groups= [];
        foreach($groups_in_deduction as $group){
            $users = $group->employees;
            $users = explode(',', $users);

            $count = 0;
            foreach($users as $user){
                $employee_details = DB::table('main_users')
                    ->where('id', $user)
                    ->first();

                $employee_groups[$group->id][$count] = strtoupper($employee_details->last_name)." ".$employee_details->first_name;
                $count++;
            }
        }

        return view('Deductions.show', compact(['deduction', 'groups_in_deduction', 'employee_groups']));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $deduction = DB::table('deduction_config')->where('id', $id)->first();
        $list_items = DB::table('list_items')->get();
        $ranges = DB::table('ranges')->get();

        return view('Deductions.edit', compact(['deduction', 'list_items', 'ranges']));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'deduction-name' => 'required|min:3|max:30',
            'deduction-type' => 'required',
            'tabulation-type' => 'required',
            'tax-option' => 'required'
        ]);

        if ($request['tabulation-type'] === '3'){
            $this->validate($request, [
                'range' => 'required'
            ]);
        }

        DB::table('deduction_config')
            ->where('id', $id)
            ->update([
                'deduction_name' => $request['deduction-name'],
                'deduction_type' => $request['deduction-type'],
                'tabulation_type' => $request['tabulation-type'],
                'tax_option' => $request['tax-option'],
                'range' => $request['range'],
            ]);

        return redirect('/deductions')->with('messages', ['success', 'Deduction has been updated.']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        if ($request->ajax()){
            DB::table('deduction_config')->where('id', $request->deductionId)->delete();

            return response()->json(array('status' => 1));
        }else{
            return response()->json(array('status' => 0));
        }
    }

    /**
     * Add groups to a deduction
     */

    public function add_employees($id){
        $departments = DB::table('departments')->get();
        return view('Deductions.employees', compact(['departments']));
    }

    /**
     * @return \Illuminate\Http\Response
     * Edit a group of employees in a deduction
     */

    public function edit_group($id){
        $departments = DB::table('departments')->get();

        #Get the group details
        $group = DB::table('payroll_item_groups')
            ->where('id', $id)
            ->first();

        #Get the employees in the group
        $employees = $group->employees;
        $employees = explode(',', $employees);

        for ($i=0;$i<count($employees);$i++){
            $employee_details = DB::table('main_users')
                ->where('id', $employees[$i])
                ->first();

            $employee_names[] = ['id' => $employee_details->id,
                'name' => strtoupper($employee_details->last_name)." ".$employee_details->first_name];
        }

        return view('Deductions.edit_group', compact(['departments', 'group', 'employee_names']));
    }

    /**
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     * Add a group of employees to a deduction
     */

    public function delete_group(Request $request){
        $deleteRequest = DB::table('payroll_item_groups')
            ->where('id', $request->groupId)
            ->delete();

        if ($deleteRequest){
            $status = 1;
        }else{
            $status = 0;
        }

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