<?php

namespace App\Http\Controllers;

use App\Models\Reseller;
use App\Models\ResellerCommissionReference;
use App\Models\ResellerRechargeReport;
use App\Models\UserAccounting;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Http\Request;

class RsellerCommissioneController extends Controller
{

    public function index()
    {
        //
    }
    public function create()
    {
        //
    }
    public function store(Request $request)
    {
        //
    }
    public function show($id)
    {
        //
    }
    public function edit($id)
    {

        $all_reseller_list = Reseller::all()->pluck('id')->toArray();

        if (!in_array($id, $all_reseller_list)) {
            Toastr::error("You do not have permission to view this.");
            return redirect()->back();
        }


        $reseller = Reseller::find($id);
        $start = Carbon::now()->startOfMonth();
        $end = today()->addDay();
        $accounts = ResellerCommissionReference::where('reseller_id', $reseller->id)
            ->whereBetween('created_at', [$start, $end])
            ->orderBy('created_at', 'asc');
        $opening_balance = ResellerCommissionReference::where('reseller_id', $reseller->id)
            ->whereRaw("created_at < '$start'")
            ->sum('received_amount');

        return view('commissionHistory.history', [
            'reseller'     => $reseller,
            'start' => $start,
            'end' => $end,
            'accounts'   => $accounts->get(),
            'opening_balance' => $opening_balance,
        ]);
    }

    public function commission_history_search(request $request)
    {
        $reseller = Reseller::find($request->id);
        $start = Carbon::parse($request->from_date);
        $end = Carbon::parse($request->to_date);
        $accounts = ResellerCommissionReference::where('reseller_id', $reseller->id)
            ->whereBetween('created_at', [$start, $end])
            ->orderBy('created_at', 'asc');
        $details = ResellerCommissionReference::where('reseller_id', $reseller->id)
            ->whereRaw("created_at < '$start'");
        $receive = $details->sum('received_amount');
        $send = $details->sum('paid_amount');
        $opening_balance = $receive - $send;

        return view('commissionHistory.history', [
            'page_title' => 'Reseller/Subreseller Commission Information',
            'accounts'   => $accounts->get(),
            'opening_balance' => $opening_balance,
            'start' => $start,
            'end' => $end,
            'reseller'     => $reseller,
        ]);
    }
    public function update(Request $request, $id)
    {
        //
    }
    public function destroy($id)
    {
        //
    }
}
