<?php

namespace App\Http\Controllers;

use App\Ranges;
use App\Allowance;
use App\ListItems;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class AllowancesController extends Controller
{

    public function index(){
        $allowances = DB::table('allowance_config')->get();
        $list_items = DB::table('list_items')->get();

        return view('Allowances.allowances', compact(['allowances', 'list_items']));
    }

    public function create()
    {
        #Retrieve all the types of range allowed for this allowance
        $ranges = DB::table('ranges')->where('payroll_item', 1)->get();
        #Retrieve list items for the select boxes
        $list_items = DB::table('list_items')->get();

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


    public function store(Request $request)
    {
        $this->validate($request, [
            'income-name' => 'required|min:3|max:30',
            'income-type' => 'required',
            'tabulation-type' => 'required',
            'tax-option' => 'required'
        ]);

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

        DB::table('allowance_config')
            ->insertGetId([
                'income_name' => $request['income-name'],
                'income_type' => $request['income-type'],
                'tabulation_type' => $request['tabulation-type'],
                'tax_option' => $request['tax-option'],
                'range' => $request['range'],
            ]);

        return redirect('/allowances');
    }

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

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

        #Get the details of the employees in the group(s)
        $employee_groups= [];
        foreach($groups_in_allowance as $group){
            #$employee_names[$group->id];

            $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('Allowances.show', compact(['allowance', 'groups_in_allowance', 'employee_groups']));
    }

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

        return view('Allowances.edit', compact(['allowance', 'list_items', 'ranges']));
    }

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

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

        DB::table('allowance_config')
            ->where('id', $id)
            ->update([
                'income_name' => $request['income-name'],
                'income_type' => $request['income-type'],
                'tabulation_type' => $request['tabulation-type'],
                'tax_option' => $request['tax-option'],
                'range' => $request['range'],
            ]);

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Allowance  $allowance
     * @return \Illuminate\Http\Response
     */

    public function destroy(Request $request)
    {
        if ($request->ajax()){
            DB::table('allowance_config')->where('id', $request->allowanceId)->delete();

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

    /**
     * Add groups to an allowance
     */

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

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

    public function save_selected_employees(Request $request){
        if ($request->allowanceValue == ""){
            $allowanceValue = "Range";
        }else{
            $allowanceValue = $request->allowanceValue;
        }

        #Check if this record exists
        $results = DB::table('payroll_item_groups')->where([
            ['payroll_item', '=', $request->payrollItem],
            ['payroll_item_id', '=', $request->allowance],
            ['value', '=', $allowanceValue]
        ])->get();

        if ($results->count() > 0){
            #Start the update process
            foreach ($results as $result){
                $employees = $result->employees;
            }

            #Convert the string of selected employees received into an array
            $selected_employees = explode(',', $request->selectedEmployees);

            #Convert the string of available employees received into an array
            $employees = explode(',', $employees);

            #Compare and remove from selected employees those employees that already exists
            $selected_employees = array_diff($selected_employees, $employees);

            #Check if there is anything left in the array
            if (count($selected_employees) > 0){
                #Re-arrange the array keys
                $selected_employees = array_values($selected_employees);

                #Implode the remaining
                $selected_employees = implode(',', $selected_employees);
                $employees = implode(',', $employees);

                #Merge the remains of the arrays to create the new record
                $employees = $employees.','.$selected_employees;
                #Update the record
                DB::table('payroll_item_groups')
                    ->where([
                        ['payroll_item', $request->payrollItem],
                        ['payroll_item_id', $request->allowance],
                        ['value', $allowanceValue]
                    ])
                    ->update([
                        'employees' => $employees,
                        'updated_at' => DB::raw('NOW()')
                    ]);

                #Exit with status = 1 response
                return response()->json(['status' => 1], 200);
            }else{
                #There is nothing left, so return a success message
                return response()->json(['status' => 1], 200);
            }

        }else{

            #Insert the new record
            DB::table('payroll_item_groups')->insert([
                'payroll_item_id' => $request->allowance,
                'value' => $allowanceValue,
                'employees' => $request->selectedEmployees,
                'payroll_item' => $request->payrollItem,
                'created_by' => 1,
                'modified_by' => 1,
                'created_at' => DB::raw('NOW()'),
                'updated_at' => DB::raw('NOW()')
            ]);

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

    }

    /**
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     * Update the group of employees in an allowance
     */

    public function update_group_members(Request $request){
        if ($request->allowanceValue == ""){
            $allowanceValue = "Range";
        }else{
            $allowanceValue = $request->allowanceValue;
        }

        #Check if this record exists
        $results = DB::table('payroll_item_groups')->where([
            ['id', $request->groupId]
        ])->get();

        $selected_employees = explode(',', $request->selectedEmployees);
        $selected_employees = array_unique($selected_employees);
        $selected_employees = implode(',', $selected_employees);
        $request->selectedEmployees = $selected_employees;

        if ($results->count() > 0){

            #Update the record
            DB::table('payroll_item_groups')
                ->where([
                    ['id', $request->groupId]
                ])
                ->update([
                    'value' => $allowanceValue,
                    'employees' => $request->selectedEmployees,
                    'updated_at' => DB::raw('NOW()')
                ]);

            #Exit with status = 1 response
            return response()->json(['status' => 1], 200);

        }else{

            #Insert the new record
            DB::table('payroll_item_groups')->insert([
                'payroll_item_id' => $request->allowance,
                'value' => $allowanceValue,
                'employees' => $request->selectedEmployees,
                'payroll_item' => $request->payrollItem,
                'created_by' => 1,
                'modified_by' => 1,
                'created_at' => DB::raw('NOW()'),
                'updated_at' => DB::raw('NOW()')
            ]);

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

    }

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

    public function filter_employees(Request $request){
        if ($request->department == 0 && $request->scope == 1){
            $results = DB::table('main_users')
                ->select('id', 'last_name', 'first_name')
                ->get();
        }else{
            #Build the query for the scope to be covered
            $scope = [];
            switch ($request->scope){
                case '1':
                    $scope = ['id', 'like', '%'];
                    break;
                case '2':
                    $scope = ['business_unit', $request->businessUnit];
                    break;
                case '3':
                    $scope = ['employee_type', 1];
                    break;
                case '4':
                    $scope = ['employee_type', 2];
                    break;
                default:
                    $scope = ['id', '%', ''];
            }

            $results = DB::table('main_users')
                ->select('id', 'last_name', 'first_name')
                ->where([
                    ['department', 'like', $request->department],
                    $scope
                ])->get();
        }

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

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

    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('Allowances.edit_group', compact(['departments', 'group', 'employee_names']));
    }

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

    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);
    }
}
