<?php

namespace App\Http\Controllers;

use App\Models\Banking;
use App\Models\BankTransfar;
use App\Models\Employee;
use App\Models\EmployeePayment;
use App\Models\Expense;
use App\Models\ExpenseHead;
use App\Models\Payroll;
use App\Models\UserAccounting;
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',
        ]);

        try {
            DB::beginTransaction();

            // Get employee information
            $employee = Employee::findOrFail($request->employee_id);

            // Check bank balance if bank account is selected
            if ($request->filled('bank_account_id') && !empty($request->bank_account_id)) {
                $banking = Banking::find($request->bank_account_id);
                if ($banking) {
                    $total_deposit = BankTransfar::where('account_id', $request->bank_account_id)->sum('diposit_amount');
                    $total_withdrawal = BankTransfar::where('account_id', $request->bank_account_id)->sum('withdraw_amount');
                    $balance = $banking->opening_balance + $total_deposit - $total_withdrawal;

                    if ($request->amount > $balance) {
                        DB::rollBack();
                        Toastr::error('Withdraw Amount is greater than Bank Balance', 'Error');
                        return back();
                    }
                }
            }

            $expanseHead = ExpenseHead::where('name', 'Employee Salary')->first();
            if (!$expanseHead) {
                $expanseHead = new ExpenseHead();
                $expanseHead->name = 'Employee Salary';
                $expanseHead->save();
            }

            $expense = new Expense();
            $expense->name = 'Employee Salary(Payroll)';
            $expense->expenseHead = $expanseHead->id;
            $expense->employee_id = $request->employee_id;
            $expense->amount = $request->amount;
            $expense->date = Carbon::now();
            $expense->description = $request->remark ?? 'Employee Salary Payment for ' . $employee->name;
            $expense->created_by = auth()->user()->id;
            $expense->bank_account_id = $request->bank_account_id ?? null;

            $user_accounting = UserAccounting::create([
                'received_amount'  => 0,
                'paid_amount'      => $expense->amount,
                'actions'          => $expense->description . ' approved by ' . auth()->user()->name,
                'comments'         => null,
                'user_id'          => $expense->created_by,
            ]);
            $expense->user_accounting_id = $user_accounting->id;

            $expense->status = 'approved';
            $expense->save();

            // Withdraw from bank account if selected
            if ($request->filled('bank_account_id') && !empty($request->bank_account_id)) {
                $bankWithdrawal = new BankTransfar();
                $bankWithdrawal->account_id = $request->bank_account_id;
                $bankWithdrawal->withdraw_amount = $request->amount;
                $bankWithdrawal->description = 'Employee Salary Payment - ' . $employee->name . ' (ID: ' . $employee->id . ') - ' . ($request->remark ?? 'Salary Payment');
                $bankWithdrawal->by = auth()->user()->name ?? 'System';
                $bankWithdrawal->save();
            }

            $employeePayment = new EmployeePayment();
            $employeePayment->employee_id = $request->employee_id;
            $employeePayment->amount = $request->amount;
            $employeePayment->remark = $request->remark;
            $employeePayment->created_by = auth()->user()->id;
            $employeePayment->bank_account_id = $request->bank_account_id ?? null;
            $employeePayment->save();

            $salarySheet = Payroll::where('employee_id', $request->employee_id)->whereMonth('created_at', Carbon::now()->month)->first();
            if ($salarySheet) {
                $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::where('salary_generate', 1)->get();
        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', 'user', 'bankAccount'])->get();

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

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

    public function previousSalary(Request $request)
    {
        $previousSalary = Payroll::where('employee_id', $request->employee_id)->whereMonth('created_at', Carbon::now()->month)->first();
// dd($previousSalary);

        DB::beginTransaction();
        try{
            $previousSalary = new Payroll();
            $previousSalary->employee_id = $request->employee_id;
            $previousSalary->salary = 0;
            $previousSalary->home_allowance = 0;
            $previousSalary->transport_allowance = 0;
            $previousSalary->other_allowance = 0;
            $previousSalary->bonous = 0;
            $previousSalary->deduction = 0;
            $previousSalary->net_salary = $request->amount;
            $previousSalary->salary_amount = 0;
            $previousSalary->remark = $request->remark;
            $previousSalary->created_by = auth()->user()->id;
            $previousSalary->save();

            DB::commit();

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

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