<?php

namespace App\Http\Controllers;

use App\Models\Pop;
use App\Models\SubResellerCommissionReference;
use Carbon\Carbon;
use Illuminate\Http\Request;

class SubRsellerCommissioneController extends Controller
{

    public function index()
    {
        //
    }
    public function create()
    {
        //
    }
    public function store(Request $request)
    {
        //
    }
    public function show($id)
    {
        //
    }
    public function edit($id)
    {
        $pop = Pop::find($id);
        $start = Carbon::now()->startOfMonth();
        $end = today()->addDay();
        $accounts = SubResellerCommissionReference::where('pop_id', $pop->id)
            ->whereBetween('created_at', [$start, $end])
            ->orderBy('created_at', 'asc');
        $opening_balance = SubResellerCommissionReference::where('pop_id', $pop->id)
            ->whereRaw("created_at < '$start'")
            ->sum('received_amount');

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

    public function update(request $request)
    {
        $pop = Pop::find($request->id);
        $start = Carbon::parse($request->from_date);
        $end = Carbon::parse($request->toDate);
        $accounts = SubResellerCommissionReference::where('pop_id', $pop->id)
            ->whereBetween('created_at', [$start, $end])
            ->orderBy('created_at', 'asc');
        $details = SubResellerCommissionReference::where('pop_id', $pop->id)
            ->whereRaw("created_at < '$start'");
        $receive = $details->sum('received_amount');
        $send = $details->sum('paid_amount');
        $opening_balance = $receive - $send;

        return view('commissionHistory.subresellerHistory', [
            'page_title' => 'Reseller/Subreseller Commission Information',
            'accounts'   => $accounts->get(),
            'opening_balance' => $opening_balance,
            'start' => $start,
            'end' => $end,
            'pop' => $pop,
        ]);
    }


    public function destroy($id)
    {
        //
    }
}