<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use App\Models\EmployeePayment;
use App\Models\Payroll;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class EmployeePaymentController extends Controller
{
    public function employeePayment(Request $request)
    {
        $request->validate([
            'employee_id' => 'required',
            'amount' => 'required|numeric|min:0',
        ]);

        try {
            DB::beginTransaction();

            $employeePayment = new EmployeePayment();
            $employeePayment->employee_id = $request->employee_id;
            $employeePayment->amount = $request->amount;
            $employeePayment->save();

            $salarySheet = Payroll::where('employee_id', $request->employee_id)->whereMonth('created_at', Carbon::now()->month)->first();
            $salarySheet->salary_amount = $salarySheet->salary_amount - $request->amount;
            $salarySheet->save();

            DB::commit();
        } catch (\Throwable $th) {
            DB::rollBack();
            Toastr::error('Something went wrong', 'Error');
            return back();
        }



        Toastr::success('Payment successfully', 'Success');
        return back();
    }

    public function salarySheet(Request $request)
    {
        $employees = Employee::all();
        return view('payroll.employee.payment.empolyeepayment', compact('employees'));
    }

    public function salaryResult(Request $request)
    {
        $fromDate = Carbon::now()->startOfMonth();
        $toDate = Carbon::now()->endOfMonth();
        if ($request->from_date) {
            $fromDate = Carbon::createFromFormat('Y-m-d', $request->from_date)->startOfMonth();
        }
        if ($request->to_date) {
            $toDate = Carbon::createFromFormat('Y-m-d', $request->to_date)->endOfMonth();
        }

        $employeePayments = EmployeePayment::with('employee')->get();

        if ($request->employee_id) {
            $employeePayments = EmployeePayment::with('employee')
                ->where('employee_id', $request->employee_id)
                ->whereBetween('created_at', [$fromDate, $toDate])
                ->get();
        } else {
            $employeePayments = EmployeePayment::with('employee')
                ->whereBetween('created_at', [$fromDate, $toDate])
                ->get();
        }

        return view('payroll.employee.payment.result', compact('employeePayments'));
    }
}
