<?php

namespace App\Http\Controllers\Backend2;

use App\Components\Functions;
use App\Events\LogAction;
use App\Http\Controllers\Backend\AdminController;
use App\Jobs\ExportMoneyInfo;
use App\Jobs\ImportMoneyInfo;
use App\Jobs\SendMailContractMoney;
use App\Jobs\SendMailRentersMoney;
use App\Jobs\SendMessageBotV2;
use App\Jobs\SendMessageV2;
use App\Jobs\SendNotificationMessage;
use App\Models\CollectSpend;
use App\Models\CollectSpendCycle;
use App\Models\CollectSpendFile;
use App\Models\Config;
use App\Models\ConfigHostel;
use App\Models\Contract;
use App\Models\Conversation;
use App\Models\ElectricWater;
use App\Models\Hostel;
use App\Models\HostelFee;
use App\Models\Message;
use App\Models\MoneyDetail;
use App\Models\MoneyInfo;
use App\Models\Receiver;
use App\Models\Renter;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\SendZaloLog;
use App\Models\Statistic;
use App\Models\StatisticLog;
use App\Models\Transaction;
use App\Models\TypeCollect;
use App\Models\TypeSpend;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use MongoDB\BSON\Type;
use Pusher\Pusher;
use Yajra\Datatables\Datatables;
use DB;

class MoneyController extends AdminController
{
    //
    protected $pusher;

    public function __construct()
    {
        parent::__construct();

        $this->pusher = \PusherService::getClient();
    }

    public function getMoneyByAttributeView()
    {
        return view('admin2.money.index');
    }

    public function sendMessageInvoiceZalo(Request $request)
    {
        $contractId = $request->input('contract_id');
        $month = $request->input('month');


        $owner = \auth('backend')->user();
        if (\auth('backend')->user()->type == User::STAFF) {
            $owner = \auth('backend')->user()->owner;
        }

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

        $contract = Contract::find($contractId);
        $room = $contract->room;
        $hostel = $contract->hostel;

        $hostelName = $hostel->name;
        $roomName = $room->name;
        $customerName = $contract->name;


        $moneyInfos = MoneyInfo::query()
            ->where('contract_id', $contractId)
            ->when($owner->type_display_money_info == User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH, function ($q) use ($month) {
                $q->where(function ($q) use ($month) {
                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->startOfMonth(),
                            $month->copy()->endOfMonth()
                        ]);
                        $q->whereIn('type', [
                            MoneyInfo::VOUCHER_CONTRACT,
                            MoneyInfo::VOUCHER_ROOM_PRICE
                        ]);
                    });

                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->subMonth()->startOfMonth(),
                            $month->copy()->subMonth()->endOfMonth()
                        ]);
                        $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                    });
                });

            }, function ($q) use ($month) {

                $q->whereBetween('date_action', [
                    $month->copy()->startOfMonth(),
                    $month->copy()->endOfMonth()
                ]);

            })->get();

        $amount = $moneyInfos->sum('remain');

        if ($amount <= 0) {
            return response([
                'status' => 0,
                'message' => 'Không thể gửi tin nhắn do không còn nợ trên các hóa đơn'
            ]);
        }

        if ($owner->type_display_money_info == \App\User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH) {
            $invoicePath = 'p-m-s?contract_id=' . $contract->id . '&month=' . $month->copy()->format('m/Y') . '&token=' . $owner->token;
        } else {
            $invoicePath = 'p-m?contract_id=' . $contract->id . '&month=' . $month->copy()->format('m/Y') . '&token=' . $owner->token;
        }
        

        $phone = $contract->phone;
        $phone = ltrim($phone, '0');
        $phone = '84' . $phone;
        $responseMessage = Functions::sendMessageInvoiceZns([
            'phone' => $phone,
            'room_name' => $roomName,
            'amount' => $amount,
            'invoice_path' => $invoicePath,
            'customer_name' => $customerName,
            'hostel_name' => $hostelName,
            'hostel_id' => $hostel->id,
            'room_id' => $room->id
        ]);
        

        if (empty($responseMessage)) {

            return response([
                'status' => 0,
                'message' => 'Bạn đã hết số lượt gửi zalo',
                'ref'=> $responseMessage
            ]);
        }

        if (empty($responseMessage['error'])) {

            return response([
                'status' => 1,
                'message' => 'Đã gửi tin nhắn Zalo tới: ' . $contract->name . ', SĐT: ' . $contract->phone,
                'ref'=> $responseMessage
            ]);
        }
        return response([
            'status' => 1,
            'message' => $responseMessage['message'],
            'ref'=> $responseMessage
        ]);

    }

    public function importMoneyInfoService(Request $request)
    {
        $file = $request->file('file');

        if (!\File::exists(public_path('files'))) {
            \File::makeDirectory(public_path('files'), '0777', true);
        }

        $filename = time() . '_' . mt_rand(1111, 9999) . '_' . str_slug($request->file('file')->getClientOriginalName());
        $filename = $filename . '.' . $file->extension();
        $request->file('file')->move(public_path('files'), $filename);

        $filePath = public_path('files/' . $filename);
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $userId = \auth('backend')->user()->id;

        dispatch(new ImportMoneyInfo($filePath, $ownerId, $userId));
        return response([
            'status' => 1,
            'message' => 'Hệ thống đang tiến hành xử lý ban nhe'
        ]);
    }

    public function getVoucherContractView(Request $request)
    {
        $month = $request->input('month');
        $owner = \auth('backend')->user();
        if (\auth('backend')->user()->type == User::STAFF) {
            $owner = auth('backend')->user()->owner;
        }
        $typeDisplay = $owner->type_display_money_info;
        $date = Carbon::createFromFormat('d/m/Y', '01/' . $month);

        // $typeDisplay = User::TYPE_DISPLAY_MONEY_INFO_CURRENT_MONTH;
        if ($typeDisplay == User::TYPE_DISPLAY_MONEY_INFO_CURRENT_MONTH) {
            $messages = [
                'all' => 'Xóa tất cả hóa đơn tháng ' . $month,
                'room_price' => 'Xóa tất cả hóa đơn tiền nhà tháng ' . $month,
                'service' => 'Xóa tất cả hóa đơn tiền dịch vụ tháng ' . $month,
            ];
        } else {
            $messages = [
                'all' => 'Xóa tất cả hóa đơn tiền nhà tháng ' . $month . ' và tiền dịch vụ tháng ' . $date->copy()->subMonth()->format('m/Y'),
                'room_price' => 'Xóa tất cả hóa đơn tiền nhà tháng ' . $month,
                'service' => 'Xóa tất cả hóa đơn tiền dịch vụ tháng ' . $date->copy()->subMonth()->format('m/Y'),
            ];
        }

        return response([
            'status' => 1,
            'data' => view('admin2.money.delete_voucher_contract', compact('messages'))->render()
        ]);
    }

    public function deleteVoucherContractsByType(Request $request)
    {
        $date = $request->input('month');
        $month = Carbon::createFromFormat('d/m/Y', '01/' . $date);
        $type = $request->input('type');
        $owner = \auth('backend')->user();
        if (\auth('backend')->user()->type == User::STAFF) {
            $owner = auth('backend')->user()->owner;
        }
        $contractIds = $request->input('contract_ids');
        if (empty($contractIds)) {
            return response([
                'status' => 0,
                'message' => 'Bạn phải chọn hợp đồng để xóa hóa đơn'
            ]);
        }

        $moneyInfos = MoneyInfo::query()
            ->whereIn('contract_id', $contractIds)
            ->when($owner->type_display_money_info == User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH, function ($q) use ($month) {
                $q->where(function ($q) use ($month) {
                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->startOfMonth(),
                            $month->copy()->endOfMonth()
                        ]);
                        $q->whereIn('type', [
                            MoneyInfo::VOUCHER_CONTRACT,
                            MoneyInfo::VOUCHER_ROOM_PRICE
                        ]);
                    });

                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->subMonth()->startOfMonth(),
                            $month->copy()->subMonth()->endOfMonth()
                        ]);
                        $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                    });
                });

            }, function ($q) use ($month) {

                $q->whereBetween('date_action', [
                    $month->copy()->startOfMonth(),
                    $month->copy()->endOfMonth()
                ]);

            });
        $items = null;
        if ($type == 'all') {
            $items = clone $moneyInfos;
            $items = $items->get();
            $moneyInfos->delete();
        } else if ($type == 'room_price') {
            $moneyInfos = $moneyInfos->whereIn('type', [
                MoneyInfo::VOUCHER_ROOM_PRICE,
                MoneyInfo::VOUCHER_CONTRACT
            ]);
            $items = clone $moneyInfos;
            $items = $items->get();
            $moneyInfos->delete();
        } else if ($type == 'service') {
            $moneyInfos = $moneyInfos->where('type', MoneyInfo::VOUCHER_SERVICE);
            $items = clone $moneyInfos;
            $items = $items->get();
            $moneyInfos->delete();
        }

        if ($items) {
            $user = Functions::getCurrentUser();
            foreach ($items as $moneyInfo) {
                $desc = '{' . optional($user)->name . '} xóa hóa đơn mã {' . $moneyInfo->name . '} phòng {' . $moneyInfo->room->name . '} nhà {' . $moneyInfo->room->hostel->name . '}';
                if ($moneyInfo->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                    $desc = '{' . optional($user)->name . '} xóa hóa đơn mã {' . $moneyInfo->name . '} giường {' . optional(optional($moneyInfo->contract)->bed)->name . '} phòng {' . $moneyInfo->room->name . '} nhà {' . $moneyInfo->room->hostel->name . '}';
                }

                event(new LogAction([
                    'type' => 'delete-money-info',
                    'user_id' => optional($user)->id,
                    'object_id' => $moneyInfo->id,
                    'hostel_id' => $moneyInfo->hostel_id,
                    'room_id' => $moneyInfo->room_id,
                    'properties' => $moneyInfo->toArray(),
                    'desc' => $desc
                ]));
            }
        }


        return response([
            'status' => 1,
            'message' => 'Xóa thành công'
        ]);
    }


    public function getCpByAttributeView()
    {
        $ownerId = \auth('backend')->user()->id;
        if (\auth('backend')->user()->type == User::STAFF) {
            $ownerId = \auth('backend')->user()->staff_owner_id;
        }
        $users = User::query()
            ->where('id', $ownerId)
            ->orWhere('staff_owner_id', $ownerId)
            ->get();

        return view('admin2.money.index_2', compact('users'));
    }

    public function getStatisticByAttributeView()
    {
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            if (auth('backend')->user()->cannot('view-stat')) {
                return redirect()->to(url('admin2/room/list'));
            }
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $typeSpends = TypeSpend::query()
            ->where('owner_id', $ownerId)
            ->get();

        return view('admin2.money.statistic', compact('typeSpends'));
    }

    public function sendMessageMoneyInfo(Request $request)
    {
        $moneyInfoId = $request->input('money_info_id');
        $fromUser = auth('backend')->user()->id;
        $moneyInfo = MoneyInfo::find($moneyInfoId);
        if (!$moneyInfo) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $room = $moneyInfo->room;
        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }
        $details = MoneyDetail::where('money_info_id', $moneyInfoId)->get();
        if ($details->count() <= 0) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $message = view('admin2.money.message', compact('moneyInfo', 'details'))->render();
        $conversation = Conversation::where('room_id', $room->id)
            ->whereNotNull('hostel_id')
            ->first();

        if (!$conversation) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $message = Message::create([
            'content' => $message,
            'conversation_id' => $conversation->id,
            'type' => Message::TYPE_TEXT,
            'from' => $fromUser
        ]);

        $conversation->update([
            'last_message_id' => $message->id,
            'last_message_time' => Carbon::now()->toDateTimeString()
        ]);

        $messageArr = $message->toArray();
        $content = $message->content;
        $userOnlineArr = [];

        if (isset($usersChannel['result'])) {
            if (isset($usersChannel['result']['users'])) {
                foreach ($usersChannel['result']['users'] as $item) {
                    $userIdOnline = $item['id'];
                    $userOnlineArr[] = $userIdOnline;
                }
            }
        }

        $membersArr = \DB::table('user_conversations')->where('conversation_id', $conversation->id)->pluck('user_id')->toArray();

        foreach ($membersArr as $userId) {


            $q = \DB::table('user_conversations')
                ->where('conversation_id', $conversation->id)
                ->where('user_id', $userId);

            if (in_array($userId, $userOnlineArr)) {
                $q->update([
                    'is_read_last_message' => 1
                ]);
            } else {
                $q->update([
                    'is_read_last_message' => 0
                ]);
            }

            if ($message->type == Message::TYPE_IMAGE || $message->type == Message::TYPE_SYSTEM) {
                if ($userId == $fromUser) {
                    if ($message->type == Message::TYPE_IMAGE) {
                        $content = 'Bạn đã gửi một ảnh';
                    } else {
                        $content = 'Bạn ' . $content;
                    }
                } else {
                    $fromUser = $message->fromUser;
                    if ($fromUser) {
                        if ($message->type == Message::TYPE_IMAGE) {
                            $content = $fromUser->name_text . ' đã gửi một ảnh';
                        } else {
                            $content = $fromUser->name_text . ' ' . $content;
                        }
                    }
                }

            }

            $messageArr['content'] = $content;
            $this->pusher->trigger('chat-' . $userId, 'new-message', $messageArr);
            dispatch(new SendNotificationMessage($userId, $messageArr));


        }

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    public function sendMessageMoneyInfo2(Request $request)
    {
        $moneyInfoId = $request->input('money_info_id');
        $moneyInfo = MoneyInfo::find($moneyInfoId);
        if (!$moneyInfo) {
            return redirect()->back()->with('error', 'Dữ liệu không hợp lệ');
        };

        $room = $moneyInfo->room;
        if (!$room) {
            return redirect()->back()->with('error', 'Dữ liệu không hợp lệ');
        }
        $details = MoneyDetail::where('money_info_id', $moneyInfoId)->get();
        if ($details->count() <= 0) {
            return redirect()->back()->with('error', 'Dữ liệu không hợp lệ');
        }

        $message = view('admin2.money.message', compact('moneyInfo', 'details'))->render();

        return response([
            'status' => 1,
            'data' => [
                'room_id' => $room->id,
                'message' => $message
            ]
        ]);
    }

    public function settingSpend()
    {
        return view('admin2.money.setting_spend');
    }

    public function createSettingSpend()
    {
        return response([
            'status' => 1,
            'data' => view('admin2.money.add_setting_spend')->render()
        ]);
    }

    public function editSettingSpend(Request $request)
    {
        $id = $request->input('id');
        $item = TypeSpend::find($id);
        if (!$item) {
            return response([
                'status' => 0
            ]);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.money.edit_setting_spend', compact('item'))->render()
        ]);
    }

    public function deleteSettingSpend(Request $request)
    {
        $id = $request->id;
        $item = TypeSpend::find($id);
        if ($item) {

            $user = Functions::getCurrentUser();
            $desc = '{' . optional($user)->name . '} xóa loại phiếu chi {' . $item->name . '}';
            event(new LogAction([
                'type' => 'delete-type-spend',
                'user_id' => optional($user)->id,
                'object_id' => $item->id,
                'properties' => $item->toArray(),
                'desc' => $desc
            ]));
            $item->delete();
            return response([
                'status' => 1,
                'action' => 'Delete success!'
            ]);
        }


        return response([
            'status' => 0,
            'action' => 'Failed'
        ]);
    }

    public function settingCollect()
    {
        return view('admin2.money.setting_collect');
    }

    public function createSettingCollect()
    {
        return response([
            'status' => 1,
            'data' => view('admin2.money.add_setting_collect')->render()
        ]);
    }

    public function editSettingCollect(Request $request)
    {
        $id = $request->input('id');
        $item = TypeCollect::find($id);
        if (!$item) {
            return response([
                'status' => 0
            ]);
        }

        return response([
            'status' => 1,
            'data' => view('admin2.money.edit_setting_collect', compact('item'))->render()
        ]);
    }

    public function deleteSettingCollect(Request $request)
    {
        $id = $request->id;
        $item = TypeCollect::find($id);
        if ($item) {
            if (!$item->can_delete) {
                return response([
                    'status' => 0,
                    'message' => 'Không thể xóa bản ghi này'
                ]);
            }
            $item->delete();
            $user = Functions::getCurrentUser();
            $desc = '{' . optional($user)->name . '} xóa loại phiếu thu {' . $item->name . '}';
            event(new LogAction([
                'type' => 'delete-type-collect',
                'user_id' => optional($user)->id,
                'object_id' => $item->id,
                'properties' => $item->toArray(),
                'desc' => $desc
            ]));
        }

        return response([
            'status' => 0,
            'action' => 'Failed'
        ]);
    }

    public function getSettingCollectByAttribute(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $items = TypeCollect::query()->where('owner_id', $ownerId);

        return Datatables::of($items)
            ->addColumn('action', function ($item) {
                $retVal = '';
                $retVal .= '<a data-id="' . $item->id . '" href="#edit-setting-collect"  data-toggle="modal" class="btn btn-sm btn-outline btn-editable btn-edit purple"><i class="fa fa-edit"></i> Sửa</a>';
                if ($item->can_delete) {
                    $retVal .= '<a data-id="' . $item->id . '" data-href="' . url('admin2/money/delete-setting-collect') . '" class="btn btn-sm btn-outline btn-editable btn-delete dark black"><i class="fa fa-trash"></i> Xóa</a>';
                }
                if ($item->is_default == 0 || $item->is_default == null) {
                    return $retVal;
                }
            })->make(true);

    }

    public function getSettingSpendByAttribute(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $items = TypeSpend::query()->where('owner_id', $ownerId);

        return Datatables::of($items)
            ->addColumn('action', function ($item) {
                $retVal = '';
                $retVal .= '<a data-id="' . $item->id . '" href="#edit-setting-spend"  data-toggle="modal" class="btn btn-sm btn-outline btn-editable btn-edit purple"><i class="fa fa-edit"></i> Sửa</a>';
                $retVal .= '<a data-id="' . $item->id . '" data-href="' . url('admin2/money/delete-setting-spend') . '" class="btn btn-sm btn-outline btn-editable btn-delete dark black"><i class="fa fa-trash"></i> Xóa</a>';
                if ($item->is_default == 0 || $item->is_default == null) {
                    return $retVal;
                }
            })->make(true);

    }

    public function storeSettingSpend(Request $request)
    {
        $data = $request->all();
        if (auth('backend')->user()->type == User::OWNER) {
            $id = auth('backend')->user()->id;
        } else if (auth('backend')->user()->type == User::STAFF) {
            $id = auth('backend')->user()->staff_owner_id;
        }
        $data['owner_id'] = $id;
        $data['is_default'] = 0;
        TypeSpend::create($data);

        return response([
            'status' => 1,
            'message' => 'Success'
        ]);

    }

    public function updateSettingSpend(Request $request)
    {
        $data = $request->all();
        $id = $data['id'];
        $item = TypeSpend::find($id);
        if ($item) {
            $item->update($data);
        }

        $user = Functions::getCurrentUser();
        $desc = '{' . optional($user)->name . '} sửa loại phiếu chi {' . $item->name . '}';
        event(new LogAction([
            'type' => 'update-type-spend',
            'user_id' => optional($user)->id,
            'object_id' => $item->id,
            'properties' => $item->toArray(),
            'desc' => $desc
        ]));

        return response([
            'status' => 1,
            'message' => 'Success'
        ]);

    }

    public function storeSettingCollect(Request $request)
    {
        $data = $request->all();
        if (auth('backend')->user()->type == User::OWNER) {
            $id = auth('backend')->user()->id;
        } else if (auth('backend')->user()->type == User::STAFF) {
            $id = auth('backend')->user()->staff_owner_id;
        }
        $data['owner_id'] = $id;
        $item = TypeCollect::create($data);

        $user = Functions::getCurrentUser();
        $desc = '{' . optional($user)->name . '} thêm loại phiếu thu {' . $item->name . '}';
        event(new LogAction([
            'type' => 'create-type-collect',
            'user_id' => optional($user)->id,
            'object_id' => $item->id,
            'properties' => $item->toArray(),
            'desc' => $desc
        ]));

        return response([
            'status' => 1,
            'message' => 'Success'
        ]);

    }

    public function updateSettingCollect(Request $request)
    {
        $data = $request->all();
        $id = $data['id'];
        $item = TypeCollect::find($id);
        if ($item) {
            $item->update($data);
        }

        $user = Functions::getCurrentUser();
        $desc = '{' . optional($user)->name . '} sửa loại phiếu thu {' . $item->name . '}';
        event(new LogAction([
            'type' => 'update-type-collect',
            'user_id' => optional($user)->id,
            'object_id' => $item->id,
            'properties' => $item->toArray(),
            'desc' => $desc
        ]));

        return response([
            'status' => 1,
            'message' => 'Success'
        ]);

    }

    public function sendMailMoneyInfo(Request $request)
    {
        $moneyInfoId = $request->input('money_info_id');
        $moneyInfo = MoneyInfo::find($moneyInfoId);
        if (!$moneyInfo) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        $roomId = $moneyInfo->room_id;
        $room = Room::find($roomId);
        if (!$room) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        dispatch_now(new SendMailRentersMoney($moneyInfoId));

        return response([
            'status' => 1,
            'message' => 'Email đã được gửi đi'
        ]);
    }

    public function sendMailMoneyInfoContract(Request $request)
    {
        $contractIds = $request->input('contract_ids');
        $month = $request->input('month');
        $owner = \auth('backend')->user();
        if (\auth('backend')->user()->type == User::STAFF) {
            $owner = \auth('backend')->user()->owner;
        }

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

        if (empty($contractIds)) {
            return response([
                'status' => 0,
                'message' => 'Bạn phải chọn HĐ'
            ]);
        }

        $moneyInfos = MoneyInfo::query()
            ->whereIn('contract_id', $contractIds)
            ->when($owner->type_display_money_info == User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH, function ($q) use ($month) {
                $q->where(function ($q) use ($month) {
                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->startOfMonth(),
                            $month->copy()->endOfMonth()
                        ]);
                        $q->whereIn('type', [
                            MoneyInfo::VOUCHER_CONTRACT,
                            MoneyInfo::VOUCHER_ROOM_PRICE
                        ]);
                    });

                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->subMonth()->startOfMonth(),
                            $month->copy()->subMonth()->endOfMonth()
                        ]);
                        $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                    });
                });

            }, function ($q) use ($month) {

                $q->whereBetween('date_action', [
                    $month->copy()->startOfMonth(),
                    $month->copy()->endOfMonth()
                ]);

            })->get();

        foreach ($moneyInfos as $moneyInfo) {
            dispatch(new SendMailContractMoney($moneyInfo->id));
        }

        return response([
            'status' => 1,
            'message' => 'Email đã được gửi đi'
        ]);
    }

    public function sendZaloMoneyInfoContract(Request $request)
    {
        $contractIds = $request->input('contract_ids');
        $month = $request->input('month');
        $owner = \auth('backend')->user();
        if (\auth('backend')->user()->type == User::STAFF) {
            $owner = \auth('backend')->user()->owner;
        }

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

        if (empty($contractIds)) {
            return response([
                'status' => 0,
                'message' => 'Bạn phải chọn HĐ'
            ]);
        }

        foreach ($contractIds as $contractId) {

            $contract = Contract::find($contractId);
            $moneyInfos = MoneyInfo::query()
                ->where('contract_id', $contractId)
                ->when($owner->type_display_money_info == User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH, function ($q) use ($month) {
                    $q->where(function ($q) use ($month) {
                        $q->orWhere(function ($q) use ($month) {
                            $q->whereBetween('date_action', [
                                $month->copy()->startOfMonth(),
                                $month->copy()->endOfMonth()
                            ]);
                            $q->whereIn('type', [
                                MoneyInfo::VOUCHER_CONTRACT,
                                MoneyInfo::VOUCHER_ROOM_PRICE
                            ]);
                        });

                        $q->orWhere(function ($q) use ($month) {
                            $q->whereBetween('date_action', [
                                $month->copy()->subMonth()->startOfMonth(),
                                $month->copy()->subMonth()->endOfMonth()
                            ]);
                            $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                        });
                    });

                }, function ($q) use ($month) {

                    $q->whereBetween('date_action', [
                        $month->copy()->startOfMonth(),
                        $month->copy()->endOfMonth()
                    ]);

                })->get();


            $amount = $moneyInfos->sum('remain');

            if ($amount <= 0) {
                continue;
            }

            if ($owner->type_display_money_info == \App\User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH) {
                $invoicePath = 'p-m-s?contract_id=' . $contract->id . '&month=' . $month->copy()->format('m/Y') . '&token=' . $owner->token;
            } else {
                $invoicePath = 'p-m?contract_id=' . $contract->id . '&month=' . $month->copy()->format('m/Y') . '&token=' . $owner->token;
            }

            $roomName = $contract->room->name;
            $customerName = $contract->name;
            $hostelName = $contract->hostel->name;
            $phone = $contract->phone;
            $phone = ltrim($phone, '0');
            //  $phone='379263615';
            $phone = '84' . $phone;
            $responseMessage = Functions::sendMessageInvoiceZns([
                'phone' => $phone,
                'room_name' => $roomName,
                'amount' => $amount,
                'invoice_path' => $invoicePath,
                'customer_name' => $customerName,
                'hostel_name' => $hostelName,
                'hostel_id' => $contract->hostel->id,
                'room_id' => $contract->room->id
            ]);
            if (empty($responseMessage)) {
                return response([
                    'status' => 0,
                    'message' => 'Bạn đã hết số lượt gửi zalo'
                ]);
            }
        }

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }


    public function getStatByAttribute(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }

        $isStat = $request->input('is_stat');
        $isExport = $request->input('is_export');

        $items = Statistic::query()->selectRaw('statistics.*, hostels.name as hostel, rooms.name as room, concat(month, "/", year) as day')
            ->leftJoin('hostels', 'hostels.id', '=', 'statistics.hostel_id')
            ->leftJoin('rooms', 'rooms.id', '=', 'statistics.room_id')
            ->where('statistics.owner_id', $ownerId);

        $hostelArrs = Hostel::query()->where('owner_id', $ownerId)->pluck('id')->toArray();
        if (auth('backend')->user()->type == User::STAFF) {
            $hostelArrs = Functions::getHostelArrStaff();
        }
        $hostel = $request->input('hostel_id');

        if (!empty($hostel)) {
            $items = $items->where('statistics.hostel_id', $hostel);
        } else {

            $items = $items->whereIn('statistics.hostel_id', $hostelArrs);
        }

        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        if (!empty($startDate)) {
            $startDate = Carbon::createFromFormat('d/m/Y', '1/' . $startDate)->startOfMonth()->toDateTimeString();
            $items = $items->where('statistics.date_action', '>=', $startDate);
        }

        if (!empty($endDate)) {
            $endDate = Carbon::createFromFormat('d/m/Y', '1/' . $endDate)->endOfMonth()->toDateTimeString();
            $items = $items->where('statistics.date_action', '<=', $endDate);
        }

        $type = $request->input('type');

        $roomId = $request->input('room_id');
        if (!empty($roomId)) {
            $items = $items->where('statistics.room_id', $roomId);
        }

        if (is_array($type)) {

            $items = $items->where(function ($q) use ($type) {
                $q->whereIn('statistics.type', $type);
                $q->orWhereNull('statistics.type');
            });
            // $items = $items->whereIn('statistics.type', $type);
        }


        if ($isStat == 1) {

            $collect = 0;
            $spend = 0;

            $itemsCollect = clone $items;
            $itemsSpend = clone $items;
            $collect = $itemsCollect->where('type_collect_spend', CollectSpend::COLLECT)->sum('amount');
            $spend = $itemsSpend->where('type_collect_spend', CollectSpend::SPEND)->sum('amount');

            return response([
                'status' => 1,
                'data' => view('admin2.money.stat_2', compact('collect', 'spend'))->render()
            ]);
        }

        if ($isExport == 1) {
            $itemsExcel = clone $items;
            $itemsExcel = $itemsExcel->orderBy('created_at', 'desc')->get();

            $responseArr = [];

            foreach ($itemsExcel as $itemE) {
                $itemArr['Mã hóa đơn'] = $itemE->money_info_code;
                $itemArr['Mã phiếu chi'] = $itemE->collect_spend_code;
                $itemArr['Số tiền'] = $itemE->amount;
                $itemArr['Loại thu chi'] = strip_tags($itemE->type_collect_spend_text);
                $itemArr['Mục đích thu chi'] = strip_tags($itemE->type_text);
                $itemArr['Nhà trọ'] = $itemE->hostel;
                $itemArr['Phòng trọ'] = $itemE->room;
                $itemArr['Thời gian'] = $itemE->created_at->format('d/m/Y H:i');
                $responseArr[] = $itemArr;
            }

            $name = 'Thong-ke-kinh-doanh';

            return \Excel::create($name . '-' . time(), function ($excel) use ($responseArr, $name) {
                $excel->sheet($name, function ($sheet) use ($responseArr) {
                    $sheet->fromArray($responseArr);
                });
            })->download('xls');
        }


        return Datatables::of($items)
            ->addIndexColumn()
            ->editColumn('amount', function ($item) {
                return number_format($item->amount, 0, '.', '.');
            })
            ->editColumn('type_collect_spend', function ($item) {
                return $item->type_collect_spend_text;
            })
            ->editColumn('type', function ($item) {
                return $item->type_text;
            })
            ->editColumn('created_at', function ($item) {
                return $item->created_at->format('d/m/Y H:i');
            })
            ->make(true);
    }

    public function getStat2ByAttribute(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }

        $isStat = $request->input('is_stat');
        $isExport = $request->input('is_export');
        $type = $request->input('type');
        $typeSpend = $request->input('type_spend');

        $hostelArrs = Hostel::query()->where('owner_id', $ownerId)
            ->pluck('id')
            ->toArray();
        if (\auth('backend')->user()->type == User::STAFF) {
            $hostelArrs = Functions::getHostelArrStaff();
        }
        $items = StatisticLog::query()->select(DB::raw('statistic_logs.*, CONCAT(month,"/", year) AS date'))
            ->with([
                'hostel',
                'room',
                'collectSpend',
                'contract'
            ])
            ->where(function ($q) {
                $q->orWhereNull('collect_spend_id');
                $q->orWhere(function ($q) {
                    $q->has('collectSpend');
                });
            })
            ->leftJoin('collect_spends', 'statistic_logs.collect_spend_id', '=', 'collect_spends.id')
            ->where(function ($q) use ($hostelArrs, $ownerId) {
                $q->orWhereIn('statistic_logs.hostel_id', $hostelArrs);
                $q->orWhere('statistic_logs.owner_id', $ownerId);
            });


        $hostel = $request->input('hostel_id');

        if (!empty($hostel)) {
            $items = $items->where('statistic_logs.hostel_id', $hostel);
        } else {
        }

        $roomId = $request->input('room_id');
        if (!empty($roomId)) {
            $items = $items->where('statistic_logs.room_id', $roomId);
        }

        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        if (!empty($startDate)) {
            $startDate = Carbon::createFromFormat('d/m/Y', '1/' . $startDate)->startOfMonth();
            $startMonth = $startDate->copy()->month;
            $startYear = $startDate->copy()->year;

            $items->where(function ($q) use ($startDate) {
                $q->whereDate(DB::raw('STR_TO_DATE(CONCAT("1","-", `statistic_logs`.`month`, "-", `statistic_logs`.`year`), "%d-%m-%Y")'), '>=', $startDate->copy()->toDateString());

            });

            // $items = $items
        }

        if (!empty($endDate)) {
            $endDate = Carbon::createFromFormat('d/m/Y', '1/' . $endDate)->endOfMonth();
            $endMonth = $endDate->copy()->month;
            $endYear = $endDate->copy()->year;
            $items = $items->whereDate(DB::raw('STR_TO_DATE(CONCAT("1","-", `statistic_logs`.`month`, "-", `statistic_logs`.`year`),"%d-%m-%Y")'), '<=', $endDate->copy()->toDateString());
//            $items = $items->where('statistic_logs.month', '<=', $endMonth)
//                ->where('statistic_logs.year', '<=', $endYear);
        }


        if (is_array($typeSpend)) {
            $ownerTypeSpend = TypeSpend::query()->where('owner_id', $ownerId)->pluck('id')->toArray();
            if (count($typeSpend) == count($ownerTypeSpend)) {
                $typeSpend = [];
            }
        }

        if (empty($typeSpend)) {
            if (!is_array($typeSpend)) {
                if ($isExport != 1) {
                    $typeSpend = ['xyz'];
                }
            }
        }

        if (!empty($type) && empty($typeSpend)) {

            if ($type == MoneyInfo::VOUCHER_CONTRACT) {

                $items = $items->where(function ($q) {
                    $q->orwhereHas('moneyInfo', function ($q2) {
                        $q2->whereIn('type', [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT]);
                    });
                    $q->orWhereHas('collectSpend', function ($q2) {
                        $q2->where('type', CollectSpend::SPEND);
                    });
                });


            } else if ($type == MoneyInfo::VOUCHER_SERVICE) {

                $items = $items->where(function ($q) {
                    $q->orwhereHas('moneyInfo', function ($q2) {
                        $q2->where('type', MoneyInfo::VOUCHER_SERVICE);
                    });
                    $q->orWhereHas('collectSpend', function ($q2) {
                        $q2->where('type', CollectSpend::SPEND);
                    });
                });
            }
        }

        if (!empty($typeSpend)) {
            if (is_array($typeSpend)) {

                $items = $items->whereHas('collectSpend', function ($q) use ($typeSpend, $type) {
                    if (empty($type)) {
                        $q->where(function ($q2) use ($typeSpend, $type) {
                            $q2->orWhereIn('type_purpose', $typeSpend);
                            $q2->orWhere('type', CollectSpend::COLLECT);
                        });

                    } else {
                        $q->where(function ($q2) use ($typeSpend, $type) {

                            if ($type == MoneyInfo::VOUCHER_CONTRACT) {
                                $q2->where(function ($q3) use ($typeSpend) {
                                    $q3->orWhereIn('type_purpose', $typeSpend);
                                    $q3->orwhereHas('moneyInfo', function ($q) {
                                        $q->whereIn('type', [
                                            MoneyInfo::VOUCHER_ROOM_PRICE,
                                            MoneyInfo::VOUCHER_CONTRACT
                                        ]);
                                    });
                                });
                            } else if ($type == MoneyInfo::VOUCHER_SERVICE) {

                                $q2->where(function ($q3) use ($typeSpend) {
                                    $q3->orWhereIn('type_purpose', $typeSpend);
                                    $q3->orwhereHas('moneyInfo', function ($q) {
                                        $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                                    });
                                });
                            }
                        });

                        //$q->where( 'type_purpose', $typeSpend );
                    }
                });
            }

        }

        if (!($request->has('order'))) {
            $items = $items->orderBy('hostel_name', 'IS_NULL')->orderBy('hostel_name')->orderBy('order')->orderBy('room_name', 'IS_NULL')->orderBy('room_name');
        }

        //dd($items->toSql());


        if ($isStat == 1) {
            $itemsCollect = clone $items;
            $itemsSpend = clone $items;
            $collect = $itemsCollect->where('statistic_logs.type', CollectSpend::COLLECT)->sum('statistic_logs.amount');
            $spend = $itemsSpend->where('statistic_logs.type', CollectSpend::SPEND)->sum('statistic_logs.amount');

            return response([
                'status' => 1,
                'data' => view('admin2.money.stat_2', compact('collect', 'spend'))->render()
            ]);
        }


        if ($isExport == 1) {
            $itemsExcel = clone $items;
            $itemsExcel = $itemsExcel->orderBy('created_at', 'desc')->get();

            $responseArr = [];
            $i = 1;
            foreach ($itemsExcel as $itemE) {
                $itemArr['STT'] = $i++;
                $itemArr['Mã phiếu thu chi'] = !empty($itemE->collectSpend) ? $itemE->collectSpend->code : null;
                $itemArr['Số tiền'] = $itemE->amount;
                $itemArr['Loại thu chi'] = !empty($itemE->collectSpend) ? strip_tags($itemE->collectSpend->type_cp_text) : null;
                $itemArr['Loại phiếu'] = strip_tags($itemE->type_text);
                $itemArr['Ghi chú'] = $itemE->note;
                $itemArr['Nhà trọ'] = !empty($itemE->hostel) ? $itemE->hostel->name : null;
                $itemArr['Phòng trọ'] = !empty($itemE->room) ? $itemE->room->name : null;
                $itemArr['Hợp đồng'] = !empty($itemE->contract) ? $itemE->contract->code : null;
                $itemArr['Thời gian'] = $itemE->created_at->format('d/m/Y H:i');
                $responseArr[] = $itemArr;
            }

            $name = 'Thong-ke-kinh-doanh';

            return \Excel::create($name . '-' . time(), function ($excel) use ($responseArr, $name) {
                $excel->sheet($name, function ($sheet) use ($responseArr) {
                    $sheet->fromArray($responseArr);
                });
            })->download('xls');
        }


        return Datatables::of($items)
            ->addIndexColumn()
            ->filterColumn('collect_spend_id', function ($query, $keyword) {
                $query->whereHas('collectSpend', function ($q) use ($keyword) {
                    $q->where('code', 'LIKE', '%' . $keyword . '%');
                });

            })
            ->filterColumn('room_id', function ($query, $keyword) {
                $query->whereHas('room', function ($q) use ($keyword) {
                    $q->where('name', 'LIKE', '%' . $keyword . '%');
                });

            })
            ->filterColumn('hostel_id', function ($query, $keyword) {
                $query->whereHas('hostel', function ($q) use ($keyword) {
                    $q->where('name', 'LIKE', '%' . $keyword . '%');
                });

            })
            ->filterColumn('contract_id', function ($query, $keyword) {
                $query->whereHas('contract', function ($q) use ($keyword) {
                    $q->where('name', 'LIKE', '%' . $keyword . '%');
                });

            })
            ->filterColumn('date', function ($query, $keyword) {
                $query->where(function ($q) use ($keyword) {
                    $q->orWhere('month', $keyword);
                    $q->orWhere('year', $keyword);
                });

            })
            ->editColumn('amount', function ($item) {
                return number_format($item->amount, 0, '.', '.');
            })
            ->editColumn('room_id', function ($item) {
                if ($item->room) {
                    return $item->room->name;
                }
            })
            ->editColumn('hostel_id', function ($item) {
                if ($item->hostel) {
                    return $item->hostel->name;
                }
            })
            ->editColumn('collect_spend_id', function ($item) {
                if ($item->collectSpend) {
                    return $item->collectSpend->code;
                }
            })
            ->editColumn('contract_id', function ($item) {
                if ($item->contract) {
                    return $item->contract->name;
                }
            })
            ->editColumn('type', function ($item) {
                //	return $item->id;
                if ($item->collectSpend) {
                    return $item->collectSpend->type_text;
                } else {
                    return $item->type_text;
                }
            })
            ->make(true);
    }

    // Son viet
    public function spendView(Request $request)
    {
        if (auth('backend')->user()->cannot('add-spend')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }
        $ownerId = \auth('backend')->user()->id;
        if (\auth('backend')->user()->type == User::STAFF) {
            $ownerId = \auth('backend')->user()->staff_owner_id;
        }
        $type_spend = TypeSpend::query()
            ->where('type_spends.owner_id', $ownerId)
            ->get();

        return response([
            'status' => 1,
            'data' => view('admin2.money.spend', ['type_spend' => $type_spend,])->render(),
        ]);
    }

    public function collectView(Request $request)
    {
        if (auth('backend')->user()->cannot('add-collect')) {
            return response([
                'status' => 2,
                'message' => 'Bạn chưa được phân quyền thực hiện'
            ]);
        }

        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }

        $types = TypeCollect::query()
            ->where('owner_id', $ownerId)
            ->get();

        return response([
            'status' => 1,
            'data' => view('admin2.money.collect', compact('types'))->render()
        ]);
    }

    public function editSpendView(Request $request)
    {
        if (auth('backend')->user()->cannot('edit-spend')) {
            return response([
                'status' => 0,
                'message' => 'Bạn không có quyền thao tác'
            ]);
        }
        $id = $request->input('id');
        $item = CollectSpend::find($id);

        if ($item->type == CollectSpend::COLLECT) {
            $code = 'Cập nhật phiếu thu, mã ' . $item->code;
        } else {
            $code = 'Cập nhật phiếu chi, mã ' . $item->code;
        }

//        $id_user = Auth::id();
//        $ownerId = auth('backend')->user()->id;
//        $type_spend = \Illuminate\Support\Facades\DB::table('type_spends')
//            ->where('type_spends.owner_id', $ownerId)
//            ->get();
        $ownerId = \auth('backend')->user()->id;
        if (\auth('backend')->user()->type == User::STAFF) {
            $ownerId = \auth('backend')->user()->staff_owner_id;
        }
        $type_spend = TypeSpend::query()
            ->where('type_spends.owner_id', $ownerId)
            ->get();

        if ($item) {
            return response([
                'status' => 1,
                'data' => view('admin2.money.edit_collect_spend', compact('item', 'type_spend'))->render(),
                'code' => $code
            ]);
        }

        return response([
            'status' => 1,
            'data' => '',
            'code' => ''
        ]);
    }

    public function deleteCpFiles(Request $request)
    {
        CollectSpendFile::query()->where('id', $request->input('id'))
            ->delete();
        return response([
            'status' => 1,
            'message' => 'Xóa thành công'
        ]);

    }

    public function editCollectView(Request $request)
    {
        if (auth('backend')->user()->cannot('edit-collect')) {
            return response([
                'status' => 0,
                'message' => 'Bạn không có quyền thao tác'
            ]);
        }
        $id = $request->input('id');
        $item = CollectSpend::find($id);

        if ($item->type == CollectSpend::COLLECT) {
            $code = 'Cập nhật phiếu thu, mã ' . $item->code;
        } else {
            $code = 'Cập nhật phiếu chi, mã ' . $item->code;
        }


        if ($item) {

            $ownerId = auth('backend')->user()->id;
            if (auth('backend')->user()->type == User::STAFF) {
                $ownerId = auth('backend')->user()->staff_owner_id;
            }

            $types = TypeCollect::query()
                ->where('owner_id', $ownerId)
                ->get();

            return response([
                'status' => 1,
                'data' => view('admin2.money.edit_collect', compact('item', 'types'))->render(),
                'code' => $code
            ]);
        }

        return response([
            'status' => 1,
            'data' => '',
            'code' => ''
        ]);
    }

    public function receivers(Request $request)
    {
        $userId = auth('backend')->user()->id;
        $query = $request->input('q');

        $items = Receiver::query()
            ->where('name', 'LIKE', '%' . $query . '%')
            ->where('user_id', $userId)
            ->get()
            ->pluck('name')
            ->toArray();

        $returnArr = [];

        foreach ($items as $item) {
            $returnArr[] = [
                'name' => $item
            ];
        }

        return response($returnArr);
    }

    public function printVoucher(Request $request)
    {
        $voucherId = $request->input('id');
        $item = CollectSpend::find($voucherId);


        if (!$item) {
            return redirect()->back()->with('error', 'Dữ liệu không hợp lệ');
        }

//        if ($item->type == CollectSpend::SPEND) {
//
//            return view('admin2.money.print_voucher', compact('item'));
//        }
//
//        return view('admin2.money.print_voucher_collect', compact('item'));


        $owner = \auth('backend')->user();
        if (\auth('backend')->user()->type == User::STAFF) {
            $owner = \auth('backend')->user()->owner;
        }

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

        if ($item->type == CollectSpend::SPEND) {
            $voucherTemplate = $config->voucher_spend;

        } else {
            $voucherTemplate = $config->voucher_collect;
        }

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

        $voucherTemplate = str_replace('{HostelName}', optional($item->hostel)->name, $voucherTemplate);
        $voucherTemplate = str_replace('{HostelAddress}', optional($item->hostel)->address_text, $voucherTemplate);
        $voucherTemplate = str_replace('{OwnerPhone}', optional($item->hostel)->owner_phone, $voucherTemplate);
        $voucherTemplate = str_replace('{Customer}', $item->receiver, $voucherTemplate);
        $voucherTemplate = str_replace('{Payer}', $item->payer, $voucherTemplate);
        $voucherTemplate = str_replace('{MHDCode}', $item->money_info_name, $voucherTemplate);
        $voucherTemplate = str_replace('{Reason}', $item->name, $voucherTemplate);
        $voucherTemplate = str_replace('{Note}', $item->note, $voucherTemplate);
        $voucherTemplate = str_replace('{Code}', $item->code, $voucherTemplate);
        $voucherTemplate = str_replace('{Creator}', \auth('backend')->user()->name, $voucherTemplate);
        $voucherTemplate = str_replace('{VoucherDate}', $item->date_action->format('d/m/Y'), $voucherTemplate);
        $voucherTemplate = str_replace('{CreatedDate}', $item->created_at->format('d/m/Y'), $voucherTemplate);
        $voucherTemplate = str_replace('{Money}', number_format($item->amount, 0, '.', '.'), $voucherTemplate);
        $voucherTemplate = str_replace('{MoneyText}', $f->format($item->amount) . ' đồng', $voucherTemplate);
        $configHostel = null;
        if($item->hostel) {
            $configHostel = ConfigHostel::query()->where('hostel_id', $item->hostel->id)->first();
        }
        if(!$configHostel) {
            $configHostel = ConfigHostel::query()->where('hostel_id', $item->owner_id)->first();
        }

        if ($configHostel) {
            if (!empty($configHostel->signature)) {
                $signature = '<img style="max-width: 150px" src="https://itro.vn/files/' . $configHostel->signature . '" />';
                $voucherTemplate = str_replace('{Signature}', $signature, $voucherTemplate);
            }
        }

        if ($config) {
            if (!empty($config->logo)) {
                $voucherTemplate = str_replace('{Logo}', '<img src="/files/' . $config->logo . '" style="max-width: 100px" />', $voucherTemplate);
            } else {
                $voucherTemplate = str_replace('{Logo}', '<img src="/frontend3/assets/img/logo.png" style="max-width: 100px" />', $voucherTemplate);
            }
        } else {
            $voucherTemplate = str_replace('{Logo}', '<img src="/frontend3/assets/img/logo.png" style="max-width: 100px" />', $voucherTemplate);
        }


        return view('admin2.money.print_voucher_setting', compact('item', 'voucherTemplate'));

    }

    public function printAllUnpaidContract($id)
    {
        $item = Contract::find($id);

        $items = MoneyInfo::query()
            ->where('room_id', $item->room_id)
            ->where('contract_id', $item->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;
        $discount = $discountItems->sum('discount');

        locale_set_default('vi_VN');

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

        $text = null;
        $config = Config::query()->where('owner_id', auth('backend')->user()->id)->first();
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $config = Config::query()->where('owner_id', auth('backend')->user()->staff_owner_id)->first();
            $ownerId = auth('backend')->user()->staff_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;
        }

        if (auth('backend')->user()->id == 6875 || auth('backend')->user()->staff_owner_id == 6875) {
            return view('admin2.money.bill_dung_eng', compact('item', 'details', 'pay', 'f', 'text', 'discount'));
        }
        $notes = $items->pluck('note')->toArray();

        if (auth('backend')->user()->id == 16088 || auth('backend')->user()->staff_owner_id == 16088) {
            return view('admin.money.bill_v2_16088', compact('item', 'details', 'pay', 'f', 'text', 'discount', 'notes'));
        }

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

    public function printAllUnpaidContractByHostel($id)
    {
        $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')
            ->orderBy('room_name', 'asc')
            ->get();


        $itemArr = [];
        $detailArr = [];
        $payArr = [];
        $fArr = [];
        $textArr = [];
        $discountArr = [];
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        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', auth('backend')->user()->id)->first();
                    if (auth('backend')->user()->type == User::STAFF) {
                        $config = Config::query()->where('owner_id', auth('backend')->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('contract_id', $contract->id)->get();
                $paid = $moneyInfos->sum('pay');
                $amount = $moneyInfos->sum('amount');
                $discount = $moneyInfos->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', auth('backend')->user()->id)->first();
                    if (auth('backend')->user()->type == User::STAFF) {
                        $config = Config::query()->where('owner_id', auth('backend')->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;
                }
            }
        }
        if (auth('backend')->user()->id == 16088 || auth('backend')->user()->staff_owner_id == 16088) {
            return view('admin.money.bill_all_unpaid_v2_16088', compact('itemArr', 'detailArr', 'payArr', 'fArr', 'textArr', 'discountArr'));
        }

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

    public function getMoneyByAttribute(Request $request)
    {
        $type = $request->input('type');
        $ownerId = auth('backend')->user()->id;

        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $items = CollectSpend::query()
            ->with('contract')
            ->with('room')
            ->with('typeCollect')
            ->when(!$request->has('order'), function ($q) {
                $q->orderBy('date_action', 'desc');
            });

        $hostelArrs = Hostel::query()->where('owner_id', $ownerId)->pluck('id')->toArray();

        if (auth('backend')->user()->type == User::STAFF) {
            $hostelArrs = Functions::getHostelArrStaff();
        }
        $hostel = $request->input('hostel_id');

        if (!empty($hostel)) {
            $hostelArrs = [$hostel];
        }
        if (empty($hostel)) {
            $items = $items->where(function ($q) use ($hostelArrs, $ownerId) {
                $q->orwhereIn('collect_spends.hostel_id', $hostelArrs);
                if (auth('backend')->user()->type == User::OWNER) {
                    $q->orwhere('collect_spends.owner_id', $ownerId);
                }
                $q->orWhereHas('moneyInfo', function ($q) use ($hostelArrs) {
                    $q->whereIn('money_infos.hostel_id', $hostelArrs);
                });
            });
        } else {
            $items = $items->where(function ($q) use ($hostelArrs, $ownerId) {
                $q->orwhereIn('collect_spends.hostel_id', $hostelArrs);
                $q->orWhereHas('moneyInfo', function ($q) use ($hostelArrs) {
                    $q->whereIn('money_infos.hostel_id', $hostelArrs);
                });
            });
        }
        $items = $items->where('collect_spends.type', $type);
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        if (!empty($startDate)) {
            try {
                $startDate = Carbon::createFromFormat('d/m/Y', $startDate)->startOfDay()->toDateTimeString();
                $items = $items->where('collect_spends.date_action', '>=', $startDate);
            } catch (\Exception $exception) {

            }
        }

        if (!empty($endDate)) {
            try {
                $endDate = Carbon::createFromFormat('d/m/Y', $endDate)->endOfDay()->toDateTimeString();
                $items = $items->where('collect_spends.date_action', '<=', $endDate);
            } catch (\Exception $exception) {

            }
        }

        $typeVoucher = $request->input('type_voucher');

        $roomId = $request->input('room_id');
        if (!empty($roomId)) {
            $items = $items->where(function ($q) use ($roomId) {
                $q->orWhere('collect_spends.room_id', $roomId);
                $q->orWhereHas('moneyInfo', function ($q) use ($roomId) {
                    $q->where('money_infos.room_id', $roomId);
                });
            });
        }


        if (!empty($typeVoucher)) {
            if ($type == CollectSpend::COLLECT) {
                $items = $items->whereIn('type_collect_id', $typeVoucher);
            } else {
                $items = $items->whereIn('type_purpose', $typeVoucher);
            }
        }
//        dump($items->toSql());
//
//        dd($items->getBindings());


        $isStat = $request->input('is_stat');

        if ($isStat == 1) {
            $deposit = 0;
            $service = 0;
            $sumEWs = 0;
            $ewsElectric = 0;
            $ewsWater = 0;
            $roomPrice = 0;
            $itemsSum = clone $items;
            $sum = $itemsSum->sum('amount');
            $itemsDeposit = clone $items;
            $itemsService = clone $items;
            $itemsRoom = clone $items;

            if ($type == CollectSpend::SPEND) {
                $typeDeposit = TypeSpend::query()
                    ->where('is_default', TypeSpend::TIEN_COC)
                    ->where('owner_id', $ownerId)
                    ->first();

                $deposit = 0;
                if ($typeDeposit) {
                    $deposit = $itemsDeposit->where('type_purpose', $typeDeposit->id)->sum('amount');
                }

            } else {
                $typeRoomPrice = TypeCollect::query()
                    ->where('type', TypeCollect::ROOM_PRICE)
                    ->where('owner_id', $ownerId)
                    ->first();
                $typeDeposit = TypeCollect::query()
                    ->where('type', TypeCollect::DEPOSIT)
                    ->where('owner_id', $ownerId)
                    ->first();
                $typeService = TypeCollect::query()
                    ->where('type', TypeCollect::SERVICE)
                    ->where('owner_id', $ownerId)
                    ->first();
                $deposit = 0;
                $roomPrice = 0;
                $service = 0;
                if ($typeDeposit) {
                    $deposit = $itemsDeposit->where('type_collect_id', $typeDeposit->id)->sum('amount');
                }
                if ($typeRoomPrice) {
                    $roomPrice = $itemsRoom->where('type_collect_id', $typeRoomPrice->id)->sum('amount');
                }

                if ($typeService) {
                    $service = $itemsService->where('type_collect_id', $typeService->id)->sum('amount');
                }
            }

            return response([
                'status' => 1,
                'data' => view('admin2.money.stat', compact('sum', 'sumEWs', 'deposit', 'type', 'service', 'roomPrice', 'ewsElectric', 'ewsWater'))->render()
            ]);
        }

        return Datatables::of($items)
            ->addIndexColumn()
            ->editColumn('amount', function ($item) {
                return number_format($item->amount, 0, '.', '.');
            })
            ->editColumn('money_info_type', function ($item) {
                if (($item->type == CollectSpend::SPEND) && ($item->type_purpose != null)) {
                    return optional($item->typespend)->name;
                } else {
                    return optional($item->typeCollect)->name;
                }
            })
            ->filterColumn('contract_code', function ($query, $keyword) {
                $query->whereHas('contract', function ($q) use ($keyword) {
                    $q->where('code', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->filterColumn('reference', function ($query, $keyword) {
                $query->whereHas('contract', function ($q) use ($keyword) {
                    $q->where('reference', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->addColumn('contract_code', function ($item) {
                if ($item->contract) {
                    return $item->contract->code;
                }
            })
            ->addColumn('reference', function ($item) {
                if ($item->contract) {
                    return $item->contract->reference;
                }
            })
            ->editColumn('room_name', function ($item) {
                if ($item->room) {
                    return $item->room->name;
                }
                if ($item->moneyInfo) {
                    return $item->moneyInfo->room->name;
                }
            })
            ->editColumn('date_action', function ($item) {
                if (!empty($item->date_action)) {
                    return Carbon::createFromFormat('Y-m-d H:i:s', $item->date_action)->format('d/m/Y');
                }
            })
            ->editColumn('money_info_name', function ($item) {
                return '<a class="detail-money" data-toggle="modal" href="#detail-money-info" data-id="' . $item->money_info_id . '">' . $item->money_info_name . '</a>';
            })
            ->editColumn('code', function ($item) {
                if ($item->type == CollectSpend::COLLECT) {
                    return 'PT' . $item->code;
                }

                return 'PC' . $item->code;
            })
            ->editColumn('payment_method', function ($item) {
                $paymentMethod = $item->payment_method;
                if ($paymentMethod == CollectSpend::MONEY) {
                    return '<label class="label label-success">Tiền mặt</label>';
                } else {
                    return '<label class="label label-danger">Chuyển khoản</label>';
                }
            })
            ->editColumn('note', function ($item) {
                return $item->note_text;
            })
            ->addColumn('action', function ($item) {
                $retVal = '';
                if ($item->type == CollectSpend::COLLECT) {

                    if (empty($item->money_info_id)) {
                        if (auth('backend')->user()->cannot('edit-collect')) {
                            $retVal = '';
                        } else {
                            $retVal =
                                '<a data-id="' . $item->id . '" data-toggle="modal" href="#edit-collect-spend" class="btn btn-sm btn-outline btn-editable btn-edit-collect dark black">
								<i class="fa fa-edit"></i> Sửa</a>';
                        }
                    } else {

                        $transactionId = $item->transaction_id;

                        $lastTransactionId = Transaction::where('money_info_id', $item->money_info_id)->orderBy('id', 'desc')->first();

                        if ($lastTransactionId) {
                            if ($transactionId == $lastTransactionId->id) {
                                if (auth('backend')->user()->cannot('edit-collect')) {
                                    $retVal = '';
                                } else {
                                    $retVal =
                                        '<a data-id="' . $item->id . '" data-toggle="modal" href="#edit-collect-spend" class="btn btn-sm btn-outline btn-editable btn-edit-collect dark black">
								<i class="fa fa-edit"></i> Sửa</a>';
                                }
                            }
                        }
                    }
                } else {
                    if (auth('backend')->user()->cannot('edit-spend')) {
                        $retVal = '';
                    } else {
                        $retVal =
                            '<a data-id="' . $item->id . '" data-toggle="modal" href="#edit-collect-spend" class="btn btn-sm btn-outline btn-editable btn-edit dark black">
								<i class="fa fa-edit"></i> Sửa</a>';
                    }
                }


                if ($item->type == CollectSpend::COLLECT) {
                    if (auth('backend')->user()->can('delete-collect')) {

                        $retVal .=
                            '<a data-id="' . $item->id . '" class="btn btn-sm btn-outline btn-editable btn-delete-money dark black">
								<i class="fa fa-trash"></i> Xóa</a>';
                    }
                } else {
                    if (auth('backend')->user()->can('delete-spend')) {

                        $retVal .=
                            '<a data-id="' . $item->id . '" class="btn btn-sm btn-outline btn-editable btn-delete-money dark black">
								<i class="fa fa-trash"></i> Xóa</a>';
                    }
                }

                $retVal .= '<a target="_blank"  href="' . url('/admin2/money/print-voucher?id=' . $item->id) . '" class="btn btn-sm btn-outline btn-editable btn-print dark black">
								<i class="fa fa-print"></i> In</a>';

                return $retVal;
            })
            ->make(true);
    }

    public function getMoneyByAttribute2(Request $request)
    {

        $ownerId = auth('backend')->user()->id;

        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $type = $request->input('type');
        $status = $request->input('status');
        $user = $request->input('user');
        $items = CollectSpend::query()
            ->with('contract')
            ->with('moneyInfo')
            ->with('room');

        if (!empty($type)) {
            $items = $items->where('type', $type);
        }

        if (!empty($user)) {
            $items = $items->where('user_id', $user);
        }

        if (!$request->has('order')) {
            $items = $items->orderBy('id', 'desc');
        }

        if ($status == 2) {
            $items = $items->onlyTrashed();
        }
        $hostelArrs = Hostel::query()->where('owner_id', $ownerId)->pluck('id')->toArray();

        if (auth('backend')->user()->type == User::STAFF) {
            $hostelArrs = Functions::getHostelArrStaff();
        }
        $hostel = $request->input('hostel_id');

        if (!empty($hostel)) {
            $hostelArrs = [$hostel];
        }

        if (empty($hostel)) {
            $items = $items->where(function ($q) use ($hostelArrs, $ownerId) {
                $q->orwhereIn('collect_spends.hostel_id', $hostelArrs);
                if (\auth('backend')->user()->type == User::OWNER) {
                    $q->orwhere('collect_spends.owner_id', $ownerId);
                }
                $q->orWhereHas('moneyInfo', function ($q) use ($hostelArrs) {
                    $q->whereIn('money_infos.hostel_id', $hostelArrs);
                });
            });
        } else {
            $items = $items->where(function ($q) use ($hostelArrs, $ownerId) {
                $q->orwhereIn('collect_spends.hostel_id', $hostelArrs);
                $q->orWhereHas('moneyInfo', function ($q) use ($hostelArrs) {
                    $q->whereIn('money_infos.hostel_id', $hostelArrs);
                });
            });
        }
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        try {
            if (!empty($startDate)) {
                $startDate = Carbon::createFromFormat('d/m/Y', $startDate)->startOfDay()->toDateTimeString();
                $items = $items->where('collect_spends.date_action', '>=', $startDate);
            }

            if (!empty($endDate)) {
                $endDate = Carbon::createFromFormat('d/m/Y', $endDate)->endOfDay()->toDateTimeString();
                $items = $items->where('collect_spends.date_action', '<=', $endDate);
            }
        } catch (\Exception $exception) {

        }

        $typeVoucher = $request->input('type_voucher');

        $roomId = $request->input('room_id');
        if (!empty($roomId)) {
            $items = $items->where(function ($q) use ($roomId) {
                $q->orWhere('collect_spends.room_id', $roomId);
                $q->orWhereHas('moneyInfo', function ($q) use ($roomId) {
                    $q->where('money_infos.room_id', $roomId);
                });
            });
        }

        $isStat = $request->input('is_stat');

        if ($isStat == 1) {
            $itemsCollect = clone $items;
            $itemsSpend = clone $items;
            $collect = $itemsCollect->where('type', CollectSpend::COLLECT)->sum('amount');
            $spend = $itemsSpend->where('type', CollectSpend::SPEND)->sum('amount');
            $remain = $collect - $spend;

            return response([
                'status' => 1,
                'data' => view('admin2.money.stat_3', compact('collect', 'spend', 'remain'))->render()
            ]);
        }

        return Datatables::of($items)
            ->addIndexColumn()
            ->setRowClass(function ($item) {
                return 'details-control';
            })
            ->editColumn('amount', function ($item) {
                return number_format($item->amount, 0, '.', '.');
            })
            ->editColumn('money_info_type', function ($item) {
                if (($item->type == CollectSpend::SPEND) && ($item->type_purpose != null)) {
                    return optional($item->typespend)->name;
                } else {
                    return optional($item->typeCollect)->name;
                }
            })
            ->filterColumn('contract_code', function ($query, $keyword) {
                $query->whereHas('contract', function ($q) use ($keyword) {
                    $q->where('code', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->filterColumn('contract_name', function ($query, $keyword) {
                $query->whereHas('contract', function ($q) use ($keyword) {
                    $q->where('name', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->filterColumn('user', function ($query, $keyword) {
                $query->where(function ($q) use ($keyword) {
                    $q->orWhere('payer', 'LIKE', '%' . $keyword . '%');
                    $q->orWhere('receiver', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->filterColumn('reference', function ($query, $keyword) {
                $query->whereHas('contract', function ($q) use ($keyword) {
                    $q->where('reference', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->addColumn('contract_code', function ($item) {
                if ($item->contract) {
                    return $item->contract->code;
                }

                return '';
            })
            ->addColumn('contract_name', function ($item) {
                if ($item->contract) {
                    return $item->contract->name;
                }
            })
            ->addColumn('hostel_name', function ($item) {
                if ($item->hostel) {
                    return $item->hostel->name;
                }

                return '';
            })
            ->addColumn('room_name', function ($item) {
                if ($item->room) {
                    return $item->room->name;
                }

                return '';
            })
            ->addColumn('user', function ($item) {
                if (!empty($item->payer)) {
                    $user = $item->payer;
                } else {
                    $user = $item->receiver;
                }

                if (!empty($user)) {
                    return $user;
                }

                return '';
            })
            ->addColumn('creator', function ($item) {
                if ($item->user) {
                    return $item->user->name_text;
                }
            })
            ->addColumn('reference', function ($item) {
                if ($item->contract) {
                    return $item->contract->reference;
                }
            })
            ->editColumn('room_name', function ($item) {
                if ($item->room) {
                    return $item->room->name;
                }

                return '';

            })
            ->editColumn('created_at', function ($item) {
                return $item->created_at->format('d/m/Y');
            })
            ->editColumn('date_action', function ($item) {
                if (!empty($item->date_action)) {
                    return Carbon::createFromFormat('Y-m-d H:i:s', $item->date_action)->format('d/m/Y');
                }
            })
            ->editColumn('money_info_name', function ($item) {
                return '<a class="detail-money" data-toggle="modal" href="#detail-money-info" data-id="' . $item->money_info_id . '">' . $item->money_info_name . '</a>';
            })
            ->addColumn('money_info_name_2', function ($item) {
                if ($item->moneyInfo) {
                    return $item->moneyInfo->name;
                }

                return '';
            })
            ->editColumn('code', function ($item) {
                if ($item->type == CollectSpend::COLLECT) {
                    return 'PT' . $item->code;
                }

                return 'PC' . $item->code;
            })
            ->editColumn('name', function ($item) {
                if (!empty($item->name)) {
                    return $item->name;
                }

                if (!empty($item->note)) {
                    return $item->note;
                }

                return '';
            })
            ->editColumn('payment_method', function ($item) {
                $paymentMethod = $item->payment_method;
                if ($paymentMethod == CollectSpend::MONEY) {
                    return '<label class="label label-success">Tiền mặt</label>';
                } else {
                    return '<label class="label label-danger">Chuyển khoản</label>';
                }
            })
            ->addColumn('action', function ($item) {
                $retVal = '';
                if ($item->type == CollectSpend::COLLECT) {

                    $transactionId = $item->transaction_id;

                    $lastTransactionId = Transaction::where('money_info_id', $item->money_info_id)->orderBy('id', 'desc')->first();

                    if ($lastTransactionId) {
                        if ($transactionId == $lastTransactionId->id) {
                            if (auth('backend')->user()->cannot('edit-collect')) {
                                $retVal = '';
                            } else {
                                $retVal =
                                    '<a data-id="' . $item->id . '" data-toggle="modal" href="#edit-collect-spend" class="btn btn-sm btn-outline btn-editable btn-edit-collect dark black">
								<i class="fa fa-edit"></i> Sửa</a>';
                            }
                        }
                    }
                } else {
                    if (auth('backend')->user()->cannot('edit-spend')) {
                        $retVal = '';
                    } else {
                        $retVal =
                            '<a data-id="' . $item->id . '" data-toggle="modal" href="#edit-collect-spend" class="btn btn-sm btn-outline btn-editable btn-edit dark black">
								<i class="fa fa-edit"></i> Sửa</a>';
                    }
                }


                if ($item->type == CollectSpend::COLLECT) {
                    if (auth('backend')->user()->can('delete-collect')) {

                        $retVal .=
                            '<a data-id="' . $item->id . '" class="btn btn-sm btn-outline btn-editable btn-delete-money dark black">
								<i class="fa fa-trash"></i> Xóa</a>';
                    }
                } else {
                    if (auth('backend')->user()->can('delete-spend')) {

                        $retVal .=
                            '<a data-id="' . $item->id . '" class="btn btn-sm btn-outline btn-editable btn-delete-money dark black">
								<i class="fa fa-trash"></i> Xóa</a>';
                    }
                }

                $retVal .= '<a target="_blank"  href="' . url('/admin2/money/print-voucher?id=' . $item->id) . '" class="btn btn-sm btn-outline btn-editable btn-print dark black">
								<i class="fa fa-print"></i> In</a>';

                return $retVal;
            })
            ->addColumn('edit_btn', function ($item) {
                return '<a data-id="' . $item->id . '" data-toggle="modal" href="#edit-collect-spend" class="btn btn-sm btn-outline btn-editable btn-edit dark black">
								<i class="fa fa-edit"></i> Sửa</a>';
            })
            ->addColumn('delete_btn', function ($item) {
                return '<a data-id="' . $item->id . '" class="btn btn-sm btn-outline btn-editable btn-delete-money dark black">
								<i class="fa fa-trash"></i> Xóa</a>';
            })
            ->addColumn('print_btn', function ($item) {
                return '<a target="_blank"  href="' . url('/admin2/money/print-voucher?id=' . $item->id) . '" class="btn btn-sm btn-outline btn-editable btn-print dark black">
								<i class="fa fa-print"></i> In</a>';
            })
            ->addColumn('action', function ($item) {
                return '<a data-id="' . $item->id . '" class="btn btn-sm btn-outline btn-editable dark black details-control">
								<i class="fa fa-edit"></i> Xem chi tiết</a>';
            })
            ->make(true);
    }

    public function exportExcel(Request $request)
    {
        $roomId = $request->input('room_id');
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $type = $request->input('type');
        $userType = $request->input('user_type');
        $status = $request->input('status');

        $items = CollectSpend::query();

        $ownerId = auth('backend')->user()->id;
        if (\auth('backend')->user()->type == User::STAFF) {
            $ownerId = \auth('backend')->user()->staff_owner_id;
        }

        $hostelArrs = Hostel::query()->where('owner_id', $ownerId)->pluck('id')->toArray();

        if (auth('backend')->user()->type == User::STAFF) {
            $hostelArrs = Functions::getHostelArrStaff();
        }

        if (!empty($userType)) {
            $items = $items->whereHas('user', function ($q) use ($userType) {
                if ($userType == 1) {
                    $q->where('type', User::OWNER);
                } else {
                    $q->where('type', User::STAFF);
                }
            });
        }

        if ($status == 2) {
            $items = $items->onlyTrashed();
        }

        $hostel = $request->input('hostel_id');


        if (empty($hostel)) {
            $items = $items->where(function ($q) use ($hostelArrs, $ownerId) {
                $q->orwhereIn('collect_spends.hostel_id', $hostelArrs);
                $q->orwhere('collect_spends.owner_id', $ownerId);
                $q->orWhereHas('moneyInfo', function ($q) use ($hostelArrs) {
                    $q->whereIn('money_infos.hostel_id', $hostelArrs);
                });
            });
        } else {
            $hostelArrs = [$hostel];
            $items = $items->where(function ($q) use ($hostelArrs, $ownerId) {
                $q->orwhereIn('collect_spends.hostel_id', $hostelArrs);
                $q->orWhereHas('moneyInfo', function ($q) use ($hostelArrs) {
                    $q->whereIn('money_infos.hostel_id', $hostelArrs);
                });
            });
        }

        if (!empty($startDate)) {
            $startDate = Carbon::createFromFormat('d/m/Y', $startDate)->startOfDay()->toDateTimeString();
            $items = $items->where('date_action', '>=', $startDate);
        }

        if (!empty($endDate)) {
            $endDate = Carbon::createFromFormat('d/m/Y', $endDate)->endOfDay()->toDateTimeString();
            $items = $items->where('date_action', '<=', $endDate);
        }

        if (!empty($roomId)) {
            $items = $items->where(function ($q) use ($roomId) {
                $q->orWhere('collect_spends.room_id', $roomId);
                $q->orWhereHas('moneyInfo', function ($q) use ($roomId) {
                    $q->where('money_infos.room_id', $roomId);
                });
            });
        }

        if (!empty($type)) {

            if ($type == 'outcome') {
                $type = CollectSpend::SPEND;
            } else {
                $type = CollectSpend::COLLECT;
            }
            $items = $items->where('type', $type);
        }

        $items = $items
            ->with([
                'hostel',
                'room'
            ])
            ->get();


        $responseArr = [];

        foreach ($items as $item) {
            $itemArr = [];
            if ($type == CollectSpend::COLLECT) {
                $itemArr['Mã phiếu thu'] = $item->code;
            } else {
                $itemArr['Mã phiếu chi'] = $item->code;
            }
            $itemArr['Mã hóa đơn'] = $item->money_info_name;
            $itemArr['Loại thu chi'] = $item->type_cp_text;
            $itemArr['Loại phiếu'] = strip_tags($item->type_text);
            $itemArr['Nhà trọ'] = $item->hostel_name;
            $itemArr['Phòng trọ'] = $item->room ? $item->room->name : $item->room_name;
            $itemArr['Số tiền'] = $item->amount;
            $itemArr['Nội dung'] = $item->name;
            $itemArr['Hình thức'] = $item->payment_method_text;
            $itemArr['Hợp đồng'] = optional($item->contract)->name;
            if ($type == CollectSpend::COLLECT) {
                $itemArr['Người nộp tiền'] = $item->payer;
            } else {
                $itemArr['Người nhận'] = $item->receiver;
            }
            $itemArr['Thời gian'] = $item->date_action->format('d/m/Y');
            $itemArr['Ghi chú'] = $item->note;
            $responseArr[] = $itemArr;
        }
        if ($type == CollectSpend::COLLECT) {
            $name = 'phieu-thu';
        } else {
            $name = 'phieu-chi';
        }
        \Excel::create($name . '-' . time(), function ($excel) use ($responseArr, $name) {
            $excel->sheet($name, function ($sheet) use ($responseArr) {
                $sheet->fromArray($responseArr);
            });
        })->download('xls');
    }

    public function exportExcelVoucher(Request $request)
    {


        $items = MoneyInfo::select(\DB::raw('money_infos.*, hostels.name as hostel, rooms.name as room'))
            ->join('hostels', 'money_infos.hostel_id', '=', 'hostels.id')
            ->join('rooms', 'money_infos.room_id', '=', 'rooms.id');

        $ownerId = auth('backend')->user()->id;

        $hostelArrs = Hostel::where('owner_id', $ownerId)->pluck('id')->toArray();

        if (auth('backend')->user()->type == User::STAFF) {
            $hostelArrs = Functions::getHostelArrStaff();
        }

        $hostel = $request->input('hostel_id');

        if (!empty($hostel)) {
            $items = $items->where('money_infos.hostel_id', $hostel);
        } else {

            $items = $items->whereIn('money_infos.hostel_id', $hostelArrs);
        }

        $startDate = $request->input('start_date');
        if (!empty($startDate)) {
            $startDate = Carbon::createFromFormat('d/m/Y', $startDate);
            $items = $items->where('date_action', '>=', $startDate->copy()->startOfDay()->toDateString());
        }

        $endDate = $request->input('end_date');
        if (!empty($endDate)) {
            $endDate = Carbon::createFromFormat('d/m/Y', $endDate);
            $items = $items->where('date_action', '<=', $endDate->copy()->startOfDay()->toDateString());
        }

        $items = $items->get();

        $responseArr = [];

        foreach ($items as $item) {
            $itemArr = [];
            $itemArr['Mã hóa đơn'] = $item->name;
            $itemArr['Nội dung'] = $item->money_info_name;
            $itemArr['Nhà trọ'] = $item->hostel;
            $itemArr['Phòng trọ'] = $item->room;
            $itemArr['Số tiền'] = $item->amount;
            $itemArr['Đã thanh toán'] = $item->pay;
            $itemArr['Còn lại'] = $item->remain;
            $itemArr['Thời gian'] = $item->date_action->format('m/Y');
            $responseArr[] = $itemArr;
        }

        \Excel::create('hoa-don-' . time(), function ($excel) use ($responseArr) {
            $excel->sheet('hoa-don', function ($sheet) use ($responseArr) {
                $sheet->fromArray($responseArr);
            });
        })->download('xls');


    }

    public function getVoucherByAttributeView2(Request $request)
    {
        $urlPrintContract = '';
        $owner = \auth('backend')->user();
        if (\auth('backend')->user()->type == User::STAFF) {
            $owner = auth('backend')->user()->owner;
        }
        $typeDisplay = $owner->type_display_money_info;

        // $typeDisplay = User::TYPE_DISPLAY_MONEY_INFO_CURRENT_MONTH;
        if ($typeDisplay == User::TYPE_DISPLAY_MONEY_INFO_CURRENT_MONTH) {
            $urlPrintContract = '/bill/print-money-info-contract';
        } else {
            $urlPrintContract = '/bill/print-money-info-room-service';
        }
        return view('admin2.money.voucher_2', compact('urlPrintContract', 'owner'));
    }

    public function getVoucherAjax(Request $request)
    {
        $month = $request->input('month');
        $hostelId = $request->input('hostel_id');
        $roomId = $request->input('room_id');
        $type = $request->input('type');
        $contractIds = $request->input('contract_ids');

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

        $owner = auth('backend')->user();
        if (auth('backend')->user()->type == User::STAFF) {
            $owner = auth('backend')->user()->owner;
        }

        $typeDisplay = $owner->type_display_money_info;

        // $typeDisplay = User::TYPE_DISPLAY_MONEY_INFO_CURRENT_MONTH;

        $contracts = Contract::query()
            ->when($request->input('status') != -1, function ($q) {
                $q->where('status', \request()->input('status'));
            })
            ->when(\auth('backend')->user()->type == User::STAFF, function ($q) {
                $hostelIds = Functions::getHostelArrStaff();
                $q->whereIn('hostel_id', $hostelIds);
            })
            ->when(!empty($contractIds), function ($q) {
                $q->whereIn('id', \request()->input('contract_ids'));
            })
//            ->join('hostels', 'contracts.hostel_id', '=', 'hostels.id')
//            ->join('rooms', 'contracts.room_id', '=', 'rooms.id')
            ->when(!empty($hostelId), function ($q) use ($hostelId) {
                $q->where('hostel_id', $hostelId);
            })
            ->when(!empty($roomId), function ($q) use ($roomId) {
                $q->where('room_id', $roomId);
            })
            ->whereHas('hostel', function ($q) use ($owner) {
                $q->where('owner_id', $owner->id);
            });

        if ($typeDisplay == User::TYPE_DISPLAY_MONEY_INFO_CURRENT_MONTH) {
            $contracts = $contracts
                ->with([
                    'hostel',
                    'room',
                    'moneyInfos' => function ($q) use ($month, $type) {
                        $q->whereBetween('date_action', [
                            $month->copy()->startOfMonth(),
                            $month->copy()->endOfMonth()
                        ]);
                    }
                ]);
        } else {
            $contracts = $contracts->with([
                'room',
                'hostel',
                'moneyInfos' => function ($q) use ($month, $type) {
                    $q->where(function ($q) use ($month, $type) {
                        $q->orWhere(function ($q) use ($month, $type) {
                            $q->whereBetween('date_action', [
                                $month->copy()->startOfMonth(),
                                $month->copy()->endOfMonth()
                            ]);
                            $q->whereIn('type', [
                                MoneyInfo::VOUCHER_CONTRACT,
                                MoneyInfo::VOUCHER_ROOM_PRICE
                            ]);
                        });

                        $q->orWhere(function ($q) use ($month, $type) {
                            $q->whereBetween('date_action', [
                                $month->copy()->subMonth()->startOfMonth(),
                                $month->copy()->subMonth()->endOfMonth()
                            ]);
                            $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                        });
                    });

                },
            ]);
        }
        $contracts = $contracts
            ->get()
            ->sortBy('hostel.name')
            ->sortBy('room.name');


        if ($type == 1) {
            $contracts = $contracts->filter(function ($item) {
                return $item->moneyInfos->sum('remain') == 0;
            });
        } else if ($type == 2) {
            $contracts = $contracts->filter(function ($item) {
                return $item->moneyInfos->sum('remain') > 0;
            });
        }

        if ($request->input('is_excel')) {
            $ownerId = $owner->id;
            return dispatch_now(new ExportMoneyInfo($ownerId, $month->copy(), $contracts));
        }

        $moneyInfos = MoneyInfo::query()
            ->whereIn('contract_id', $contracts->pluck('id')->toArray())
            ->when($owner->type_display_money_info == User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH, function ($q) use ($month) {
                $q->where(function ($q) use ($month) {
                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->startOfMonth(),
                            $month->copy()->endOfMonth()
                        ]);
                        $q->whereIn('type', [
                            MoneyInfo::VOUCHER_CONTRACT,
                            MoneyInfo::VOUCHER_ROOM_PRICE
                        ]);
                    });

                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->subMonth()->startOfMonth(),
                            $month->copy()->subMonth()->endOfMonth()
                        ]);
                        $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                    });
                });

            }, function ($q) use ($month) {

                $q->whereBetween('date_action', [
                    $month->copy()->startOfMonth(),
                    $month->copy()->endOfMonth()
                ]);

            })->get();

        return response([
            'status' => 1,
            'data' => view('admin2.money.voucher_2_ajax', compact('contracts', 'owner', 'month', 'moneyInfos'))->render()
        ]);
    }

    public function getVoucherByAttribute(Request $request)
    {
        $items = MoneyInfo::query()
            ->selectRaw('*, amount-discount as amount, amount-pay-discount as remain')
            ->with([
                'hostel',
                'room',
                'contract'
            ]);


        $ownerId = auth('backend')->user()->id;
        $hostel = $request->input('hostel_id');
        $month = $request->input('month');
        $type = $request->input('type');

        $hostelArrs = Hostel::query()->where('owner_id', $ownerId)->pluck('id')->toArray();

        if (auth('backend')->user()->type == User::STAFF) {
            $hostelArrs = Functions::getHostelArrStaff();
        }

        if (!empty($hostel)) {
            $items = $items->where('money_infos.hostel_id', $hostel);
        } else {

            $items = $items->whereIn('money_infos.hostel_id', $hostelArrs);
        }

        $startDate = null;
        $endDate = null;
        if (!empty($month)) {
            $month = Carbon::createFromFormat('d/m/Y', '01/' . $month);
            $startDate = $month->copy()->startOfMonth();
            $endDate = $month->copy()->endOfMonth();
        }
        if (!empty($startDate)) {
            $items = $items->where('date_action', '>=', $startDate->copy()->startOfDay());
        }

        if (!empty($endDate)) {
            $items = $items->where('date_action', '<=', $endDate->copy()->endOfDay());
        }

        if (!empty($type)) {
            if ($type == 1) {
                $items = $items->whereIn('type', [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT]);
            } else {
                $items = $items->whereNotIn('type', [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT]);
            }
        }


        return Datatables::of($items)
            ->addIndexColumn()
            ->setRowClass(function ($item) {
                return $item->remain > 0 ? 'warning' : '';
            })
            ->filterColumn('hostel', function ($query, $keyword) {
                $query->where('hostels.name', 'LIKE', '%' . $keyword . '%');
            })
            ->filterColumn('name', function ($query, $keyword) {

                $query->where(function ($q) use ($keyword) {
                    $q->orWhere('money_infos.name', 'LIKE', '%' . $keyword . '%');
                    $q->orWhere(DB::raw('CONCAT("HD",money_infos.id,DATE_FORMAT(money_infos.created_at, "%d%m%y"))'), 'LIKE', '%' . $keyword . '%');
                });

            })
            ->filterColumn('room_id', function ($query, $keyword) {
                $query->whereHas('room', function ($q) use ($keyword) {
                    $q->where('rooms.name', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->filterColumn('hostel_id', function ($query, $keyword) {
                $query->whereHas('hostel', function ($q) use ($keyword) {
                    $q->where('hostels.name', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->filterColumn('contract_name', function ($query, $keyword) {
                $query->whereHas('contract', function ($q) use ($keyword) {
                    $q->where('contracts.name', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->filterColumn('contract_code', function ($query, $keyword) {
                $query->whereHas('contract', function ($q) use ($keyword) {
                    $q->where('contracts.code', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->filterColumn('reference', function ($query, $keyword) {
                $query->whereHas('contract', function ($q) use ($keyword) {
                    $q->where('contracts.reference', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->editColumn('amount', function ($item) {
                return number_format($item->amount, 0, '.', '.');
            })
            ->editColumn('hostel_id', function ($item) {
                if ($item->hostel) {
                    return $item->hostel->name;
                }
            })
            ->editColumn('room_id', function ($item) {
                if ($item->room) {
                    return $item->room->name;
                }
            })
            ->addColumn('contract_name', function ($item) {
                if ($item->contract) {
                    return $item->contract->name;
                }
            })
            ->addColumn('contract_code', function ($item) {
                if ($item->contract) {
                    return $item->contract->code;
                }
            })
            ->addColumn('reference', function ($item) {
                if ($item->contract) {
                    return $item->contract->reference;
                }
            })
            ->editColumn('pay', function ($item) {
                return number_format($item->pay, 0, '.', '.');
            })
            ->editColumn('remain', function ($item) {
                return number_format($item->remain, 0, '.', '.');
            })
            ->editColumn('date_action', function ($item) {
                return $item->date_action->format('m/Y');
            })
            ->addColumn('action', function ($item) {
                $edit = '';
                if (auth('backend')->user()->can('edit-money-info')) {
                    $edit = '<a target="_blank" data-money-info="' . $item->id . '" data-date="' . $item->date_action->format('m/Y') . '" class="update-money-info btn btn-sm btn-outline btn-editable dark black">
								<i class="fa fa-edit"></i> Sửa</a>';
                    if (!in_array($item->type, [
                        MoneyInfo::VOUCHER_ROOM_PRICE,
                        MoneyInfo::VOUCHER_CONTRACT
                    ])) {
                        $edit = '';
                    }
                }

                return '<div style="min-width: 300px">' .
                    '<a target="_blank" data-money-info="' . $item->id . '" data-date="' . $item->date_action->format('m/Y') . '" class="print-money-info btn btn-sm btn-outline btn-editable detail-money dark black">
								<i class="fa fa-print"></i> In</a>' .
                    $edit .
                    '<a data-id="' . $item->id . '" data-toggle="modal" href="#detail-money-info" class="btn btn-sm btn-outline btn-editable detail-money dark black">
								<i class="fa fa-eye"></i> Xem chi tiết</a>' .
                    '<a data-room="' . $item->room_id . '" data-id="' . $item->id . '" data-toggle="modal" href="#transaction-history" class="btn btn-sm btn-outline btn-editable btn-transaction-history dark">
								<i class="fa fa-edit"></i> Lịch sử thanh toán</a>' .
                    '<a data-money-info="' . $item->id . '" data-date="' . $item->date_action->format('m/Y') . '" class="delete-voucher btn btn-sm btn-outline btn-editable dark black">
								<i class="fa fa-trash"></i> Xóa</a></div>';
            })
            ->make(true);
    }

    public function checkNumberMoneyInfo(Request $request)
    {
        $id = $request->input('id');
        $item = MoneyInfo::find($id);
        $items = MoneyInfo::whereBetween('date_action', [
            $item->date_action->startOfMonth()->startOfDay(),
            $item->date_action->endOfMonth()->endOfDay()
        ])
            ->where('room_id', $item->room_id)
            ->where('remain', '<>', 0)->count();

        return response([
            'status' => 1,
            'data' => $items
        ]);
    }

    public function getPaidFullView(Request $request)
    {
        $ids = $request->input('id');
        $contractIds = $request->input('contract_ids');
        $month = $request->input('month');
        if (empty($month)) {
            $month = Carbon::now();
        } else {
            $month = Carbon::createFromFormat('d/m/Y', '01/' . $month);
        }

        $isDelete = $request->input('is_delete');


        if (!empty($contractIds)) {
            $owner = \auth('backend')->user();
            if (\auth('backend')->user()->type == User::STAFF) {
                $owner = \auth('backend')->user()->owner;
            }
            $ids = MoneyInfo::query()
                ->whereIn('contract_id', $contractIds)
                ->when($owner->type_display_money_info == User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH, function ($q) use ($month) {
                    $q->where(function ($q) use ($month) {
                        $q->orWhere(function ($q) use ($month) {
                            $q->whereBetween('date_action', [
                                $month->copy()->startOfMonth(),
                                $month->copy()->endOfMonth()
                            ]);
                            $q->whereIn('type', [
                                MoneyInfo::VOUCHER_CONTRACT,
                                MoneyInfo::VOUCHER_ROOM_PRICE
                            ]);
                        });

                        $q->orWhere(function ($q) use ($month) {
                            $q->whereBetween('date_action', [
                                $month->copy()->subMonth()->startOfMonth(),
                                $month->copy()->subMonth()->endOfMonth()
                            ]);
                            $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                        });
                    });

                }, function ($q) use ($month) {

                    $q->whereBetween('date_action', [
                        $month->copy()->startOfMonth(),
                        $month->copy()->endOfMonth()
                    ]);

                })->pluck('id')->toArray();
        }

        if (empty($ids)) {
            return response([
                'status' => 0,
                'message' => 'Bạn cần chọn hóa đơn để thanh toán'
            ]);
        }
        $moneyInfos = MoneyInfo::query()
            ->whereIn('id', $ids)
            ->get();

        $amount = $moneyInfos->sum('remain');
        $amount = number_format($amount, 0, '.', '.');

        return response([
            'status' => 1,
            'data' => view('admin2.money.mark_paid_full', compact('ids', 'moneyInfos', 'isDelete', 'amount'))->render()
        ]);
    }

    public function markPaidFullMoneyInfos(Request $request)
    {
        $ids = $request->input('id');
        $dateAction = $request->input('date_action');
        $paymentMethod = $request->input('payment_method');
        $amount = $request->input('amount');
        $amount = Functions::filterInputNumber($amount);

        if (empty($ids) || !is_array($ids)) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }


        $moneyInfos = MoneyInfo::query()
            ->with([
                'hostel',
                'room',
                'contract'
            ])
            ->whereIn('id', $ids)
            ->get();

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

        if (empty($amount)) {
            $amount = $moneyInfos->sum('remain');
        }

        $sumAmount = $moneyInfos->sum('remain');
        if ($amount > $sumAmount) {
            return response([
                'status' => 0,
                'message' => 'Bạn chỉ được thanh toán tối đa ' . number_format($sumAmount, 0, '.', '.')
            ]);
        }

        foreach ($moneyInfos as $moneyInfo) {
//            if(empty($amount)) {
//                $amount = $moneyInfo->amount - $moneyInfo->discount - $moneyInfo->pay;
//            }
            if ($amount <= 0) {
                break;
            }
            if ($moneyInfo->remain == 0) {
                continue;
            }
            $remain = $moneyInfo->remain;
            if ($amount >= $remain) {
                $payAmount = $remain;
            } else {
                $payAmount = $amount;
            }


            $moneyInfo->remain = $moneyInfo->remain - $payAmount;
            $moneyInfo->pay = $moneyInfo->pay + $payAmount;
            $moneyInfo->save();

            $moneyInfoId = $moneyInfo->id;
            $hostelId = $moneyInfo->hostel_id;
            $userId = auth('backend')->user()->id;
            $roomId = $moneyInfo->room_id;
            $payer = optional($moneyInfo->contract)->name;

            $transaction = Transaction::create([
                'amount' => $payAmount,
                'hostel_id' => $hostelId,
                'date_action' => $dateAction,
                'user_id' => $userId,
                'money_info_id' => $moneyInfoId,
                'type' => CollectSpend::COLLECT,
                'payer' => $payer
            ]);

            $collectSpend = CollectSpend::create([
                'amount' => $payAmount,
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'payment_method' => $paymentMethod,
                'date_action' => $dateAction,
                'user_id' => $userId,
                'money_info_id' => $moneyInfoId,
                'type' => CollectSpend::COLLECT,
                'transaction_id' => $transaction->id,
                'payer' => $payer
            ]);
            $amount = $amount - $remain;

            $user = Functions::getCurrentUser();

            $contract = $moneyInfo->contract;

            if ($contract) {

                $desc = '{' . $user->name . '} vừa thu {' . number_format($payAmount, 0, '.', '.') . '}, hóa đơn {' . $moneyInfo->name . '} của khách {' . $contract->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
                if ($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                    $desc = '{' . $user->name . '} vừa thu {' . number_format($payAmount, 0, '.', '.') . '}, hóa đơn {' . $moneyInfo->name . '} của khách {' . $contract->name . '} giường {' . optional($contract->bed)->name . '} phòng {' . $contract->room->name . '} nhà {' . $contract->hostel->name . '}';
                }
                event(new LogAction([
                    'type' => 'add-payment-collect',
                    'user_id' => optional($user)->id,
                    'object_id' => $collectSpend->id,
                    'hostel_id' => $contract->hostel_id,
                    'room_id' => $contract->room_id,
                    'properties' => $collectSpend->toArray(),
                    'desc' => $desc
                ]));
            }
        }

        return response([
            'status' => 1
        ]);
    }

    public function checkNumberMoneyUnpaid(Request $request)
    {
        $id = $request->input('hostel_id');
        $item = MoneyInfo::where('hostel_id', $id)->first();
        $items = MoneyInfo::whereBetween('date_action', [
            $item->date_action->startOfMonth()->startOfDay(),
            $item->date_action->endOfMonth()->endOfDay()
        ])
            ->where('room_id', $item->room_id)
            ->where('remain', '=', 0)->count();

        return response([
            'status' => 1,
            'data' => $items
        ]);
    }

    public function deleteVoucherMultiple(Request $request)
    {
        $ids = $request->input('ids');
        $contractIds = $request->input('contract_ids');
        $month = $request->input('month');
        if (empty($month)) {
            $month = Carbon::now();
        } else {
            $month = Carbon::createFromFormat('d/m/Y', '01/' . $month);
        }


        if (!empty($contractIds)) {
            $owner = \auth('backend')->user();
            if (\auth('backend')->user()->type == User::STAFF) {
                $owner = \auth('backend')->user()->owner;
            }
            $moneyInfos = MoneyInfo::query()
                ->whereIn('contract_id', $contractIds)
                ->when($owner->type_display_money_info == User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH, function ($q) use ($month) {
                    $q->where(function ($q) use ($month) {
                        $q->orWhere(function ($q) use ($month) {
                            $q->whereBetween('date_action', [
                                $month->copy()->startOfMonth(),
                                $month->copy()->endOfMonth()
                            ]);
                            $q->whereIn('type', [
                                MoneyInfo::VOUCHER_CONTRACT,
                                MoneyInfo::VOUCHER_ROOM_PRICE
                            ]);
                        });

                        $q->orWhere(function ($q) use ($month) {
                            $q->whereBetween('date_action', [
                                $month->copy()->subMonth()->startOfMonth(),
                                $month->copy()->subMonth()->endOfMonth()
                            ]);
                            $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                        });
                    });

                }, function ($q) use ($month) {

                    $q->whereBetween('date_action', [
                        $month->copy()->startOfMonth(),
                        $month->copy()->endOfMonth()
                    ]);

                })->get();
            $ids = $moneyInfos->pluck('id')->toArray();
        } else {
            $moneyInfos = MoneyInfo::query()
                ->whereIn('id', $ids)
                ->get();
        }

        if (empty($ids)) {
            return response([
                'status' => 0,
                'message' => 'Bạn cần chọn hóa đơn để thanh toán'
            ]);
        }
        MoneyInfo::query()
            ->whereIn('id', $ids)
            ->delete();


        CollectSpend::whereIn('money_info_id', $ids)->delete();
        Transaction::whereIn('money_info_id', $ids)->delete();
        MoneyDetail::whereIn('money_info_id', $ids)->delete();
        $user = Functions::getCurrentUser();
        foreach ($moneyInfos as $moneyInfo) {

            $desc = '{' . optional($user)->name . '} xóa hóa đơn mã ' . $moneyInfo->name . ' phòng {' . $moneyInfo->room->name . '} nhà {' . $moneyInfo->room->hostel->name . '}';
            if ($moneyInfo->hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
                $desc = '{' . optional($user)->name . '} xóa hóa đơn mã ' . $moneyInfo->name . ' giường {' . optional(optional($moneyInfo->contract)->bed)->name . '} phòng {' . $moneyInfo->room->name . '} nhà {' . $moneyInfo->room->hostel->name . '}';
            }

            event(new LogAction([
                'type' => 'delete-money-info',
                'user_id' => optional($user)->id,
                'object_id' => $moneyInfo->id,
                'hostel_id' => $moneyInfo->hostel_id,
                'room_id' => $moneyInfo->room_id,
                'properties' => $moneyInfo->toArray(),
                'desc' => $desc
            ]));
        }

        return response([
            'status' => 1,
            'message' => 'Thanh cong'
        ]);
    }

    public function deleteVoucher(Request $request)
    {
        $id = $request->input('id');
        $voucher = MoneyInfo::find($id);
        if (!$voucher) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        CollectSpend::where('money_info_id', $voucher->id)->delete();
        Transaction::where('money_info_id', $voucher->id)->delete();
        MoneyDetail::where('money_info_id', $voucher->id)->delete();
        $voucher->delete();

        return response([
            'status' => 1,
            'message' => 'Thanh cong'
        ]);
    }

    public function spend(Request $request)
    {
        $data = $request->all();
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $type_purpose = $data['type_purpose'];

        $amount = $data['amount'];

        if (empty($amount)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống số tiền'
            ]);
        }

        $amount = Functions::filterInputNumber($amount);

        if (!is_numeric($amount)) {
            return response([
                'status' => 0,
                'message' => 'Số tiền phải là số'
            ]);
        }

        if (!empty($data['date_action'])) {
            $dateAction = Carbon::createFromFormat('d/m/Y', $data['date_action'])->toDateString();
        } else {
            $dateAction = Carbon::now()->toDateString();
        }

        $roomId = null;
        $hostelId = null;
        if (isset($data['room_id'])) {
            $roomId = $data['room_id'];
        }
        if (isset($data['hostel_id'])) {
            $hostelId = $data['hostel_id'];
        }

        try {
            \DB::beginTransaction();
            if ($type_purpose == null) {
                $orther_type_purpose = $data['orther_type_purpose'];
                if ($orther_type_purpose == null || $orther_type_purpose == '') {
                    return response([
                        'status' => 0,
                        'message' => 'Không được bỏ trống loại chi'
                    ]);
                } else {
                    $type_purpose = TypeSpend::create([
                        'name' => $orther_type_purpose,
                        'owner_id' => $ownerId,
                    ])->id;
                }
            }
            $transaction = Transaction::create([
                'amount' => $amount,
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'date_action' => $dateAction,
                'type' => CollectSpend::SPEND,
            ]);

            $cp = CollectSpend::create([
                'amount' => $amount,
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'owner_id' => $ownerId,
                'note' => $data['note'],
                'payment_method' => $data['payment_method'],
                'date_action' => $dateAction,
                'type' => CollectSpend::SPEND,
                'receiver' => $data['receiver'],
                'name' => $data['name'],
                'transaction_id' => $transaction->id,
                'type_purpose' => $type_purpose,
                'is_allow_cycle' => true
                //'type_spend_id' => '',
            ]);

            $cnt = Receiver::query()->where('name', trim($data['receiver']))
                ->where('user_id', auth('backend')->user()->id)->count();

            if ($cnt == 0) {
                Receiver::create([
                    'user_id' => auth('backend')->user()->id,
                    'name' => $data['receiver']
                ]);
            }

            \DB::commit();
            $files = $request->file('files');
            if (!empty($files) && is_array($files)) {
                foreach ($files as $key => $file) {
                    $name = time() . $file->getClientOriginalName();
                    $filePath = 'collect-spends/' . $cp->id . '/files/' . str_slug($name);
                    $filePath = $filePath . '.' . $file->getClientOriginalExtension();
                    \Storage::disk('s3')->put($filePath, file_get_contents($file), 'public');
                    CollectSpendFile::create([
                        'collect_spend_id' => $cp->id,
                        'name' => $file->getClientOriginalName(),
                        'file' => 'https://resident.sgp1.digitaloceanspaces.com/' . $filePath
                    ]);
                }
            }

            $repeatEvery = $request->input('repeat_every');
            if ($repeatEvery) {
                CollectSpendCycle::query()->updateOrCreate([
                    'collect_spend_id' => $cp->id,
                ], [
                    'collect_spend_id' => $cp->id,
                    'repeat_every' => $request->input('repeat_every'),
                    'repeat_every_custom' => $request->input('repeat_every_custom'),
                    'repeat_type_custom' => $request->input('repeat_type_custom'),
                    'cycles' => $request->input('cycles'),
                    'unlimited_cycles' => $request->input('unlimited_cycles') == 'on' ? true : false,

                ]);
            } else {
                CollectSpendCycle::query()
                    ->where('collect_spend_id', $cp->id)
                    ->delete();
            }

            $user = Functions::getCurrentUser();
            $desc = '{' . optional($user)->name . '} vừa chi {' . number_format($cp->amount, 0, '.', '.') . '} với nội dung {' . $request->input('name') . '}';
            event(new LogAction([
                'type' => 'create-spend',
                'user_id' => optional($user)->id,
                'object_id' => $cp->id,
                'hostel_id' => $cp->hostel_id,
                'room_id' => $cp->room_id,
                'properties' => $cp->toArray(),
                'desc' => $desc
            ]));
        } catch (\Exception $exception) {
            \DB::rollBack();

            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra vui lòng thử lại sau'
            ]);
        }

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    public function getVoucherByAttributeView(Request $request)
    {
        return view('admin2.money.voucher');
    }

    public function collect(Request $request)
    {
        $data = $request->all();

        $amount = $data['amount'];

        if (empty($amount)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống số tiền'
            ]);
        }

        $amount = Functions::filterInputNumber($amount);

        if (!is_numeric($amount)) {
            return response([
                'status' => 0,
                'message' => 'Số tiền phải là số'
            ]);
        }

        if (!empty($data['date_action'])) {
            $dateAction = Carbon::createFromFormat('d/m/Y', $data['date_action'])->toDateString();
        } else {
            $dateAction = Carbon::now()->toDateString();
        }

        $roomId = $data['room_id'];
        $hostelId = $data['hostel_id'];

        try {
            \DB::beginTransaction();

            $transaction = Transaction::create([
                'amount' => $amount,
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'date_action' => $dateAction,
                'type' => CollectSpend::COLLECT,
                'payer' => $data['payer']
            ]);

            $cp = CollectSpend::create([
                'amount' => $amount,
                'hostel_id' => $hostelId,
                'room_id' => $roomId,
                'note' => $data['note'],
                'payment_method' => $data['payment_method'],
                'date_action' => $dateAction,
                'type' => CollectSpend::COLLECT,
                'name' => $data['name'],
                'transaction_id' => $transaction->id,
                'payer' => $data['payer'],
                'receiver' => $data['receiver'],
                'type_collect_id' => !empty($data['type_collect_id']) ? $data['type_collect_id'] : null,
            ]);

            \DB::commit();
            $files = $request->file('files');
            if (!empty($files) && is_array($files)) {
                foreach ($files as $key => $file) {
                    $name = time() . $file->getClientOriginalName();
                    $filePath = 'collect-spends/' . $cp->id . '/files/' . str_slug($name);
                    $filePath = $filePath . '.' . $file->getClientOriginalExtension();
                    \Storage::disk('s3')->put($filePath, file_get_contents($file), 'public');
                    CollectSpendFile::create([
                        'collect_spend_id' => $cp->id,
                        'name' => $file->getClientOriginalName(),
                        'file' => 'https://resident.sgp1.digitaloceanspaces.com/' . $filePath
                    ]);
                }
            }

            $user = Functions::getCurrentUser();
            $desc = '{' . optional($user)->name . '} vừa thu {' . number_format($cp->amount, 0, '.', '.') . '} với nội dung {' . $request->input('name') . '}';
            event(new LogAction([
                'type' => 'create-collect',
                'user_id' => optional($user)->id,
                'object_id' => $cp->id,
                'hostel_id' => $cp->hostel_id,
                'room_id' => $cp->room_id,
                'properties' => $cp->toArray(),
                'desc' => $desc
            ]));
        } catch (\Exception $exception) {
            \DB::rollBack();

            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra vui lòng thử lại sau'
            ]);
        }

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    public function edit(Request $request)
    {
        $data = $request->except([
            'repeat_every',
            'repeat_every_custom',
            'repeat_type_custom',
            'cycles',
            'unlimited_cycles'
        ]);

        $amount = $data['amount'];

        if (empty($amount)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống số tiền'
            ]);
        }

        $amount = Functions::filterInputNumber($amount);
        $data['amount'] = $amount;

        if (!is_numeric($amount)) {
            return response([
                'status' => 0,
                'message' => 'Số tiền phải là số'
            ]);
        }

        if (!empty($data['date_action'])) {
            $data['date_action'] = Carbon::createFromFormat('d/m/Y', $data['date_action'])->toDateString();
        } else {
            $data['date_action'] = Carbon::now()->toDateString();
        }

        $roomId = $data['room_id'];
        $hostelId = $data['hostel_id'];

        if ($hostelId) {
            $hostel = Hostel::find($hostelId);
            if ($hostel) {
                $data['hostel_name'] = $hostel->name;
            } else {
                $data['hostel_name'] = null;
            }
        } else {
            $data['hostel_name'] = null;
        }
        if ($roomId) {
            $room = Room::find($roomId);
            if ($room) {
                $data['room_name'] = $room->name;
            } else {
                $data['room_name'] = null;
            }
        } else {
            $data['room_name'] = null;
        }

        try {
            \DB::beginTransaction();

            $collectSpend = CollectSpend::find($data['id']);

            if (!$collectSpend) {
                return response([
                    'status' => 0,
                    'message' => 'Dữ liệu không hợp lệ'
                ]);
            }

            $collectSpend->update($data);



            $dateAction = $collectSpend->date_action;
            if (!empty($dateAction)) {

                $month = $collectSpend->date_action->month;
                $year = $collectSpend->date_action->year;
                StatisticLog::query()->where('collect_spend_id', $collectSpend->id)
                    ->update([
                        'month' => $month,
                        'year' => $year
                    ]);
            }

            $transactionId = $collectSpend->transaction_id;
            $transaction = Transaction::find($transactionId);

            if ($transaction) {
                $transaction->amount = $amount;
                $transaction->save();
            }

            $paid = Transaction::where('money_info_id', $transaction->money_info_id)->sum('amount');
            $moneyInfo = MoneyInfo::find($transaction->money_info_id);
            if ($moneyInfo) {
                $moneyInfo->pay = $paid;
                $moneyInfo->remain = $moneyInfo->amount - $moneyInfo->discount - $paid;
                $moneyInfo->save();
            }

            if (isset($data['receiver'])) {
                $cnt = Receiver::where('name', trim($data['receiver']))
                    ->where('user_id', auth('backend')->user()->id)->count();

                if ($cnt == 0) {
                    Receiver::create([
                        'user_id' => auth('backend')->user()->id,
                        'name' => $data['receiver']
                    ]);
                }
            }


            \DB::commit();
            $files = $request->file('files');
            if (!empty($files) && is_array($files)) {
                foreach ($files as $key => $file) {
                    $name = time() . $file->getClientOriginalName();
                    $filePath = 'collect-spends/' . $collectSpend->id . '/files/' . str_slug($name);
                    $filePath = $filePath . '.' . $file->getClientOriginalExtension();
                    \Storage::disk('s3')->put($filePath, file_get_contents($file), 'public');
                    CollectSpendFile::create([
                        'collect_spend_id' => $collectSpend->id,
                        'name' => $file->getClientOriginalName(),
                        'file' => 'https://resident.sgp1.digitaloceanspaces.com/' . $filePath
                    ]);
                }
            }


            $user = Functions::getCurrentUser();
            if ($collectSpend->type == CollectSpend::SPEND) {
                $desc = '{' . $user->name . '} sửa phiếu chi {' . $collectSpend->name . '}';
                $type = 'update-spend';
            } else {
                $desc = '{' . $user->name . '} sửa phiếu thu {' . $collectSpend->name . '}';
                $type = 'update-collect';
            }
            event(new LogAction([
                'type' => $type,
                'user_id' => optional($user)->id,
                'object_id' => $collectSpend->id,
                'hostel_id' => $collectSpend->hostel_id,
                'room_id' => $collectSpend->room_id,
                'properties' => $collectSpend->toArray(),
                'desc' => $desc
            ]));

        } catch (\Exception $exception) {
            \DB::rollBack();

            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra vui lòng thử lại sau'
            ]);
        }

        $repeatEvery = $request->input('repeat_every');
        if ($repeatEvery) {
            CollectSpendCycle::query()->updateOrCreate([
                'collect_spend_id' => $collectSpend->id,
            ], [
                'collect_spend_id' => $collectSpend->id,
                'repeat_every' => $request->input('repeat_every'),
                'repeat_every_custom' => $request->input('repeat_every_custom'),
                'repeat_type_custom' => $request->input('repeat_type_custom'),
                'cycles' => $request->input('cycles'),
                'unlimited_cycles' => $request->input('unlimited_cycles') == 'on' ? true : false,

            ]);
        } else {
            CollectSpendCycle::query()
                ->where('collect_spend_id', $collectSpend->id)
                ->delete();
        }


        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    public function updateTransactionCollect(Request $request)
    {
        $transactionId = $request->input('transaction_id');
        $amount = Functions::filterInputNumber($request->input('amount'));

        $transaction = Transaction::find($transactionId);

        if (empty($amount)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống số tiền'
            ]);
        }

        if (!is_numeric($amount)) {
            return response([
                'status' => 0,
                'message' => 'Số tiền phải là số'
            ]);
        }

        if (!$transaction) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        try {

            \DB::beginTransaction();

            $transaction->amount = $amount;
            $transaction->save();

            $collectSpend = CollectSpend::where('transaction_id', $transaction->id)->first();
            if ($collectSpend) {
                $collectSpend->amount = $amount;
                $collectSpend->save();
            }

            $paid = Transaction::where('money_info_id', $transaction->money_info_id)->sum('amount');
            $moneyInfo = MoneyInfo::find($transaction->money_info_id);
            if ($moneyInfo) {
                $moneyInfo->pay = $paid;
                $moneyInfo->remain = $moneyInfo->amount - $moneyInfo->discount - $paid;
                $moneyInfo->save();
            }

            \DB::commit();

        } catch (\Exception $exception) {
            \DB::rollBack();

            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra vui lòng thử lại sau'
            ]);
        }

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    public function detailMoneyInfo(Request $request)
    {
        $moneyInfoId = $request->input('money_info_id');
        $details = MoneyDetail::where('money_info_id', $moneyInfoId)->orderBy('id', 'desc')->get();
        $pay = \App\Components\Functions::calculateAmountForOrder($moneyInfoId)['pay'];
        $moneyInfoItem = MoneyInfo::find($moneyInfoId);
        if (!$moneyInfoItem) {
            return response([
                'status' => 0,
                'message' => 'Wrong data'
            ]);
        }
        $sum = 0;
        foreach ($details as $detail) {
            if (!empty($detail->sum_amount)) {
                $sum += $detail->sum_amount;
            } else {
                $sum += $detail->amount;
            }
        }

        return response([
            'status' => 1,
            'data' => view('admin2.money.detail_with_paid', compact('details', 'sum', 'pay', 'moneyInfoItem'))->render(),
            'title' => 'Thông tin hóa đơn ' . $moneyInfoItem->name,
        ]);
    }

    public function editMoneyInfoContract(Request $request)
    {
        $contractId = $request->input('contract_id');

        $month = $request->input('month');
        if (empty($month)) {
            $month = Carbon::now();
        } else {
            $month = Carbon::createFromFormat('d/m/Y', '01/' . $month);
        }
        $contract = Contract::find($contractId);
        $owner = \auth('backend')->user();
        if (\auth('backend')->user()->type == User::STAFF) {
            $owner = \auth('backend')->user()->owner;
        }

        $typeDisplay = $owner->type_display_money_info;
        // $typeDisplay = User::TYPE_DISPLAY_MONEY_INFO_CURRENT_MONTH;
        $moneyInfos = MoneyInfo::query()
            ->where('contract_id', $contractId)
            ->when($typeDisplay == User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH, function ($q) use ($month) {
                $q->where(function ($q) use ($month) {
                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->startOfMonth(),
                            $month->copy()->endOfMonth()
                        ]);
                        $q->whereIn('type', [
                            MoneyInfo::VOUCHER_CONTRACT,
                            MoneyInfo::VOUCHER_ROOM_PRICE
                        ]);
                    });

                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->subMonth()->startOfMonth(),
                            $month->copy()->subMonth()->endOfMonth()
                        ]);
                        $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                    });
                });

            }, function ($q) use ($month) {

                $q->whereBetween('date_action', [
                    $month->copy()->startOfMonth(),
                    $month->copy()->endOfMonth()
                ]);

            })->get();
        return response([
            'status' => 1,
            'data' => view('admin2.money.money_info_contracts', compact('moneyInfos'))->render()
        ]);
    }

    public function detailMoneyInfoContract(Request $request)
    {
        $contractId = $request->input('contract_id');

        $month = $request->input('month');
        if (empty($month)) {
            $month = Carbon::now();
        } else {
            $month = Carbon::createFromFormat('d/m/Y', '01/' . $month);
        }
        $contract = Contract::find($contractId);

        $owner = \auth('backend')->user();
        if (\auth('backend')->user()->type == User::STAFF) {
            $owner = \auth('backend')->user()->owner;
        }

//        $owner->type_display_money_info = User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH;
        $moneyInfos = MoneyInfo::query()
            ->where('contract_id', $contractId)
            ->when($owner->type_display_money_info == User::TYPE_DISPLAY_MONEY_INFO_PREVIOUS_MONTH, function ($q) use ($month) {
                $q->where(function ($q) use ($month) {
                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->startOfMonth(),
                            $month->copy()->endOfMonth()
                        ]);
                        $q->whereIn('type', [
                            MoneyInfo::VOUCHER_CONTRACT,
                            MoneyInfo::VOUCHER_ROOM_PRICE
                        ]);
                    });

                    $q->orWhere(function ($q) use ($month) {
                        $q->whereBetween('date_action', [
                            $month->copy()->subMonth()->startOfMonth(),
                            $month->copy()->subMonth()->endOfMonth()
                        ]);
                        $q->where('type', MoneyInfo::VOUCHER_SERVICE);
                    });
                });

            }, function ($q) use ($month) {

                $q->whereBetween('date_action', [
                    $month->copy()->startOfMonth(),
                    $month->copy()->endOfMonth()
                ]);

            });

        $details = MoneyDetail::query()
            ->whereIn('money_info_id', $moneyInfos->pluck('id')->toArray())
            ->get();
        $payItems = clone $moneyInfos;
        $discountItems = clone $moneyInfos;

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

        $sum = 0;
        foreach ($details as $detail) {
            if (!empty($detail->sum_amount)) {
                $sum += $detail->sum_amount;
            } else {
                $sum += $detail->amount;
            }
        }

        return response([
            'status' => 1,
            'data' => view('admin2.money.detail_with_paid_contract', compact('details', 'sum', 'pay', 'discount'))->render(),
            'title' => 'Thông tin hóa đơn HĐ ' . $contract->code . ' tháng ' . $month->copy()->format('m/Y'),
        ]);
    }

    public function destroy(Request $request)
    {
        $id = $request->input('id');
        $item = CollectSpend::find($id);
        if (!$item) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu không hợp lệ'
            ]);
        }

        if ($item->type == CollectSpend::COLLECT) {
            if (auth('backend')->user()->cannot('delete-collect')) {
                return response([
                    'status' => 0,
                    'message' => 'Bạn không có quyền thực hiện'
                ]);
            }
        }

        if ($item->type == CollectSpend::SPEND) {
            if (auth('backend')->user()->cannot('delete-spend')) {
                return response([
                    'status' => 0,
                    'message' => 'Bạn không có quyền thực hiện'
                ]);
            }
        }

        $hostelId = $item->hostel_id;
        $hostel = Hostel::find($hostelId);

        if ($hostel) {
            if ($hostel->owner_id != auth('backend')->user()->id && $hostel->owner_id != auth('backend')->user()->staff_owner_id) {
                return response([
                    'status' => 0,
                    'message' => 'Dữ liệu không hợp lệ'
                ]);
            }
        }
        $transactionId = $item->transaction_id;

        $moneyInfoId = $item->money_info_id;

        DB::beginTransaction();

        try {

            StatisticLog::query()
                ->where('collect_spend_id', $item->id)
                ->delete();

            $item->delete();

            $transaction = Transaction::find($transactionId);

            if ($transaction) {
                $transaction->delete();
            }

            $moneyInfo = MoneyInfo::find($moneyInfoId);
            if ($moneyInfo) {
                $paid = Functions::calculateAmountForOrder($moneyInfoId)['pay'];
                $moneyInfo->pay = $paid;
                $moneyInfo->remain = $moneyInfo->amount - $moneyInfo->discount - $paid;
                $moneyInfo->save();
            }


            DB::commit();
            $typeName = 'thu';
            if ($item->type == CollectSpend::SPEND) {
                $typeName = 'chi';
            }

            $user = Functions::getCurrentUser();
            $desc = '{' . optional($user)->name . '} xóa phiếu ' . $typeName . ' với nội dung {' . $item->name . '}';
            event(new LogAction([
                'type' => 'delete-collect-spend',
                'user_id' => optional($user)->id,
                'object_id' => $item->id,
                'hostel_id' => $item->hostel_id,
                'room_id' => $item->room_id,
                'properties' => $item->toArray(),
                'desc' => $desc
            ]));

        } catch (\Exception $exception) {
            DB::rollBack();

            return response([
                'status' => 0,
                'message' => 'Có lỗi xảy ra vui lòng thử lại sau'
            ]);
        }

        return response([
            'status' => 1,
            'message' => 'Thành công'
        ]);
    }

    public function listAllUnpaidContractByHostel(Request $request)
    {
        $id = $request->input('hostel_id');
        $token = auth('backend')->user()->token;
        if (empty($token)) {
            $token = uniqid();
            auth('backend')->user()->token = $token;
            auth('backend')->user()->save();
        }

        return response([
            'status' => 1,
            'message' => 'Success!',
            'data' => url('bill/print-all-unpaid-contract-by-hostel?token=' . $token, ['id' => $id]),
        ]);
    }

    public function sendAllUnpaidByHostel(Request $request)
    {
        $id = $request->input('hostel_id');
        $token = auth('backend')->user()->token;
        if (empty($token)) {
            $token = uniqid();
            auth('backend')->user()->token = $token;
            auth('backend')->user()->save();
        }
        $hostel = Hostel::find($id);

        $fromUser = auth('backend')->user()->id;

        if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {
            $hostelRoomUnPaid = MoneyInfo::where('hostel_id', $id)->where('remain', '>', 0)->pluck('room_id')->toArray();
            $conversations = Conversation::whereIn('room_id', array_unique($hostelRoomUnPaid))
                ->whereNotNull('hostel_id')
                ->get();

            if ($conversations->count() <= 0) {
                return response([
                    'status' => 0,
                    'message' => 'Dữ liệu không hợp lệ'
                ]);
            }

            foreach ($conversations as $conversation) {
                $content = 'Danh sách hóa đơn chưa thanh toán: ' . url('bill/print-all-unpaid-contract-by-hostel-room?token=' . $token, [
                        'id' => $id,
                        'room_id' => $conversation->room_id
                    ]);
                $content = strip_tags($content, '<p><a>');
                $message = Message::create([
                    'content' => $content,
                    'conversation_id' => $conversation->id,
                    'type' => Message::TYPE_TEXT,
                    'from' => $fromUser
                ]);


                $conversation->update([
                    'last_message_id' => $message->id,
                    'last_message_time' => Carbon::now()->toDateTimeString()
                ]);
                $messageArr = $message->toArray();
                $content = $message->content;
                $userOnlineArr = [];

                if (isset($usersChannel['result'])) {
                    if (isset($usersChannel['result']['users'])) {
                        foreach ($usersChannel['result']['users'] as $item) {
                            $userIdOnline = $item['id'];
                            $userOnlineArr[] = $userIdOnline;
                        }
                    }
                }


                $membersArr = \DB::table('user_conversations')->where('conversation_id', $conversation->id)->pluck('user_id')->toArray();

                foreach ($membersArr as $userId) {


                    $q = \DB::table('user_conversations')
                        ->where('conversation_id', $conversation->id)
                        ->where('user_id', $userId);

                    if (in_array($userId, $userOnlineArr)) {
                        $q->update([
                            'is_read_last_message' => 1
                        ]);
                    } else {
                        $q->update([
                            'is_read_last_message' => 0
                        ]);
                    }

                    if ($message->type == Message::TYPE_IMAGE || $message->type == Message::TYPE_SYSTEM) {
                        if ($userId == $fromUser) {
                            if ($message->type == Message::TYPE_IMAGE) {
                                $content = 'Bạn đã gửi một ảnh';
                            } else {
                                $content = 'Bạn ' . $content;
                            }
                        } else {
                            $fromUser = $message->fromUser;
                            if ($fromUser) {
                                if ($message->type == Message::TYPE_IMAGE) {
                                    $content = $fromUser->name_text . ' đã gửi một ảnh';
                                } else {
                                    $content = $fromUser->name_text . ' ' . $content;
                                }
                            }
                        }

                    }

                    $messageArr['content'] = $content;


                    $this->pusher->trigger('chat-' . $userId, 'new-message', $messageArr);

                    dispatch(new SendNotificationMessage($userId, $messageArr));
                }
            }
        }

        if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            $hostelRoomUnPaidUsers = MoneyInfo::where('hostel_id', $id)->where('remain', '>', 0)->groupBy('user_id')->get();
            foreach ($hostelRoomUnPaidUsers as $hostelRoomUnPaidUser) {
                $contractId = $hostelRoomUnPaidUser->contract_id;
                $content = 'Hóa đơn chưa thanh toán:' . url('bill/print-all-contract-unpaid?token=' . $token, ['id' => $contractId]);
                $content = strip_tags($content, '<p><a>');
                dispatch(new SendMessageBot($content, $hostelRoomUnPaidUser->user_id, $fromUser));
            }
        }

        return response([
            'status' => 1,
            'message' => 'Thành công',
        ]);
    }

    public function sendAllUnpaidByHostel2(Request $request)
    {
        $id = $request->input('hostel_id');
        $token = auth('backend')->user()->token;
        if (empty($token)) {
            $token = uniqid();
            auth('backend')->user()->token = $token;
            auth('backend')->user()->save();
        }
        if (empty($id)) {
            if (auth('backend')->user()->type == User::STAFF) {
                $hostelArrs = Functions::getHostelArrStaff();
            } else {
                $hostelArrs = Hostel::query()
                    ->where('owner_id', auth('backend')->user()->id)
                    ->pluck('id')
                    ->toArray();
            }

            foreach ($hostelArrs as $hostelArr) {
                $request->request->add([
                    'hostel_id' => $hostelArr
                ]);
                $this->sendAllUnpaidByHostel2($request);
                return response([
                    'status' => 1,
                    'message' => 'Thành công'
                ]);
           }
        }
        $hostel = Hostel::find($id);


        $fromUser = auth('backend')->user()->id;

        if ($hostel->type_rent == Hostel::TYPE_RENT_ALL) {
            $hostelRoomUnPaid = MoneyInfo::where('hostel_id', $id)
                ->where('remain', '>', 0)
                ->pluck('room_id')
                ->toArray();
            $conversations = \App\Models_v2\Conversation::query()->whereIn('room_id', array_unique($hostelRoomUnPaid))
                ->get();

            if ($conversations->count() <= 0) {
                return response([
                    'status' => 0,
                    'message' => 'Dữ liệu không hợp lệ'
                ]);
            }
            //dd($conversations->pluck('id')->toArray());


            foreach ($conversations as $conversation) {
                $content = 'Danh sách hóa đơn chưa thanh toán: ' . url('bill/print-all-unpaid-contract-by-hostel-room?token=' . $token, [
                        'id' => $id,
                        'room_id' => $conversation->room_id
                    ]);
                $content = strip_tags($content, '<p><a>');
                dispatch(new SendMessageV2($conversation->id, $content, auth('backend')->user()->id));
            }
        } else if ($hostel->type_rent == Hostel::TYPE_RENT_EVERY) {
            $hostelRoomUnPaidUsers = MoneyInfo::where('hostel_id', $id)->where('remain', '>', 0)->groupBy('user_id')->get();
            foreach ($hostelRoomUnPaidUsers as $hostelRoomUnPaidUser) {
                $contractId = $hostelRoomUnPaidUser->contract_id;
                $content = 'Hóa đơn chưa thanh toán: ' . url('bill/print-all-contract-unpaid?token=' . $token, ['id' => $contractId]);
                $content = strip_tags($content, '<p><a>');
                dispatch(new SendMessageBotV2($content, $hostelRoomUnPaidUser->user_id, $fromUser))->onConnection('redis');
                // dispatch(new SendMessageBotV2($content, $hostelRoomUnPaidUser->user_id, $fromUser))->onConnection('redis');
            }
        }

        return response([
            'status' => 1,
            'message' => 'Thành công',
        ]);
    }

    public function getZaloHistory(Request $request)
    {
        return view('admin2.money.zalo_log');
    }

    public function getZaloLogByAttribute(Request $request)
    {

        if (\auth('backend')->user()->type == User::OWNER) {
            $ownerId = \auth('backend')->user()->id;
        } else {
            $ownerId = \auth('backend')->user()->staff_owner_id;

        }
        $userArr = User::query()
            ->where(function ($q) use ($ownerId) {
                $q->orWhere('id', $ownerId);
                $q->orWhere('staff_owner_id', $ownerId);
            })
            ->pluck('id')
            ->toArray();

        $items = SendZaloLog::query()
            ->when(!$request->has('order'), function ($q) {
                $q->orderBy('id', 'desc');
            })
            ->whereIn('user_id', $userArr);

        return \datatables()->of($items)
            ->editColumn('hostel_name', function ($item) {
                return optional($item->hostel)->name;
            })
            ->editColumn('room_name', function ($item) {
                return optional($item->room)->name;
            })
            ->editColumn('content', function ($item) {
                return $item->content;
            })
            ->editColumn('created_at', function ($item) {
                return $item->created_at->format('d/m/Y H:i');
            })
            ->editColumn('status', function ($item) {
                return $item->status;
            })
            ->addIndexColumn()
            ->make(true);

    }
}
