<?php

namespace App\Http\Controllers;

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

class PayslipController extends Controller
{

    public function index(){
        Return view('Payslip.index');
    }

    public function process_payslip(Request $request){
        #Get the user details of this employee
        #Pull payslip details for given year
        #Return results
        $employee = DB::table('main_users')
            ->where('id', $request->userId)
            ->first();

        $payslip = DB::table('payslips')
            ->where([
                ['user_id', $employee->id],
                ['year', $request->year],
                ['month', $request->month]
            ])
            ->get();

        return view('Payslip.payslip', compact(['employee', 'payslip']));
    }

    public function view_payslip(Request $request){
        $user_id = 2;

        $users = DB::table('payslips')
            ->join('main_users', 'main_users.id', '=', 'payslips.user_id')
            ->join('departments', 'departments.id', '=', 'main_users.department')
            ->join('calendar_months', 'calendar_months.numeral', '=', 'payslips.month')
            ->join('employee_salary_details', 'employee_salary_details.user_id', '=', 'payslips.user_id')
            ->select(DB::raw('distinct payslips.user_id'), 'payslips.year', 'employee_salary_details.salary', 'main_users.first_name', 'main_users.last_name', 'main_users.employee_id', 'departments.department_name', 'calendar_months.month')
            ->get();


        $user_details = DB::table('payslips')
            ->where('payslips.user_id', $user_id)
            ->join('main_users', 'main_users.id', '=', 'payslips.user_id')
            ->join('employee_salary_details', 'employee_salary_details.user_id', '=', 'payslips.user_id')
            ->join('departments', 'departments.id', '=', 'main_users.department')
            ->select('employee_salary_details.salary', 'main_users.first_name', 'main_users.last_name', 'main_users.employee_id', 'departments.department_name', 'payslips.*')
            ->get();

        return view('Payslip.view_payslip', compact(['users', 'user_details']));
    }
}
