<?php

namespace App\Http\Controllers;

use App\Models\BandSale;
use App\Models\BandSaleItem;
use App\Models\BandService;
use App\Models\BwCustomer;
use App\Models\Income;
use App\Models\IncomeHead;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BandwdtihSaleController extends Controller
{

    public function index()
    {
        $data = [
            'list' => BandSale::with('bandwidthSaleCustomer')->get(),
        ];

        return view('bandwidth-sale.bw-sale.index', $data);
    }

    public function create()
    {
        $data = [
            'customer' => BwCustomer::get(),
            'service' => BandService::all()
        ];

        return view('bandwidth-sale.bw-sale.create', $data);
    }

    public function store(Request $request)
    {
        // dd($request->all());
        DB::beginTransaction();
        try {

            $bandWidthSale = new BandSale();
            $bandWidthSale->customer_id = $request->customer_id;
            $bandWidthSale->billing_date = $request->billing_date;
            $bandWidthSale->paid = $request->paidAmount;
            $bandWidthSale->discount = $request->discount;
            $bandWidthSale->total = $request->totalPrice;
            $bandWidthSale->save();

            $income_amount = 0;
            if (($request->totalPrice - $request->discount) < $request->paidAmount) {
                $income_amount = $request->totalPrice - $request->discount;
            } else {
                $income_amount = $request->paidAmount;
            }

            $len = sizeof($request->service_id);
            for ($i = 0; $i < $len; $i++) {
                $saleItem = new BandSaleItem();
                $saleItem->sale_id = $bandWidthSale->id;
                $saleItem->service_id = $request->service_id[$i];
                $saleItem->from_date = $request->from_date[$i];
                $saleItem->to_date = $request->to_date[$i];
                $saleItem->quantity = $request->quantity[$i];
                $saleItem->rate = $request->rate[$i];
                $saleItem->vat = $request->vat[$i];
                $saleItem->line_total = $request->lineTotal[$i];
                $saleItem->save();
            }

            $income_head = IncomeHead::where('name', "BandWith Sale")->first();
            if ($income_head == null) {
                (new FixCommonIssueController)->addBandwidthSaleInIncomeHeadTable();
                $income_head = IncomeHead::where('name', "BandWith Sale")->first();
            }
            $note = "Bandwidth Sale added by " . auth()->user()->name;
            $income = new Income();
            $income->name = "Bandwidth Sale";
            $income->incomeHead = $income_head->id;
            $income->invoice_number = 'nan';
            $income->date = $request->billing_date;
            $income->amount = $income_amount;
            $income->description = $note;
            $income->bandwidth_sale_id = $bandWidthSale->id;


            $income->save();



            DB::commit();
            Toastr::success("Sale successful added");
            return redirect()->route('bw-sale.index');
        } catch (\Exception $e) {
            // dd($e);
            DB::rollBack();
            Toastr::error('Sale is not successful');
            return redirect()->back();
        }
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $bandWidthSale = BandSale::with('sateItems')->find($id);
        $data = [
            'bandWidthSale' => $bandWidthSale,
            'customer' => BwCustomer::get(),
            'service' => BandService::all()
        ];
        return view('bandwidth-sale.bw-sale.edit', $data);
    }

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

            $bandWidthSale =  BandSale::find($id);
            $bandWidthSale->customer_id = $request->customer_id;
            $bandWidthSale->billing_date = $request->billing_date;
            $bandWidthSale->paid = $request->paidAmount;
            $bandWidthSale->discount = $request->discount;
            $bandWidthSale->total = $request->totalPrice;
            $bandWidthSale->save();

            $income_amount = 0;
            if (($request->totalPrice - $request->discount) < $request->paidAmount) {
                $income_amount = $request->totalPrice - $request->discount;
            } else {
                $income_amount = $request->paidAmount;
            }

            BandSaleItem::where('sale_id', $id)->delete();

            $len = sizeof($request->service_id);
            for ($i = 0; $i < $len; $i++) {
                $saleItem = new BandSaleItem();
                $saleItem->sale_id = $bandWidthSale->id;
                $saleItem->service_id = $request->service_id[$i];
                $saleItem->from_date = $request->from_date[$i];
                $saleItem->to_date = $request->to_date[$i];
                $saleItem->quantity = $request->quantity[$i];
                $saleItem->rate = $request->rate[$i];
                $saleItem->vat = $request->vat[$i];
                $saleItem->line_total = $request->lineTotal[$i];
                $saleItem->save();
            }


            $income =  Income::where('bandwidth_sale_id', $bandWidthSale->id)->first();

            $income->date = $request->billing_date;
            $income->amount = $income_amount;



            $income->save();



            DB::commit();
            Toastr::success("Sale update successful");
            return redirect()->back();
        } catch (\Exception $e) {
            // dd($e);
            DB::rollBack();
            Toastr::error('Sale update is not successful');
            return redirect()->back();
        }
    }

    public function destroy($id)
    {
        //
    }

    public function bandwidthSaleReport()
    {
        $start = today()->firstOfMonth();
        $end = today();

        return view('bandwidth-sale.search', [
            'page_title' => 'Bandwidth Sale Report',
            'start'      => $start,
            'end'        => $end,
            'services'   => BandService::all()
        ]);
    }

    public function bandwidthSaleSearch(Request $request)
    {
        if ($request->ajax()) {

            $from = $request->from_date == '' ? today() : Carbon::parse($request->from_date);
            $to   = $request->to_date == '' ? today() : Carbon::parse($request->to_date);

            $from = Carbon::parse($from)->format('Y-m-d 00:00:00');
            $to   = Carbon::parse($to)->format('Y-m-d 23:59:59');

            if ($request->service != null) {
                $list = BandSale::with(['sateItems' => function ($query) use ($request) {
                    $query->where('service_id', $request->service);
                }])->whereBetween('billing_date', [$from, $to])
                    ->whereHas('sateItems', function ($query) use ($request) {
                        $query->where('service_id', $request->service);
                    });
            } else {
                $list = BandSale::with(['sateItems'])->whereBetween('billing_date', [$from, $to]);
            }

            return view('bandwidth-sale.result', [
                'list'       =>  $list->get()
            ]);
        }
    }
}
