<?php

namespace App\Http\Controllers\Accounting;

use App\Models\User;
use App\Models\FundTransfer;
use Illuminate\Http\Request;
use App\Models\UserAccounting;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;

class FundTransferController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:fund-transfer', ['only' => ['index', 'show']]);
        $this->middleware('permission:fund-transfer', ['only' => ['create', 'store']]);
        $this->middleware('permission:fund-transfer', ['only' => ['edit', 'update']]);
    }

    public function index()
    {
        $users = User::where('email', '!=', 'admin@billingfix.xyz')
            ->where('email', '!=', 'limitedyetfix@gmail.com')
            ->where('email', '!=', 'soiket@outlook.com')
            ->where('email', '!=', 'support@yetfix.com')
            ->where('user_accounting_status','yes')
            ->get();
        $all_users = User::get();
        // dd(FundTransfer::orderBy('id', 'desc')->take(500)->get());
        return view('accounts.fundtransfer', [
            'users' => $users,
            'lists' => FundTransfer::orderBy('id', 'desc')->take(500)->get(),
            'all_users' => $all_users,
        ]);
    }

    public function edit($id)
    {
        return view('accounts.fundtransferEdit', [
            'users' => User::where('email', '!=', 'admin@billingfix.xyz')->get(),
            'fund' => FundTransfer::find($id)
        ]);
    }

    // public function update(request $request, $id)
    // {
    //     DB::beginTransaction();
    //     try {

    //         $fund = FundTransfer::find($id);
    //         $fund->amount = $fund->fund_send_by == 0 ? -$request->amount : $request->amount;
    //         $fund->note = $request->note;
    //         $fund->save();

    //         $useraccount = UserAccounting::find($fund->user_accountings_id);
    //         if ($fund->fund_send_by == 0) {
    //             $useraccount->received_amount = $request->amount;
    //         } else {
    //             $useraccount->paid_amount = $request->amount;
    //         }
    //         $useraccount->comments = $request->note;
    //         $useraccount->save();

    //         DB::commit();

    //         return redirect()->route('fund-transfer.index')->with('success_message', 'Fund Transfer Update Successfull');
    //     } catch (\Throwable $th) {
    //         //throw $th;

    //         DB::rollBack();
    //     }
    // }


    public function update(request $request, $id)
    {
        DB::beginTransaction();
        try {

            $fund = FundTransfer::find($id);
            $fund->amount = $request->amount;
            $fund->note = $request->note;
            $fund->update();

            if ($fund->fund_send_by != '0' && $fund->fund_received_by != '0') {
                return redirect()->back()->with('error_message', 'Something is wrong');
            }

            if ($fund->fund_send_by != '0') {
                $ac_id = UserAccounting::find($fund->user_accountings_id);
                $ac_id->received_amount = 0;
                $ac_id->paid_amount = $request->amount;
                $ac_id->comments = $request->note;
                $ac_id->update();
            }

            if ($fund->fund_received_by != '0') {
                $ac_id = UserAccounting::find($fund->user_accountings_id);
                $ac_id->received_amount = $request->amount;
                $ac_id->paid_amount = 0;
                $ac_id->actions = $request->note;
                $ac_id->update();
            }

            DB::commit();
            return redirect()->route('fund-transfer.index')->with('success_message', 'Fund Transfer Update Successfull');
        } catch (\Throwable $th) {
            //throw $th;
            DB::rollBack();
        }
    }

    public function store(request $request)
    {
        DB::beginTransaction();


        if ($request->amount < 0) {
            Toastr::error('Negative Value not supported', 'Error');
            return redirect()->back();
        }

        try {
            if ($request->send_by == '0' && $request->received_by == '0') {
                return redirect()->back()->with('error_message', 'Something is wrong');
            }

            $sender = $request->send_by == '0' ? 'Cash' : User::where('id', $request->send_by)->pluck('name')->first();
            $receiver = $request->received_by == '0' ? 'Cash' : User::where('id', $request->received_by)->pluck('name')->first();
            $note = 'Balance Transfer From ' . $sender . ' To ' . $receiver . ' - ' . $request->note;

            if ($request->send_by != '0') {
                $user_accounting = UserAccounting::userAcDeduct($request->amount, $note, $request->send_by);
                $user_accountings_id = $user_accounting->id;
            }

            if ($request->received_by != '0') {
                $user_accounting = UserAccounting::userAcPaid($request->amount, $note, $request->received_by);
                $user_accountings_id = $user_accounting->id;
            }

            $status = FundTransfer::create([
                'fund_send_by'          => $request->send_by,
                'fund_received_by'      => $request->received_by,
                'note'                  => $note,
                'transfer_by'           => auth()->user()->id,
                'amount'                => $request->send_by == '0' ? -$request->amount : $request->amount,
                'user_accountings_id'   => $user_accountings_id ?? null,
                'transfer_type'         => $request->transfer_type
            ]);


            DB::commit();

            return redirect()->route('fund-transfer.index')->with('success_message', 'Fund Transfer Success');
        } catch (\Throwable $th) {
            //throw $th;

            dd($th);
            DB::rollback();
        }
    }
}
