<?php

namespace App\Http\Controllers\Accounting;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Reseller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Reseller\ResellerRechargeController;
use App\Models\Expense;
use App\Models\FundTransfer;
use App\Models\ResellerCommissionReference;

class ResellerCommissionInHandController extends Controller
{
    public function commissionInHand(request $request, $type)
    {
        $start = Carbon::now()->startOfMonth();
        $end = today()->addDay();
        $managers = Reseller::get(); //->where('reseller_type','other')->get();

        $accounts = ResellerCommissionReference::selectRaw('sum(received_amount) as ramount, sum(paid_amount) as pamount,reseller_id')
            ->groupBy('reseller_id')->get();
        return view('report.commission_in_hand', [
            'page_title'    => 'Manager Commission Report',
            'type'          => $type,
            'managers'       => $managers,
            'accounts'      => $accounts,
            'start'         => $start,
            'end'           => $end,
        ]);
    }

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

        try {

            $managers = Reseller::get();
            $accounts = ResellerCommissionReference::selectRaw('sum(received_amount) as ramount, sum(paid_amount) as pamount,reseller_id')->groupBy('reseller_id')->get();

            foreach ($managers as $s) {
                if ($s->id == $request->received_by) {

                    $totalAmount = 0;
                    foreach ($accounts as $ac) {
                        if ($ac->reseller_id == $s->id) {
                            $totalAmount += $ac->ramount - $ac->pamount;
                        }
                    }

                    if ($request->amount > $totalAmount) {
                        return redirect()->back()->with('error_message', 'Sorry! You have not enough balance to transfer');
                    }
                }
            }

            if ($request->txn_type == "ManagerRecharge") {

                $request->merge(['reseller_id' => $request->received_by]);
                $request->merge(['paid_amount' => $request->amount]);
                $request->merge(['remark' => $request->note . '--commission transfer through recharge']);

                (new ResellerRechargeController)->store($request);

                if (session('commissionReturnResult') != 'success') {
                    return redirect()->back()->with('error_message', 'Failed to transfer commission');
                }
            }

            $fundtransfer = new FundTransfer();
            $fundtransfer->fund_send_by = 0;
            $fundtransfer->fund_received_by = 0;
            $fundtransfer->amount = $request->amount;
            $fundtransfer->transfer_by = auth()->user()->id;
            $fundtransfer->note = $request->note . '--transfer through--'. $request->txn_type;
            $fundtransfer->created_at = now();
            $fundtransfer->updated_at = now();
            $fundtransfer->transfer_type = 'expense';
            $fundtransfer->save();

            $expense = new Expense();
            $expense->name = 'Commission Transfer';
            $expense->expenseHead = 6;
            $expense->date = today();
            $expense->amount = $request->amount;
            $expense->description = $request->note . '--transfer through--'. $request->txn_type;
            $expense->created_at = now();
            $expense->updated_at = now();
            $expense->status = 'approved';
            $expense->save();

            $resellerCommissionReference = new ResellerCommissionReference();
            $resellerCommissionReference->paid_amount = $request->amount;
            $resellerCommissionReference->comments = $request->note . '--transfer through--'. $request->txn_type;
            $resellerCommissionReference->reseller_id = $request->received_by;
            $resellerCommissionReference->user_id = auth()->user()->id;
            $resellerCommissionReference->created_at = now();
            $resellerCommissionReference->updated_at = now();
            $resellerCommissionReference->fund_transfer_id = $fundtransfer->id;
            $resellerCommissionReference->expense_id = $expense->id;
            $resellerCommissionReference->save();

            DB::commit();

            return redirect()->back()->with('success_message', 'Commission Transfer Successfull');
        } catch (\Throwable $th) {
            //throw $th;
            DB::rollBack();
            return redirect()->back()->with('error_message', 'Something is worong');
        }
    }

    public function commissionSearch(Request $request)
    {
        if ($request->ajax()) {
            // dd($request->all());
            $start = Carbon::now()->startOfMonth();
            $end = today()->addDay();
            $from = $request->from_date == '' ? today() : Carbon::parse($request->from_date)->format('Y-m-d 00:00:00');
            $to   = $request->to_date == '' ? today() : Carbon::parse($request->to_date)->format('Y-m-d 23:59:59');

            $managers = Reseller::with('commission')->get(); //->where('reseller_type','other')->get();

            $accounts = ResellerCommissionReference::selectRaw('sum(received_amount) as ramount, sum(paid_amount) as pamount,reseller_id')
                ->whereBetween('created_at', [$from, $to])
                ->groupBy('reseller_id')->get();

            if($request->reseller != null){
                $managers = Reseller::with('commission')->where('id', $request->reseller)->get();
                $accounts = ResellerCommissionReference::selectRaw('sum(received_amount) as ramount, sum(paid_amount) as pamount,reseller_id')
                    ->whereBetween('created_at', [$from, $to])
                    ->where('reseller_id', $request->reseller)
                    ->groupBy('reseller_id')->get();
            }

            return view('report.commissionResult', [
                'page_title'    => 'Manager Commission Report',
                'type'          => 'all',
                'managers'       => $managers,
                'accounts'      => $accounts,
                'start'         => $start,
                'end'           => $end,
            ]);
        }
    }
}
