<?php

namespace App\Http\Controllers;

use App\Models\BillMasterCompanyPayroll;
use Illuminate\Http\Request;

class BillMasterCompanyPayrollController extends Controller
{
    /**Create a Function that will be used to get the current Balance of a Company Payroll**/
    public function currentCompanyPayrollBalance($id){
        /**The above ID is the Id for the Payroll**/
        $currentBalance = 0;
        $lessThanThirty = 0;
        $thirtyAndSixty = 0;
        $sixtyAndNinety = 0;
        $ninetyAndOneEighty = 0;
        $oneEightyAndThreeSixtyFive = 0;
        $moreThanThreeSixtyFive = 0;

        $entries = BillMasterCompanyPayroll::where('payroll_id', $id)->get();
        if($entries){
            $currentBalance = $entries->sum('amount');

            /**Balance where Date is less than 30 Days**/
            $thirtyDaysAgo = \Carbon\Carbon::now()->subMonth()->format('Y-m-d');
            $lessThanThirty = BillMasterCompanyPayroll::where('payroll_id', $id)->whereBetween('date', [$thirtyDaysAgo, date('Y-m-d')])->sum('amount');
            /**Balance where Date is Between 30 and 60 Days**/
            $sixtyDaysAgo = \Carbon\Carbon::now()->subMonths(2)->format('Y-m-d');
            $thirtyAndSixty = BillMasterCompanyPayroll::where('payroll_id', $id)->whereBetween('date', [$sixtyDaysAgo, $thirtyDaysAgo])->sum('amount');
            /**Balance where Date is Between 61 and 90 Days**/
            $ninetyDaysAgo = \Carbon\Carbon::now()->subMonths(3)->format('Y-m-d');
            $sixtyAndNinety = BillMasterCompanyPayroll::where('payroll_id', $id)->whereBetween('date', [$ninetyDaysAgo, $sixtyDaysAgo])->sum('amount');
            /**Balance where Date is Between 91 and 180 Days**/
            $sixMothsAgo = \Carbon\Carbon::now()->subMonths(6)->format('Y-m-d');
            $ninetyAndOneEighty = BillMasterCompanyPayroll::where('payroll_id', $id)->whereBetween('date', [$sixMothsAgo, $ninetyDaysAgo])->sum('amount');
            /**Balance where Date is Between 181 and 365 Days**/
            $oneYearAgo = \Carbon\Carbon::now()->subYear()->format('Y-m-d');
            $oneEightyAndThreeSixtyFive = BillMasterCompanyPayroll::where('payroll_id', $id)->whereBetween('date', [$oneYearAgo, $sixMothsAgo])->sum('amount');
            /**Balance where Date is More than a Year Ago(365 Days)**/
            $moreThanThreeSixtyFive = BillMasterCompanyPayroll::where('payroll_id', $id)->whereDate('date', '<', $oneYearAgo)->sum('amount');
        }

        return [
            'currentBalance' => $currentBalance,
            'lessThanThirty' => $lessThanThirty,
            'thirtyAndSixty' => $thirtyAndSixty,
            'sixtyAndNinety' => $sixtyAndNinety,
            'ninetyAndOneEighty' => $ninetyAndOneEighty,
            'oneEightyAndThreeSixtyFive' => $oneEightyAndThreeSixtyFive,
            'moreThanThreeSixtyFive' => $moreThanThreeSixtyFive,
        ];
    }
}
