<?php

namespace App\Http\Controllers\Backend;

use App\Components\Functions;
use App\Models\CollectSpend;
use App\Models\Config;
use App\Models\ConfigHostel;
use App\Models\Contract;
use App\Models\Hostel;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\Transaction;
use App\User;
use Barryvdh\DomPDF\Facade as PDF;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use phpDocumentor\Reflection\DocBlock\Description;
use App\Http\Controllers\Backend\AdminController;

class BillController extends Controller
{
    //
    public function printBill($id, Request $request)
    {

        $token = $request->input('token');
        $user = User::query()->where('token', $token)->first();
        if (!$user) {
            return redirect()->to(url('/'));
        }
        $item = MoneyInfo::find($id);
        if (!$item) {
            return '<h1>Hóa đơn không tồn tại</h1>';
        }
        $details = MoneyDetail::where('money_info_id', $id)->get();
        $room = $item->room;
        $dateAction = $item->date_action->format('m/Y');
        $pay = $item->pay;
        locale_set_default('vi_VN');


        $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);
        $font = 1;
        $isPrint = 1;
        $text = '';
        
        $user = User::query()->where('token', $token)->first();
        $config = Config::query()->where('owner_id', $user->id)->first();
        $ownerId = $user->id;
        if ($user->type == User::STAFF) {
            $ownerId = $user->staff_owner_id;
            $config = Config::query()->where('owner_id', $user->staff_owner_id)->first();
        }
        if ($user->type == User::RENTER) {
            $renterRoom = RenterRoom::query()
                ->where('user_id', $user->id)
                ->latest()
                ->first();

            if ($renterRoom) {
                $hostel = $renterRoom->hostel;
                if ($hostel) {
                    $ownerId = $hostel->owner_id;
                    $config = Config::query()->where('owner_id', $hostel->owner_id)->first();
                }
            }
        }
        if ($config) {
            $text = $config->voucher;
        }

        $configHostel = ConfigHostel::query()
            ->where('owner_id', $ownerId)
            ->where('hostel_id', $item->hostel_id)
            ->first();

        if ($configHostel) {
            $text = $configHostel->voucher;
        }

        return view('admin.money.bill_v2', compact('item', 'details', 'pay', 'f', 'font', 'isPrint', 'text'));

    }

    public function printEndContract($id, Request $request)
    {
        $token = $request->input('token');
        $user = User::query()->where('token', $token)->first();
        if (auth('backend')->check() && empty($token)) {
            $user = auth('backend')->user();
        }
        if (!$user) {
            return redirect()->to(url('/'));
        }
        $contract = Contract::find($id);
        if (!$contract) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $roomId = $contract->room_id;
        $room = $contract->room;
        $hostel = $contract->room->hostel;
        $userId = $contract->renter_id;
        $messageReturned = '';
        $isConfirm = $request->input('is_confirm');
        $isReturnDeposit = $request->input('is_return_deposit');
        $isReturnMoneyInfo = $request->input('is_return_money_info');

        $dateEndContract = $request->input('date_end_contract');

        if (empty($dateEndContract)) {
            $dateEndContract = Carbon::now();
        } else {
            $dateEndContract = Carbon::createFromFormat('d/m/Y', $dateEndContract);
        }


        $items = MoneyInfo::query()
            ->where('room_id', $roomId)
            ->where('remain', '>', 0)
            ->where(function ($q) use ($contract) {

                $q->orwhere('user_id', $contract->renter_id);
                $q->orWhere('contract_id', $contract->id);

            })
            ->orderBy('id', 'desc')->get();

        $itemsRoomPrice = MoneyInfo::where('room_id', $roomId)
            ->where(function ($q) use ($contract) {

                $q->orwhere('user_id', $contract->renter_id);
                $q->orWhere('contract_id', $contract->id);

            })->whereIn('type', [
                MoneyInfo::VOUCHER_ROOM_PRICE,
                MoneyInfo::VOUCHER_CONTRACT
            ])->pluck('id')->toArray();

        $moneyDetails = MoneyDetail::query()->whereIn('money_info_id', $itemsRoomPrice)
            ->orderBy('end_date', 'desc')->first();

        $itemsSum = MoneyInfo::query()->where('room_id', $roomId)
            ->where('remain', '>', 0)
            ->where(function ($q) use ($contract) {

                $q->orwhere('user_id', $contract->renter_id);
                $q->orWhere('contract_id', $contract->id);

            });

        $amountRemain = MoneyInfo::where('room_id', $roomId)
            ->where('remain', '>', 0)
            ->where(function ($q) use ($contract) {

                $q->orwhere('user_id', $contract->renter_id);
                $q->orWhere('contract_id', $contract->id);

            })->sum('remain');
        $amountReturnUser = 0;
        $amountCollected = 0;
        $amountReturned = 0;
        $messageReturnCollected = null;
        $amountItemSum = clone $itemsSum;
        $amountItemPay = clone $itemsSum;
        $amountItemDiscount = clone $itemsSum;

        $amountSum = $amountItemSum->sum('amount');
        $amountPay = $amountItemPay->sum('pay');
        $amountDiscount = $amountItemDiscount->sum('discount');

        $amountSum -= $amountDiscount;

        // $endDate = null;


        $latestEndDate = optional($moneyDetails)->end_date;
        $endDate = null;
        if (!empty($latestEndDate)) {
            $endDateCarbon = Carbon::createFromFormat('Y-m-d', $latestEndDate);
            $endDate = $endDateCarbon->copy()->addDay();
            $startDate = $dateEndContract->copy()->addDay(1)->startOfDay();
            if ($startDate->lessThanOrEqualTo($endDateCarbon)) {
                $amountReturned = Functions::calculateMoneyInRange4($startDate, $endDateCarbon, $contract->room_price, $contract->day_collect);
                $messageReturned = 'Trả lại tiền phòng từ ' . $startDate->copy()->format('d/m/Y') . ' đến ' . $endDateCarbon->copy()->format('d/m/Y');
            }
        }

        //	$amountReturnUser = $amountRemain - $amountReturned - $contract->deposit;


        $amountReturnUser = $amountSum;
        if ($isReturnMoneyInfo) {
            $amountReturnUser = $amountReturnUser - $amountReturned;
        }
        if ($isReturnDeposit) {
            $amountReturnUser = $amountReturnUser - $contract->deposit;
        }

        if ($amountPay > 0) {
            $amountReturnUser = $amountReturnUser - $amountPay;
        }

        $details = MoneyDetail::query()->whereIn('money_info_id', $items->pluck('id')->toArray())->get();
        $discount = $amountDiscount;
        $pay = $amountPay;
        $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);

        return view('admin.money.bill_end_contract', compact('items', 'amountSum', 'amountPay', 'details', 'user',
            'roomId', 'room', 'hostel', 'userId', 'contract', 'endDate', 'amountCollected', 'pay', 'f', 'isReturnDeposit', 'isReturnMoneyInfo',
            'messageReturnCollected', 'amountReturned', 'messageReturned', 'amountReturnUser', 'contract', 'discount'));

    }

    public function printAllBill($id, $contractId, Request $request)
    {
        $token = $request->input('token');
        $month = $request->input('month');
        $item = MoneyInfo::find($id);

        if (!$item) {
            return '<h1>Hóa đơn không tồn tại</h1>';
        }
        $items = MoneyInfo::query()
            ->where('room_id', $item->room_id);

        if (empty($month)) {
            $items = $items->whereBetween('date_action', [
                $item->date_action->startOfMonth()->startOfDay(),
                $item->date_action->endOfMonth()->endOfDay()
            ]);
        } else {
            try {
                $monthCarbon = Carbon::createFromFormat('d/m/Y', '01/'.$month);
            } catch (\Exception $exception) {
                $monthCarbon = Carbon::now();
            }
            $items = $items->whereBetween('date_action', [
                $monthCarbon->startOfMonth()->startOfDay(),
                $monthCarbon->endOfMonth()->endOfDay()
            ]);
        }
        // ->where('remain', '>', 0);
        if (!empty($contractId)) {
            $items = $items->where('contract_id', $contractId);
        }
        $user = User::query()->where('token', $token)->first();
        if (!$user) {
            return redirect()->to(url('/'));
        }

        $font = 1;
        $pay = clone $items;
        $discount = clone $items;
        $items = $items->get();
        $ids = $items->pluck('id')->toArray();
        $details = MoneyDetail::query()->whereIn('money_info_id', $ids)->get();

        $discount = $discount->sum('discount');
        $room = $item->room;
        $pay = $pay->sum('pay');
        locale_set_default('vi_VN');
        $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);
        $text = null;
        $config = Config::query()->where('owner_id', $user->id)->first();
        $ownerId = $user->id;


        if ($user->type == User::STAFF) {
            $config = Config::query()->where('owner_id', $user->staff_owner_id)->first();
            $ownerId = $user->staff_owner_id;
        }

        if ($user->type == User::RENTER) {
            $renterRoom = RenterRoom::query()
                ->where('user_id', $user->id)
                ->latest()
                ->first();
            if ($renterRoom) {
                $hostel = $renterRoom->hostel;
                if ($hostel) {
                    $config = Config::query()->where('owner_id', $hostel->owner_id)->first();
                    $ownerId = $hostel->owner_id;
                }
            }
        }
        if ($config) {
            $text = $config->voucher;
        }
        $configHostel = ConfigHostel::query()
            ->where('owner_id', $ownerId)
            ->where('hostel_id', $item->hostel_id)
            ->first();

        if ($configHostel) {
            $text = $configHostel->voucher;
        }
        $isPrint = 1;
        $notes = $items->pluck('note')->toArray();

        return view('admin.money.bill_v2', compact('item', 'notes', 'details', 'pay', 'f', 'font', 'text', 'discount', 'isPrint'));

    }

    public function printAllBillByContract(Request $request)
    {

        $token = $request->input('token');
        $month = $request->input('month');
        $contractId = $request->input('contract_id');
        $contractIds = $request->input('contract_ids');
        try {
            $monthCarbon = Carbon::createFromFormat('d/m/Y', '01/' . $month);
            $dateCarbon = Carbon::createFromFormat('d/m/Y', '01/' . $month);
        } catch (\Exception $exception) {
            $monthCarbon = Carbon::now();
            $dateCarbon = Carbon::now();
        }

        $item = null;
        if (!empty($contractId)) {
            $item = Contract::find($contractId);
        } else if (!empty($contractIds)) {
            $item = Contract::find($contractIds[0]);
        }

        if (!$item) {
            return '<h3>Dữ liệu không hợp lệ</h3>';
        }


        $items = MoneyInfo::query()
            ->when(!empty($contractId), function ($q) use ($contractId) {
                $q->where('contract_id', $contractId);
            })
            ->when(!empty($contractIds), function ($q) use ($contractIds) {
                $q->whereIn('contract_id', $contractIds);
            });


        $items = $items->whereBetween('date_action', [
            $monthCarbon->copy()->startOfMonth()->startOfDay(),
            $monthCarbon->copy()->endOfMonth()->endOfDay()
        ]);

        // ->where('remain', '>', 0);
        $user = User::query()->where('token', $token)->first();
        if (!$user) {
            return redirect()->to(url('/'));
        }

        $font = 1;
        $pay = clone $items;
        $discount = clone $items;
        $items = $items->get();
        $ids = $items->pluck('id')->toArray();
        $details = MoneyDetail::query()->whereIn('money_info_id', $ids)->get();

        $discount = $discount->sum('discount');
        $room = $item->room;
        $pay = $pay->sum('pay');
        locale_set_default('vi_VN');
        $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);
        $text = null;
        $config = Config::query()->where('owner_id', $user->id)->first();
        $ownerId = $user->id;


        if ($user->type == User::STAFF) {
            $config = Config::query()->where('owner_id', $user->staff_owner_id)->first();
            $ownerId = $user->staff_owner_id;
        }

        if ($user->type == User::RENTER) {
            $renterRoom = RenterRoom::query()
                ->where('user_id', $user->id)
                ->latest()
                ->first();
            if ($renterRoom) {
                $hostel = $renterRoom->hostel;
                if ($hostel) {
                    $config = Config::query()->where('owner_id', $hostel->owner_id)->first();
                    $ownerId = $hostel->owner_id;
                }
            }
        }
        if ($config) {
            $text = $config->voucher;
        }
        $configHostel = ConfigHostel::query()
            ->where('owner_id', $ownerId)
            ->where('hostel_id', $item->hostel_id)
            ->first();

        if ($configHostel) {
            $text = $configHostel->voucher;
        }
        $isPrint = null;
        $notes = $items->pluck('note')->toArray();

        if(!empty($contractIds))
        {
            $contracts = Contract::query()->whereIn('id', $contractIds)->get();
            $type = 2;
            foreach ($contracts as $contract)
            {
                $contract->note_money_info = $items->where('contract_id','=', $contract->id)->pluck('note')
                    ->filter(function($item) {
                        return !empty($item);
                    })
                    ->toArray();
            }
//            if (auth('backend')->user()->id == 16088 || auth('backend')->user()->staff_owner_id == 16088) {
//                return view('admin.money.bill_contracts_v2_16088', compact('dateCarbon','type', 'contracts','item','items', 'notes', 'details', 'pay', 'f', 'font', 'text', 'discount', 'isPrint'));
//            }
            return view('admin.money.bill_contracts_v2', compact('dateCarbon','type', 'contracts','item','items', 'notes', 'details', 'pay', 'f', 'font', 'text', 'discount', 'isPrint'));
        }
//        if (auth('backend')->user()->id == 16088 || auth('backend')->user()->staff_owner_id == 16088) {
//            return view('admin.money.bill_v2_16088', compact('item', 'notes', 'details', 'pay', 'f', 'font', 'text', 'discount', 'isPrint'));
//        }
        return view('admin.money.bill_v2', compact('item', 'notes', 'details', 'pay', 'f', 'font', 'text', 'discount', 'isPrint'));

    }

    public function printRoomService(Request $request)
    {
        $token = $request->input('token');
        $month = $request->input('month');
        $contractId = $request->input('contract_id');
        $contractIds = $request->input('contract_ids');

        $month = '01/' . $month;
        $contract= null;
        if (!empty($contractId)) {
            $contract = Contract::find($contractId);

        } else if (!empty($contractIds)) {
            $contract = Contract::find($contractIds[0]);
        }
        if (!$contract) {
            return '<h1>Dữ liệu không hợp lệ</h1>';
        }

        $dateCarbon = Carbon::createFromFormat('d/m/Y', $month);

        $items = MoneyInfo::query()
            ->where(function ($q) use ($dateCarbon) {
                $q->orWhere(function ($q2) use ($dateCarbon) {
                    $q2->where('type', MoneyInfo::VOUCHER_SERVICE)
                        ->whereBetween('date_action', [
                            $dateCarbon->copy()->subMonth()->startOfMonth()->startOfDay(),
                            $dateCarbon->copy()->subMonth()->endOfMonth()->endOfDay()
                        ]);
                });
                $q->orWhere(function ($q2) use ($dateCarbon) {
                    $q2->whereIn('type', [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT])
                        ->whereBetween('date_action', [
                            $dateCarbon->copy()->startOfMonth()->startOfDay(),
                            $dateCarbon->copy()->endOfMonth()->endOfDay()
                        ]);
                });
            })
            ->when(!empty($contractId), function ($q) use ($contractId) {
                $q->where('contract_id', $contractId);
            })
            ->when(!empty($contractIds), function ($q) use ($contractIds) {
                $q->whereIn('contract_id', $contractIds);
            });
        $user = User::query()->where('token', $token)->first();
        if (!$user) {
            return '<h1>Dữ liệu không hợp lệ</h1>';
        }

        $font = 1;
        $pay = clone $items;
        $discount = clone $items;
        $items = $items->get();
        $ids = $items->pluck('id')->toArray();
        $details = MoneyDetail::query()->whereIn('money_info_id', $ids)->get();
        $discount = $discount->sum('discount');
        $room = $contract->room;
        $pay = $pay->sum('pay');
        locale_set_default('vi_VN');
        $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);
        $text = null;
        $ownerId = $contract->hostel->owner_id;
        $config = Config::query()->where('owner_id', $ownerId)->first();
        if ($config) {
            $text = $config->voucher;
        }
        $configHostel = ConfigHostel::query()
            ->where('owner_id', $ownerId)
            ->where('hostel_id', $contract->hostel_id)
            ->first();

        if ($configHostel) {
            $text = $configHostel->voucher;
        }
        $item = $items->first();
        if ($request->has('web')) {
            $isPrint = null;
        } else {
            $isPrint = 1;
        }
        $notes = $items->pluck('note')->toArray();

        if(!empty($contractIds))
        {
            $contracts = Contract::query()->whereIn('id', $contractIds)->get();
            $type = 1;
            return view('admin.money.bill_contracts_v2', compact('dateCarbon','type', 'contracts','item','items', 'notes', 'details', 'pay', 'f', 'font', 'text', 'discount', 'isPrint'));
        }

        return view('admin.money.bill_v2', compact('item', 'notes', 'details', 'pay', 'f', 'font', 'text', 'discount', 'isPrint'));

    }


    public function printAllBillContractUnpaid($id, Request $request)
    {
        $font = 1;
        $token = $request->input('token');
        $user = User::query()->where('token', $token)->first();
        if (!$user) {
            return redirect()->to(url('/'));
        }
        $item = Contract::find($id);
        if (!$item) {
            return '<h1>Hợp đồng không tồn tại</h1>';
        }
        $items = MoneyInfo::query()
            ->where('room_id', $item->room_id)
            ->where('contract_id', $item->id)
            ->where('remain', '<>', 0);
        $idItems = clone $items;
        $ids = $idItems->pluck('id')->toArray();
        $details = MoneyDetail::query()->whereIn('money_info_id', $ids)->with('moneyInfo')->get();
        //$room = $item->room;
        $payItems = clone $items;
        $discountItems = clone $items;
        $pay = $payItems->sum('pay');
        $discount = $discountItems->sum('discount');
        locale_set_default('vi_VN');

        $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);

        $text = null;
        $isPrint = 1;
        $config = Config::query()->where('owner_id', $user->id)->first();
        $ownerId = $user->id;
        if ($user->type == User::STAFF) {
            $config = Config::query()->where('owner_id', $user->staff_owner_id)->first();
            $ownerId = $user->staff_owner_id;
        }
        if ($user->type == User::RENTER) {
            $renterRoom = RenterRoom::query()
                ->where('user_id', $user->id)
                ->latest()
                ->first();
            if ($renterRoom) {
                $hostel = $renterRoom->hostel;
                if ($hostel) {
                    $config = Config::query()->where('owner_id', $hostel->owner_id)->first();
                    $ownerId = $hostel->owner_id;
                }
            }
        }

        if ($config) {
            $text = $config->voucher;
        }
        $configHostel = ConfigHostel::query()
            ->where('owner_id', $ownerId)
            ->where('hostel_id', $item->hostel_id)
            ->first();
        if ($configHostel) {
            $text = $configHostel->voucher;
        }
        $notes = $items->pluck('note')->toArray();
        return view('admin.money.bill_v2', compact('item', 'notes', 'details', 'pay', 'f', 'font', 'text', 'discount', 'isPrint'));
    }

    public function printAllUnpaidContractByHostel($id, Request $request)
    {
        $token = $request->input('token');
        $user = User::query()->where('token', $token)->first();
        if (!$user) {
            return redirect()->to(url('/'));
        }
        $contracts = Contract::select('contracts.*', 'rooms.name as room_name')
            ->where('contracts.hostel_id', $id)
            ->where('contracts.status', '<>', Contract::LIQUIDATED)
            ->join('rooms', 'contracts.room_id', 'rooms.id')
            ->orderBy('room_name', 'asc')
            ->get();

        $isPrint = 1;

        $itemArr = [];
        $detailArr = [];
        $payArr = [];
        $fArr = [];
        $textArr = [];
        $discountArr = [];
        foreach ($contracts as $contract) {

            if ($contract->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                $moneyInfos = MoneyInfo::query()->where('room_id', $contract->room_id)->pluck('id')->toArray();
                $paid = Transaction::query()->whereIn('money_info_id', $moneyInfos)->where('type', CollectSpend::COLLECT)->sum('amount');
                $amount = MoneyInfo::query()->where('room_id', $contract->room_id)->sum('amount');
                $discount = MoneyInfo::query()->where('room_id', $contract->room_id)->sum('discount');
                $remain = $amount - $paid - $discount;

                if ($remain > 0) {

                    $items = MoneyInfo::query()
                        ->where('room_id', $contract->room_id)
                        ->where('contract_id', $contract->id)
                        ->where('remain', '<>', 0)
                        ->orderBy('date_action');
                    $idItems = clone $items;
                    $ids = $idItems->pluck('id')->toArray();
                    $details = MoneyDetail::query()->whereIn('money_info_id', $ids)->with('moneyInfo')->get();
                    //$room = $item->room;

                    $payItems = clone $items;
                    $pay = $payItems->sum('pay');
                    $discountItems = clone $items;
                    $discountValue = $discountItems->sum('discount');

                    locale_set_default('vi_VN');

                    $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);

                    $text = null;
                    $config = Config::query()->where('owner_id', $user->id)->first();
                    $ownerId = $user->id;
                    if ($user->type == User::STAFF) {
                        $ownerId = $user->staff_owner_id;
                        $config = Config::query()->where('owner_id', $user->staff_owner_id)->first();
                    }
                    if ($config) {
                        $text = $config->voucher;
                    }

                    $configHostel = ConfigHostel::query()
                        ->where('owner_id', $ownerId)
                        ->where('hostel_id', $contract->hostel_id)
                        ->first();
                    if ($configHostel) {
                        $text = $configHostel->voucher;
                    }

                    $itemArr[] = $contract;
                    $detailArr[] = $details;
                    $payArr[] = $pay;
                    $textArr[] = $text;
                    $fArr[] = $f;
                    $discountArr[] = $discount;

                }
            } elseif ($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                $moneyInfos = MoneyInfo::query()->where('room_id', $contract->room_id)->where('bed_id', $contract->bed_id)->pluck('id')->toArray();
                $paid = Transaction::query()->whereIn('money_info_id', $moneyInfos)->where('type', CollectSpend::COLLECT)->sum('amount');
                $amount = MoneyInfo::query()->where('room_id', $contract->room_id)->where('bed_id', $contract->bed_id)->sum('amount');
                $discount = MoneyInfo::query()->where('room_id', $contract->room_id)->where('bed_id', $contract->bed_id)->sum('discount');
                $remain = $amount - $paid - $discount;
                if ($remain > 0) {
                    $items = MoneyInfo::query()
                        ->where('room_id', $contract->room_id)
                        ->where('contract_id', $contract->id)
                        ->where('remain', '<>', 0)
                        ->orderBy('date_action');
                    $idItems = clone $items;
                    $ids = $idItems->pluck('id')->toArray();
                    $details = MoneyDetail::query()->whereIn('money_info_id', $ids)->with('moneyInfo')->get();
                    //$room = $item->room;

                    $payItems = clone $items;
                    $pay = $payItems->sum('pay');
                    $discountItems = clone $items;
                    $discountValue = $discountItems->sum('discount');

                    locale_set_default('vi_VN');

                    $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);

                    $text = null;
                    $config = Config::query()->where('owner_id', $user->id)->first();
                    $ownerId = $user->id;
                    if ($user->type == User::STAFF) {
                        $ownerId = $user->staff_owner_id;
                        $config = Config::query()->where('owner_id', $user->staff_owner_id)->first();
                    }
                    if ($config) {
                        $text = $config->voucher;
                    }

                    $configHostel = ConfigHostel::query()
                        ->where('owner_id', $ownerId)
                        ->where('hostel_id', $contract->hostel_id)
                        ->first();
                    if ($configHostel) {
                        $text = $configHostel->voucher;
                    }

                    $itemArr[] = $contract;
                    $detailArr[] = $details;
                    $payArr[] = $pay;
                    $textArr[] = $text;
                    $fArr[] = $f;
                    $discountArr[] = $discount;
                }
            }
        }

        return view('admin.money.bill_all_unpaid_v2', compact('itemArr', 'detailArr', 'payArr', 'fArr', 'textArr', 'discountArr', 'isPrint'));
    }

    public function printAllUnpaidContractByHostelRoom($id, $room_id, Request $request)
    {
        $roomId = $room_id;
        $token = $request->input('token');
        $user = User::query()->where('token', $token)->first();
        if (!$user) {
            return redirect()->to(url('/'));
        }
        $contracts = Contract::query()->select('contracts.*', 'rooms.name as room_name')
            ->where('contracts.hostel_id', $id)
            ->where('contracts.status', '<>', Contract::LIQUIDATED)
            ->join('rooms', 'contracts.room_id', 'rooms.id');

        if (!empty($roomId)) {
            $contracts = $contracts->where('contracts.room_id', $roomId);
        }
        $contracts = $contracts->orderBy('room_name', 'asc')->get();

        $isPrint = 1;

        $itemArr = [];
        $detailArr = [];
        $payArr = [];
        $fArr = [];
        $textArr = [];
        $discountArr = [];

        foreach ($contracts as $contract) {
            if ($contract->hostel->type_rent == Hostel::TYPE_RENT_ALL) {
                $moneyInfos = MoneyInfo::query()->where('room_id', $contract->room_id)->pluck('id')->toArray();
                $paid = Transaction::query()->whereIn('money_info_id', $moneyInfos)->where('type', CollectSpend::COLLECT)->sum('amount');
                $amount = MoneyInfo::query()->where('room_id', $contract->room_id)->sum('amount');
                $discount = MoneyInfo::query()->where('room_id', $contract->room_id)->sum('discount');
                $remain = $amount - $paid - $discount;

                if ($remain > 0) {

                    $items = MoneyInfo::query()
                        ->where('room_id', $contract->room_id)
                        ->where('contract_id', $contract->id)
                        ->where('remain', '<>', 0)
                        ->orderBy('date_action');
                    $idItems = clone $items;
                    $ids = $idItems->pluck('id')->toArray();
                    $details = MoneyDetail::query()->whereIn('money_info_id', $ids)->with('moneyInfo')->get();
                    //$room = $item->room;

                    $payItems = clone $items;
                    $pay = $payItems->sum('pay');
                    $discountItems = clone $items;
                    $discountValue = $discountItems->sum('discount');

                    locale_set_default('vi_VN');

                    $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);

                    $text = null;
                    $config = Config::query()->where('owner_id', $user->id)->first();
                    $ownerId = $user->id;
                    if ($user->type == User::STAFF) {
                        $ownerId = $user->staff_owner_id;
                        $config = Config::query()->where('owner_id', $user->staff_owner_id)->first();
                    }
                    if ($config) {
                        $text = $config->voucher;
                    }

                    $configHostel = ConfigHostel::query()
                        ->where('owner_id', $ownerId)
                        ->where('hostel_id', $contract->hostel_id)
                        ->first();
                    if ($configHostel) {
                        $text = $configHostel->voucher;
                    }


                    $itemArr[] = $contract;
                    $detailArr[] = $details;
                    $payArr[] = $pay;
                    $textArr[] = $text;
                    $fArr[] = $f;
                    $discountArr[] = $discount;

                }
            } elseif ($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                $moneyInfos = MoneyInfo::query()->where('room_id', $contract->room_id)->where('bed_id', $contract->bed_id)->pluck('id')->toArray();
                $paid = Transaction::query()->whereIn('money_info_id', $moneyInfos)->where('type', CollectSpend::COLLECT)->sum('amount');
                $amount = MoneyInfo::query()->where('room_id', $contract->room_id)->where('bed_id', $contract->bed_id)->sum('amount');
                $discount = MoneyInfo::query()->where('room_id', $contract->room_id)->where('bed_id', $contract->bed_id)->sum('discount');
                $remain = $amount - $paid - $discount;
                if ($remain > 0) {
                    $items = MoneyInfo::query()
                        ->where('room_id', $contract->room_id)
                        ->where('contract_id', $contract->id)
                        ->where('remain', '<>', 0)
                        ->orderBy('date_action');
                    $idItems = clone $items;
                    $ids = $idItems->pluck('id')->toArray();
                    $details = MoneyDetail::query()->whereIn('money_info_id', $ids)->with('moneyInfo')->get();
                    //$room = $item->room;

                    $payItems = clone $items;
                    $pay = $payItems->sum('pay');
                    $discountItems = clone $items;
                    $discountValue = $discountItems->sum('discount');

                    locale_set_default('vi_VN');

                    $f = new \NumberFormatter('vi_VN', \NumberFormatter::SPELLOUT);

                    $text = null;
                    $config = Config::query()->where('owner_id', $user->id)->first();

                    $ownerId = $user->id;
                    if ($user->type == User::STAFF) {
                        $ownerId = $user->staff_owner_id;
                        $config = Config::query()->where('owner_id', $user->staff_owner_id)->first();
                    }
                    if ($config) {
                        $text = $config->voucher;
                    }

                    $configHostel = ConfigHostel::query()
                        ->where('owner_id', $ownerId)
                        ->where('hostel_id', $contract->hostel_id)
                        ->first();
                    if ($configHostel) {
                        $text = $configHostel->voucher;
                    }


                    $itemArr[] = $contract;
                    $detailArr[] = $details;
                    $payArr[] = $pay;
                    $textArr[] = $text;
                    $fArr[] = $f;
                    $discountArr[] = $discount;
                }
            }
        }


        return view('admin.money.bill_all_unpaid_v2', compact('itemArr', 'detailArr', 'payArr', 'fArr', 'textArr', 'discountArr', 'isPrint'));
    }
}
