<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Models\AccVendor;
use App\Models\CompanyChartsOfAccount;
use App\Models\CompanyPayrollManager;
use App\Models\EmployeeDeductionType;
use App\Models\EmployeePayrollDeduction;
use App\Models\EmployeePayrollManager;
use App\Models\Requisition;

class CompanyPayrollController extends Controller
{
    public function managePayroll()
    {
        $lists = CompanyPayrollManager::orderBy('year', 'desc')->orderBy('month', 'desc')->get();

        return view('finance.employees.manage-employee-payroll', compact('lists'));
    }

    /**Function to View and manage an Individual Payroll File**/

    public function managePayrollFile($month, $year)
    {
        $payroll = CompanyPayrollManager::where('month', $month)->where('year', $year)->first();

        $liabilityAccount = CompanyChartsOfAccount::where('mapped_id', 'SalaryControl')->first();
        $pendingRequisitions = Requisition::where('dr_id',$payroll->id)->where('req_type', 'net-pay-payment')->where('second_approved', 0)
            ->orWhere('dr_id',$payroll->id)->where('req_type', 'paye-payment')->where('second_approved', 0)
            ->orWhere('dr_id',$payroll->id)->where('req_type', 'deduction-payment')->where('second_approved', 0)
            ->get();
        $payrolls = CompanyPayrollManager::orderBy('month', 'desc')->orderBy('year', 'desc')->get();
        $netPayPayment = 0;
        if(Requisition::where('dr_id', $payroll->id)->where('req_type', 'net-pay-payment')->where('req_status', 'paid')->first()){
            $netPayPayment = Requisition::where('dr_id', $payroll->id)->where('req_type', 'net-pay-payment')->where('req_status', 'paid')->sum('amount');
        }
        $payePayment = 0;
        if(Requisition::where('dr_id', $payroll->id)->where('req_type', 'paye-payment')->where('req_status', 'paid')->first()){
            $payePayment = Requisition::where('dr_id', $payroll->id)->where('req_type', 'paye-payment')->where('req_status', 'paid')->sum('amount');
        }

        /**Above recent Transactions involves Deductions + Paye + NetPay which gives the total Basic Pay**/
        $deductions = EmployeePayrollDeduction::where('month', $month)->where('year', $year)->get();
        $deductionList = [];
        foreach ($deductions as $row){
            $deductionList[] = [
                'deductionId' => $row->deduction_id,
                'deductionName' => $row->deduction ? $row->deduction->name : '',
                'deductionAmount' => $row->deduction_amount,
                'deductionPaidAmount' => 0,
            ];
        }
        $deductionsData = []; //This will be used as the Deduction Data
        if($deductionList != null){
            foreach($deductionList as $v){
                /**For every Deduction, we can check through the Requisitions Table to See if it has been paid**/
                $req = Requisition::where('batch',$v["deductionId"])->where('dr_id', $payroll->id)->where('req_type', 'deduction-payment')->where('req_status', 'paid')->first();
                $paidAmount = 0;
                if($req != null){
                    $paidAmount = $req->amount;
                }

                $key = $v["deductionId"];

                if(isset($deductionsData[$key])){
                    $deductionsData[$key]["deductionAmount"] += $v["deductionAmount"];
                    $deductionsData[$key]["deductionPaidAmount"] = $paidAmount;
                }else{
                    $deductionsData[$key] = $v;
                }
            }
        }
        return view('finance.employees.payroll-file', compact('payroll', 'liabilityAccount', 'pendingRequisitions', 'deductionsData', 'payrolls', 'netPayPayment', 'payePayment'));
    }

    /**Create a Function that will return a List of Payroll Accounts**/
    public function payrollPaymentAccounts($id, $type)
    {
        $payroll = CompanyPayrollManager::findOrFail($id);
        $paymentAccounts = [];
        if($type == 'net-pay-payment'){
            /**Here, we are paying Net Premium: So we need to get individual employees and Display them **/
            $list = EmployeePayrollManager::where('month', $payroll->month)->where('year', $payroll->year)->get();
            foreach ($list as $row){
                $paymentAccounts[] = [
                    'id' => $row->id,
                    'name' => $row->employee ? $row->employee->firstName." ".$row->employee->lastName : '',
                ];
            }
        }elseif ($type == 'paye-payment'){
            /**Here we are paying for the TAXES - PAYE, as a result, we have a Ledger Account that has the mapped ID of PAYE**/
            $ledgers = CompanyChartsOfAccount::where('mapped_id', 'PAYE')->get();
            foreach ($ledgers as $row){
                $paymentAccounts[] = [
                    'id' => $row->id,
                    'name' => $row->acc_name
                ];
            }
        }elseif($type == 'deduction-payment'){
            /**Here we are paying for the Deductions, as a result we need to Display all Deductions in the Company List**/
            $deductions = EmployeeDeductionType::where('ledger_id', "!=", null)->get();
            foreach ($deductions as $row){
                $paymentAccounts[] = [
                    'id' => $row->id,
                    'name' => $row->name
                ];
            }
        }
        return view('finance.employees.payroll-payment-accounts', compact( 'paymentAccounts'));
    }

    /**Create a FUnction that will get the Current Balance for a given Payroll Item**/
    public function billBalance($id, $item, $type)
    {
        $payroll = CompanyPayrollManager::findOrFail($id);
        $billBalance = 0;
        $payee = "";
        if($type == 'net-pay-payment'){
            /**Here we are searching for the Net Pay depending on the Employee**/
            $employeePayroll = EmployeePayrollManager::findOrFail($item);
            if($employeePayroll){
                $billBalance = $employeePayroll->net_salary;
                $payee = $employeePayroll->employee ? strtoupper($employeePayroll->employee->firstName." ".$employeePayroll->employee->lastName) : "";
            }
        }elseif($type == 'paye-payment'){
            /**Here, we are just paying the PAYE amount as a whole**/
            $billBalance = $payroll->paye;
            /**For the P.A.Y.E on this, we look at the Vendors Section where there exists a vendor who is affiliated to the PAYE Expense Ledger **/
            $ledger = CompanyChartsOfAccount::where('mapped_id', 'PAYE')->first();
            if($ledger){
                /**At this Point we are sure that a Ledger Exists for the PAYE Expenses int the company**/
                /**We now look into the Vendors Table for a Vendor who is affiliated to this Ledger**/
                $vendor = AccVendor::where('ledger_id', $ledger->id)->first();
                if($vendor){
                    $payee = strtoupper($vendor->name);
                }
            }
        }elseif($type == 'deduction-payment'){
            /**Here we are paying for the Deductions and as a result we are doing an Individual item at an time**/
            $deductions = EmployeePayrollDeduction::where('month', $payroll->month)->where('year', $payroll->year)->where('deduction_id', $item)->get();
            if($deductions){
                $billBalance = $deductions->sum('deduction_amount');

                /**The above Item ID is a Deduction Type ID**/
                $deduction = EmployeeDeductionType::where('id', $item)->first();
                if($deduction->ledger_id != null){
                    /**The above shows that the Deduction Item was mapped to an expense account**/
                    $ledger = $deduction->ledger_id;
                    /**We now look into the Vendors Table for a Vendor who is affiliated to this Ledger**/
                    $vendor = AccVendor::where('ledger_id', $ledger)->first();
                    if($vendor){
                        $payee = strtoupper($vendor->name);
                    }
                }
            }
        }
        $results = [
            'payee' => $payee,
            'amount' => $billBalance
        ];

        return response()->json($results);
    }

    /**View and Download Net Pay Report**/
    public function downloadNetPayReport($id)
    {
        /**The above Id is the Payroll Id**/
        $payroll = CompanyPayrollManager::findOrFail($id);

        $netPayData = EmployeePayrollManager::where('month', $payroll->month)->where('year', $payroll->year)->get();

        return view('finance.employees.download-net-pay-report', compact('payroll', 'netPayData'));
    }

    /**View and Download Paye Report**/
    public function downloadPayeReport($id)
    {
        /**The above Id is the Payroll Id**/
        $payroll = CompanyPayrollManager::findOrFail($id);

        $netPayData = EmployeePayrollManager::where('month', $payroll->month)->where('year', $payroll->year)->get();

        return view('finance.employees.download-paye-report', compact('payroll', 'netPayData'));
    }

    /**View and Download Net Pay Report**/
    public function downloadDeductionReport($id, $deduction_id)
    {
        /**The above Id is the Payroll Id**/
        $payroll = CompanyPayrollManager::findOrFail($id);

        $deductionPayData = EmployeePayrollDeduction::where('month', $payroll->month)->where('year', $payroll->year)->where('deduction_id', $deduction_id)->get();
        $deduction = EmployeeDeductionType::find($deduction_id);

        return view('finance.employees.download-deduction-report', compact('payroll', 'deductionPayData', 'deduction'));
    }

}
