<?php

namespace App\Http\Controllers\Backend2;

use App\Components\Functions;
use App\Http\Controllers\Backend\AdminController;
use App\Jobs\AddDiscountHostel;
use App\Models\ConfigHostel;
use App\Models\Contract;
use App\Models\Coupon;
use App\Models\DiscountHostel;
use App\Models\Hostel;
use App\Models\MailConfig;
use App\Models\MoneyInfo;
use App\Models\MoneyUnit;
use App\Models\Package;
use App\Models\Renter;
use App\Models\UserMoney;
use App\Models\UserPackage;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Config;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\Shared\Html;

class SettingController extends AdminController
{
    //
    public function index(Request $request)
    {

        return view('admin2.setting.index');
    }

    public function discount(Request $request)
    {
        return view('admin2.setting.discount');
    }

    public function email(Request $request)
    {
        return view('admin2.setting.email');
    }

    public function storeEmail(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        $data = $request->all();
        MailConfig::query()
            ->updateOrCreate([
                'owner_id' => $ownerId
            ], $data);
        return redirect()->back()->with('success', 'Cập nhật thành công');
    }

    public function checkMail(Request  $request)
    {
        try {
            config()->set('mail', [
                'driver' => 'smtp',
                'host' => $request->smtp_server,
                'port' => $request->smtp_port,
                'from' => ['address' => $request->email, 'name' => $request->email],
                'encryption' => $request->encryption,
                'username' => $request->smtp_username,
                'password' => $request->smtp_password
            ]);

            \Mail::raw('Đây là email test cấu hình từ tài khoản user_id: ' . auth('backend')->user()->id, function ($mail) {
                $mail->to('huynt57@gmail.com');
                $mail->subject('Mail test cấu hình itro');
            });
        } catch (\Exception $exception)
        {
            return response([
                'status' => 0
            ]);
        }

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

    public function createDiscount(Request $request)
    {
        $user = auth('backend')->user();
        $hostels = Hostel::query()
            ->when(auth('backend')->user()->type == User::STAFF, function ($q) use ($user) {
                $q->where('owner_id', $user->staff_owner_id);
            }, function ($q) use ($user) {
                $q->where('owner_id', $user->id);
            })->get();

        return response([
            'status' => 1,
            'data' => view('admin2.setting.create_discount', compact('hostels'))->render()
        ]);
    }

    public function editDiscount(Request $request)
    {
        $user = auth('backend')->user();
        $id = $request->input('id');
        $hostels = Hostel::query()
            ->when(auth('backend')->user()->type == User::STAFF, function ($q) use ($user) {
                $q->where('owner_id', $user->staff_owner_id);
            }, function ($q) use ($user) {
                $q->where('owner_id', $user->id);
            })->get();
        $discount = DiscountHostel::find($id);

        return response([
            'status' => 1,
            'data' => view('admin2.setting.edit_discount', compact('hostels', 'discount'))->render()
        ]);
    }

    public function storeDiscount(Request $request)
    {
        $data = $request->all();
        $hostelIds = $request->input('hostel_id');
        if (empty($hostelIds) || !is_array($hostelIds)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống nhà trọ'
            ]);
        }

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

        $date = $request->input('date');
        $discount = Functions::filterInputNumber($request->input('discount'));
        try {
            $dateCarbon = Carbon::createFromFormat('d/m/Y', '01/' . $date);
        } catch (\Exception $exception) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu thời gian không hợp lệ. Format phải là m/Y'
            ]);
        }
        foreach ($hostelIds as $hostelId) {

            $hostel = Hostel::find($hostelId);

            $checkDiscount = DiscountHostel::query()
                ->where('month', $dateCarbon->copy()->month)
                ->where('year', $dateCarbon->copy()->year)
                ->whereHas('hostels', function ($q) use ($hostelId) {
                    $q->where('hostel_id', $hostelId);
                })
                ->count();

            if ($checkDiscount > 0) {
                return response([
                    'status' => 0,
                    'message' => 'Nhà trọ ' . $hostel->name . ' đã được cài giảm giá cho tháng ' . $dateCarbon->copy()->format('m/Y') . ' trước đó'
                ]);
            }

            $checkMoneyInfo = MoneyInfo::query()
                ->whereIn('type', [
                    MoneyInfo::VOUCHER_CONTRACT,
                    MoneyInfo::VOUCHER_ROOM_PRICE
                ])
                ->where('hostel_id', $hostelId)
                ->whereBetween('date_action', [
                    $dateCarbon->copy()->startOfMonth(),
                    $dateCarbon->copy()->endOfMonth()
                ])
                ->where('pay', '<>', 0)
                ->count();

            if ($checkMoneyInfo) {
                return response([
                    'status' => 0,
                    'message' => 'Nhà trọ ' . $hostel->name . ' tồn tại hóa đơn đã thanh toán hoặc thanh toán một phần'
                ]);
            }
        }

        $discountItem = DiscountHostel::create([
            'month' => $dateCarbon->copy()->month,
            'year' => $dateCarbon->copy()->year,
            'date' => $dateCarbon->copy()->toDateString(),
            'user_id' => auth('backend')->user()->id,
            'owner_id' => $ownerId,
            'discount' => $discount
        ]);

        $discountItem->hostels()->sync($hostelIds);

        dispatch(new AddDiscountHostel($discountItem->id));


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

    public function deleteDiscount(Request $request)
    {
        $id = $request->input('id');
        DiscountHostel::query()
            ->where('id', $id)
            ->delete();
        return response([
            'status' => 1
        ]);
    }

    public function updateDiscount(Request $request)
    {
        $data = $request->all();
        $hostelIds = $request->input('hostel_id');
        if (empty($hostelIds) || !is_array($hostelIds)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống nhà trọ'
            ]);
        }

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

        $date = $request->input('date');
        $discount = Functions::filterInputNumber($request->input('discount'));
        try {
            $dateCarbon = Carbon::createFromFormat('d/m/Y', '01/' . $date);
        } catch (\Exception $exception) {
            return response([
                'status' => 0,
                'message' => 'Dữ liệu thời gian không hợp lệ. Format phải là m/Y'
            ]);
        }
        foreach ($hostelIds as $hostelId) {

            $hostel = Hostel::find($hostelId);

            $checkDiscount = DiscountHostel::query()
                ->where('month', $dateCarbon->copy()->month)
                ->where('year', $dateCarbon->copy()->year)
                ->whereHas('hostels', function ($q) use ($hostelId) {
                    $q->where('hostel_id', $hostelId);
                })
                ->count();

            if ($checkDiscount > 0) {
                return response([
                    'status' => 0,
                    'message' => 'Nhà trọ ' . $hostel->name . ' đã được cài giảm giá cho tháng ' . $dateCarbon->copy()->format('m/Y') . ' trước đó'
                ]);
            }

            $checkMoneyInfo = MoneyInfo::query()
                ->with('contract')
                ->where('contract_status', '<>', Contract::LIQUIDATED)
                ->where('hostel_id', $hostelId)
                ->whereIn('type', [
                    MoneyInfo::VOUCHER_CONTRACT,
                    MoneyInfo::VOUCHER_ROOM_PRICE
                ])
                ->whereBetween('date_action', [
                    $dateCarbon->copy()->startOfMonth(),
                    $dateCarbon->copy()->endOfMonth()
                ])
                ->where('pay', '<>', 0)

                ->count();

            if ($checkMoneyInfo) {
                return response([
                    'status' => 0,
                    'message' => 'Nhà trọ ' . $hostel->name . ' tồn tại hóa đơn đã thanh toán hoặc thanh toán một phần'
                ]);
            }
        }

        $discountItem = DiscountHostel::find($request->input('id'));
        $discountItem->update([
            'month' => $dateCarbon->copy()->month,
            'year' => $dateCarbon->copy()->year,
            'date' => $dateCarbon->copy()->toDateString(),
            'user_id' => auth('backend')->user()->id,
            'owner_id' => $ownerId,
            'discount' => $discount
        ]);

        $discountItem->hostels()->sync($hostelIds);
        dispatch(new AddDiscountHostel($discountItem->id));

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

    public function getDiscountsByAttribute(Request $request)
    {
        $user = auth('backend')->user();
        $items = DiscountHostel::query()
            ->when(auth('backend')->user()->type == User::STAFF, function ($q) use ($user) {
                $q->where('owner_id', $user->staff_owner_id);
            }, function ($q) use ($user) {
                $q->where('owner_id', $user->id);
            })
            ->when(!$request->has('order'), function ($q) {
                $q->orderBy('id', 'desc');
            });

        return datatables()->of($items)
            ->addIndexColumn()
            ->filterColumn('user_id', function ($query, $keyword) {
                $query->whereHas('user', function ($q) use ($keyword) {
                    $q->where('users.name', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->filterColumn('hostel_id', function ($query, $keyword) {
                $query->whereHas('hostel', function ($q) use ($keyword) {
                    $q->where('hostels.name', 'LIKE', '%' . $keyword . '%');
                });
            })
            ->editColumn('hostel_id', function ($item) {
                return $item->hostels->pluck('name')->toArray();
            })
            ->editColumn('user_id', function ($item) {
                return optional($item->user)->name_text;
            })
            ->editColumn('date', function ($item) {
                return $item->date->format('m/Y');
            })
            ->editColumn('discount', function ($item) {
                return number_format($item->discount, 0, '.', '.');
            })
            ->editColumn('created_at', function ($item) {
                return $item->created_at->format('d/m/Y');
            })
            ->addColumn('action', function ($item) {
                $retVal = '<a data-id="' . $item->id . '" href="#edit-discount"  data-toggle="modal" class="btn btn-sm btn-outline btn-editable btn-edit-discount purple"><i class="fa fa-edit"></i> Sửa</a>'
                    . '<a data-id="' . $item->id . '"  class="btn btn-sm btn-outline btn-editable btn-delete-discount dark black"><i class="fa fa-trash"></i> Xóa</a>';

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

    public function domain(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $item = Config::where('owner_id', $ownerId)->first();

        return view('admin2.setting.domain', compact('item'));
    }

    public function hotline(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        $hostels = Hostel::where('owner_id', $ownerId)->get();
        $users = User::where('id', $ownerId)->orWhere('staff_owner_id', $ownerId)->get();

        return view('admin2.setting.hotline', compact('hostels', 'users'));
    }

    public function voucher(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        $hostelId = $request->input('hostel_id');
        $hostels = Hostel::query()
            ->where('owner_id', $ownerId)
            ->get();

        if (empty($hostels->count())) {
            return redirect()->back()->with('error', 'Bạn cần thiết lập nhà trọ trước khi thiết lập hóa đơn');
        }

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

        $setting = ConfigHostel::query()
            ->where('owner_id', $ownerId)
            ->where('hostel_id', $hostelId)
            ->first();
        $voucher = null;
        if ($setting) {
            $voucher = $setting->voucher_text;
        }


        return view('admin2.setting.voucher', compact('voucher', 'hostels', 'hostelId'));
    }

    public function storeDomain(Request $request)
    {
        $domain = $request->input('domain');


        if (empty($domain)) {
            return redirect()->back()->with('error', 'Bạn không được bỏ trống địa chỉ');
        }

        $domain = str_replace('.itro.vn', '', $domain);
        $domain = Functions::filterTextNumber($domain);
        $domain = $domain . '.itro.vn';


        auth('backend')->user()->update([
            'domain' => $domain
        ]);

        $file = $request->file('image');
        $link = null;
        if (!empty($file)) {

            $link = Functions::uploadImage($file);
            $ownerId = auth('backend')->user()->id;
            Config::updateOrCreate([
                'owner_id' => $ownerId,
            ], [
                'owner_id' => $ownerId,
                'logo_website' => $link
            ]);
        }

        return redirect()->back()->with('success', 'Thành công. Địa chỉ website của bạn là <a target="_blank" href="http://' . $domain . '">' . $domain . '</a>');
    }

    public function updateHotline(Request $request)
    {
        $hostelId = $request->input('hostel_id');
        $userId = $request->input('user_id');

        $hotline = null;
        $user = User::find($userId);

        if ($user) {
            $hotline = $user->phone;
        }

        $hostel = Hostel::find($hostelId);
        $hostel->hotline = $hotline;
        $hostel->user_hotline = $userId;
        $hostel->save();

        return redirect()->back()->with('success', 'Thành công');
    }

    public function hotlineStaff(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        $hostelId = $request->input('hostel_id');
        $hostel = Hostel::find($hostelId);
        $staffs = \DB::table('staff_hostels')->where('hostel_id', $hostelId)->pluck('user_id')->toArray();
        $users = User::where('id', $ownerId)->orWhereIn('id', $staffs)->get();

        return response([
            'status' => 1,
            'data' => view('admin2.setting.staffs', compact('users', 'hostel'))->render()
        ]);
    }

    public function redeemCoupon(Request $request)
    {
        return view('admin2.setting.coupon');
    }

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

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

        if ($user->type == User::STAFF) {
            $user = User::find($user->staff_owner_id);
        }
        //set unit money
        if (!empty($request->money_unit)) {
            $checkexits = UserMoney::where('user_id', $user->id)->first();
            if (!empty($checkexits)) {
                $checkexits->update([
                    'money_unit' => $request->money_unit,
                ]);
            } else {
                UserMoney::create([
                    'money_unit' => $request->money_unit,
                    'user_id' => $user->id,
                ]);
            }
        }

        $user->update($data);

        return redirect()->back()->with('success', 'Thành công');
    }

    public function redeem(Request $request)
    {
        $coupon = $request->input('coupon');
        $url = $request->input('_url');
        if (empty($coupon)) {
            return redirect()->back()->with('error', 'Không được bỏ trống mã coupon');
        }

        $check = \DB::table('coupon_generates')->where('code', $coupon)->first();

        if (!$check) {
            return redirect()->back()->with('error', 'Coupon không tồn tại');
        }


        if ($check->is_active == 0) {
            return redirect()->back()->with('error', 'Mã coupon chưa được kích hoạt');
        }

        $couponId = $check->coupon_id;
        $couponItem = Coupon::find($couponId);
        if (!$couponItem) {
            return redirect()->back()->with('error', 'Dữ liệu không hợp lệ');
        }

        if (!empty($couponItem->from_date_expire)) {
            if ($couponItem->from_date_expire->greaterThan(Carbon::now())) {
                return redirect()->back()->with('error', 'Coupon chưa thể sử dụng');
            }
        }

        if (!empty($couponItem->end_date_expire)) {
            if ($couponItem->end_date_expire->lessThan(Carbon::now())) {
                return redirect()->back()->with('error', 'Coupon đã quá hạn sử dụng');
            }
        }


        $numberUse = $couponItem->number_use;

        $numberUseBefore = \DB::table('log_coupons')
            ->where('code', $coupon)
            ->count();

        $numberUserInCoupon = \DB::table('log_coupons')
            ->where('coupon_id', $couponItem->id)
            ->count();

        if ($numberUserInCoupon > 1) {
            return [
                'status' => 0,
                'message' => 'Bạn đã tham gia chương trình này trước đó'
            ];
        }

        if ($numberUseBefore >= $numberUse) {
            return redirect()->back()->with('error', 'Coupon đã được sử dụng trước đó');
        }


        $packageId = $couponItem->package_ids;

        $currentPackage = UserPackage::where('user_id', auth('backend')->user()->id)->first();
        $packageApply = $couponItem->package_apply;
        if (!empty($packageApply)) {

            if ($currentPackage) {
                $currentPackageId = $currentPackage->package_id;
                $packageApplyArr = json_decode($packageApply, true);

                if (!in_array(-1, $packageApplyArr)) {
                    if (!in_array($currentPackageId, $packageApplyArr)) {
                        return redirect()->back()->with('error', 'Coupon không áp dụng cho gói cước hiện tại của bạn');
                    }
                }
            }
        }

        $packageName = null;
        $endTime = null;
        try {

            \DB::beginTransaction();

            if ($currentPackage) {
                if (!empty($packageId)) {

                    if ($currentPackage->package_id < $packageId) {

                        $currentPackage->package_id = $packageId;
                    }
                }

                $currentPackage->end_date = $currentPackage->end_date->addMonth($couponItem->number_month_more);
                $currentPackage->save();

                $packageNew = Package::find($packageId);
                if ($packageNew) {
                    $packageName = $packageNew->name;
                }
                $endTime = $currentPackage->end_date->format('d/m/Y');
            }

            \DB::table('log_coupons')->insert([
                'user_id' => auth('backend')->user()->id,
                'coupon_id' => $couponItem->id,
                'coupon_generate_id' => $check->id,
                'code' => $coupon,
                'created_at' => Carbon::now()->toDateTimeString(),
                'updated_at' => Carbon::now()->toDateTimeString(),
            ]);

            \DB::table('coupon_generates')->where('code', $coupon)
                ->update([
                    'status' => Coupon::COUPON_GENERATE_USED,
                    'used_by' => auth('backend')->user()->id,
                    'used_by_name_phone' => auth('backend')->user()->name_text . ' - ' . auth('backend')->user()->phone
                ]);

            \DB::table('coupon_transactions')->where('code', $coupon)
                ->where('coupon_id', $couponId)
                ->update([
                    'status' => Coupon::COUPON_GENERATE_USED,
                ]);

            \DB::commit();

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

            if (!empty($url)) {
                return redirect()->back()->with('error', 'Có lỗi xảy ra vui lòng thử lại sau');
            }

            return redirect()->back()->with('error', 'Có lỗi xảy ra vui lòng thử lại sau');
        }

        if (!empty($url)) {
            return redirect()->to($url)->with('success_coupon', view('admin2.setting.coupon_success', compact('endTime', 'packageName'))->render());
        }

        return redirect()->back()->with('success_coupon', view('admin2.setting.coupon_success', compact('endTime', 'packageName'))->render());
    }

    public function contract(Request $request)
    {

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

        $hostels = Hostel::query()
            ->where('owner_id', $ownerId)
            ->get();
        if (empty($hostels->count())) {
            return redirect()->back()->with('error', 'Bạn cần thiết lập nhà trọ trước khi thiết lập hóa đơn');
        }
        $hostelId = $request->input('hostel_id');
        if (empty($hostelId)) {
            $hostelId = $hostels->first()->id;
        }

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

        if (!$item || empty($item->contract)) {
            $item = Config::query()->where('owner_id', $ownerId)->first();
        }

        if (!$item) {
            $sample = \DB::table('samples')->where('id', 1)->first();
            if ($sample) {
                $item = Config::create([
                    'owner_id' => $ownerId,
                    'voucher_collect' => $sample->voucher_collect,
                    'voucher_spend' => $sample->voucher_spend,
                    'contract' => $sample->contract
                ]);
            }
            //Config::create();
        }

        return view('admin2.setting.contract', compact('item', 'hostels', 'hostelId'));
    }

    public function logo(Request $request)
    {
        $item = Config::query()->where('owner_id', auth('backend')->user()->id)->first();

        return view('admin2.setting.logo', compact('item'));
    }

    public function collect(Request $request)
    {
        $item = Config::query()->where('owner_id', auth('backend')->user()->id)->first();

        return view('admin2.setting.voucher_collect', compact('item'));
    }

    public function spend(Request $request)
    {
        $item = Config::query()->where('owner_id', auth('backend')->user()->id)->first();

        return view('admin2.setting.voucher_spend', compact('item'));
    }

    public function storeLogo(Request $request)
    {
        $file = $request->file('image');
        $link = null;
        if (!empty($file)) {

            $link = Functions::uploadImage($file);
            $ownerId = auth('backend')->user()->id;
            Config::updateOrCreate([
                'owner_id' => $ownerId,
            ], [
                'owner_id' => $ownerId,
                'logo' => $link
            ]);
        }

        return redirect()->back()->with('success', 'Cập nhật thành công');
    }

    public function deleteLogo(Request $request)
    {
        $id = $request->input('id');
        Config::find($id)->delete();

        return redirect()->back()->with('success', 'Xóa thành công');
    }

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

        $contract = $request->input('contract');
        $hostelId = $request->input('hostel_id');

        ConfigHostel::updateOrCreate([
            'owner_id' => $ownerId,
            'hostel_id' => $hostelId
        ], [
            'hostel_id' => $hostelId,
            'owner_id' => $ownerId,
            'contract' => $contract
        ]);

        Config::updateOrCreate([
            'owner_id' => $ownerId,
        ], [
            'owner_id' => $ownerId,
            'contract' => $contract
        ]);

        return redirect()->back()->with('success', 'Cập nhật thành công');
    }

    public function backup(Request $request)
    {
        $ownerId = auth('backend')->user()->id;
        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $item = Config::where('owner_id', $ownerId)->first();

        return view('admin2.setting.backup', compact('item'));
    }

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

        $backupNumberday = $request->input('backup_number_day');
        $backupHour = $request->input('backup_hour');

        Config::updateOrCreate([
            'owner_id' => $ownerId,
        ], [
            'backup_number_day' => $backupNumberday,
            'backup_hour' => $backupHour
        ]);

        return redirect()->back()->with('success', 'Cập nhật thành công');
    }

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

        if (auth('backend')->user()->type == User::STAFF) {
            $ownerId = auth('backend')->user()->staff_owner_id;
        }
        $voucher = $request->input('voucher');
        $hostelId = $request->input('hostel_id');

        ConfigHostel::updateOrCreate([
            'owner_id' => $ownerId,
            'hostel_id' => $hostelId
        ], [
            'hostel_id' => $hostelId,
            'owner_id' => $ownerId,
            'voucher' => $voucher
        ]);

        return redirect()->back()->with('success', 'Cập nhật thành công');
    }

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

        $voucherCollect = $request->input('voucher_collect');

        Config::updateOrCreate([
            'owner_id' => $ownerId,
        ], [
            'owner_id' => $ownerId,
            'voucher_collect' => $voucherCollect
        ]);

        return redirect()->back()->with('success', 'Cập nhật thành công phiếu thu');
    }

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

        $voucherSpend = $request->input('voucher_spend');

        Config::query()->updateOrCreate([
            'owner_id' => $ownerId,
        ], [
            'owner_id' => $ownerId,
            'voucher_spend' => $voucherSpend
        ]);

        return redirect()->back()->with('success', 'Cập nhật thành công phiếu chi');
    }

    public function printContract($id, Request $request)
    {
        $type = $request->input('type', 'print');
        $contract = Contract::find($id);

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

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

        if ($configHostel) {
            if (!empty(optional($configHostel)->contract)) {
                $contractTemplate = $configHostel->contract;
            }
        }

        $renter = Renter::query()->where('user_id', $contract->renter_id)->latest()->first();
        
        


        if ($type == 'download') {

            $isDownload = true;

            $contractTemplate = Functions::getContractTemplate($contract, $contractTemplate, $renter, true);
            // dd($contractTemplate);
            //dd(1);
            $contractTemplate = html_entity_decode($contractTemplate);
            $contractTemplate = preg_replace('/&(?!#?[a-z0-9]+;)/', '-', $contractTemplate);
            //	dd($contractTemplate);
            //var_dump($contractTemplate);die();
//			$contractTemplate = str_replace( '<span style="font-family:"
//Times New Roman",serif">', '<span style="font-family:
//Times New Roman,serif">', $contractTemplate );
            $phpWord = new PhpWord();
            
            $section = $phpWord->addSection();
            
            Html::addHtml($section, $contractTemplate);
            // dd($contractTemplate);
            $dirName = 'hop-dong/hostel-' . $contract->hostel->id . '/room-' . $contract->room->id;
            
            $objectWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
            if (!\File::exists(public_path($dirName))) {
                \File::makeDirectory(public_path($dirName), 0777, true);
            }

            if (\File::exists(public_path($dirName . '/phong-' . str_slug($contract->room->name) . '-nha-tro-' . str_slug($contract->hostel->name) . '.docx'))) {
                \File::delete(public_path($dirName . '/phong-' . str_slug($contract->room->name) . '-nha-tro-' . str_slug($contract->hostel->name) . '.docx'));
            }

            $objectWriter->save(public_path($dirName . '/phong-' . str_slug($contract->room->name) . '-nha-tro-' . str_slug($contract->hostel->name) . '.docx'));

            return redirect()->to(url('/' . $dirName . '/phong-' . str_slug($contract->room->name) . '-nha-tro-' . str_slug($contract->hostel->name) . '.docx'));
        } else {
            $contractTemplate = Functions::getContractTemplate($contract, $contractTemplate, $renter);
        }

        return view('admin2.contract.print', compact('contractTemplate'));
    }


}
