<?php

namespace App\Http\Controllers\Api\v1;

use App\Components\Functions;
use App\Models\Coupon;
use App\Models\Order;
use App\Models\Package;
use App\Models\UserPackage;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PaymentController extends BaseController
{
    //
    /**
     * @api {post} /process-order Tạo đơn hàng
     * @apiName process-order
     * @apiGroup Payment
     * @apiDescription Xử lý đơn hàng
     *
     * @apiParam {String} coupon_code
     * @apiParam {String} package_id
     * @apiParam {String} month số tháng
     * @apiParam {String} rooms số phòng
     * @apiParam {String} payment_type loại thanh toán, 0 là chuyển khoản, 1 là vnpay
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function processOrder(Request $request)
    {
        $data = $request->all();

        $coupon = $request->input('coupon_code');

        $packageId = $request->input('package_id');
        $month = $request->input('month', 1);
        $paymentType = $request->input('payment_type');
        $room = $request->input('rooms');

        $package = Package::find($packageId);

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

        $currentPackage = UserPackage::where('user_id', $this->user->id)->first();
        if ($currentPackage) {
            if (!empty($packageId)) {

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

                    return response([
                        'status' => 0,
                        'message' => 'Bạn không thể chọn gói thấp hơn gói sử dụng hiện tại'
                    ]);
                }
            }

        }

        $price = $package->price_per_month;
        $sum = $price * $month;

        $roomMore = $room - $package->number_rooms;
        $extra = ($roomMore / 10) * $package->price_10_rooms * $month;

        if ($extra > 0) {
            $sum += $extra;
        }


        $newSum = $sum;
        $couponItem = null;
        $discount = 0;
        $extraMonth = 0;

        if (!empty($coupon)) {

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

            if (!$check) {
                return [
                    'status' => 0,
                    'message' => 'Coupon không tồn tại'
                ];
            }

            if ($check->is_active == 0) {
                return [
                    'status' => 0,
                    'message' => 'Coupon chưa được kích hoạt'
                ];
            }

            $couponId = $check->coupon_id;
            $couponItem = Coupon::find($couponId);
            if (!$couponItem) {
                return [
                    'status' => 0,
                    'message' => 'Không tìm thấy mã khuyến mại'
                ];
            }

            if (!empty($couponItem->from_date_expire)) {
                if ($couponItem->from_date_expire->greaterThan(Carbon::now())) {
                    return [
                        'status' => 0,
                        'message' => 'Coupon chưa thể sử dụng'
                    ];
                }
            }

            if (!empty($couponItem->end_date_expire)) {
                if ($couponItem->end_date_expire->lessThan(Carbon::now())) {
                    return [
                        'status' => 0,
                        'message' => 'Coupon đã quá hạn sử dụng'
                    ];
                }
            }

            $extraMonth = $couponItem->number_month_more;
            $discount = 0;

            if ($couponItem->type != 0) {
                if ($couponItem->type == 1) {
                    $discountPercent = $couponItem->percent_reduce;
                    $discount = $discountPercent * $sum / 100;
                    if ($discount > $couponItem->percent_reduce_max) {
                        if (!empty($couponItem->percent_reduce_max)) {
                            $discount = $couponItem->percent_reduce_max;
                        }
                    }
                } else if ($couponItem->type == 2) {
                    $discount = $couponItem->amount_reduce;
                }
            }

            $newSum = $sum - $discount;

            if ($newSum < 0) {
                $newSum = 0;
            }
        }

        $order = Order::create([
            'value' => $sum,
            'package_id' => $packageId,
            'user_id' => $this->user->id,
            'name' => $this->user->name_text,
            'phone' => $this->user->phone,
            'status' => Order::PROCESSING,
            'discount' => $discount,
            'coupon_id' => !empty($couponItem) ? $couponItem->id : null,
            'coupon_code' => $coupon,
            'extra_month' => $extraMonth,
            'month' => $month,
            'rooms' => $room,
            'payment_type' => $paymentType
        ]);

        $url = '';

        if ($paymentType == 1) {
            $url = Functions::buildVnPayUrl($newSum, $request->getClientIp(), null, 'vn', $order->id);
        }

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

    }

    /**
     * @api {get} /payment-info Lấy thông tin khi thanh toán
     * @apiName payment-info
     * @apiGroup Payment
     * @apiDescription Lấy thông tin khi thanh toán
     *
     * @apiParam {String} coupon_code
     * @apiParam {String} package_id
     * @apiParam {String} month số tháng
     * @apiParam {String} room số phòng
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getPaymentCouponInfo(Request $request)
    {
        $coupon = $request->input('coupon_code');
        $room = $request->input('room');

        $packageId = $request->input('package_id');
        $month = $request->input('month', 1);

        $package = Package::find($packageId);

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

        $price = $package->price_per_month;
        $sum = $price * $month;

        $roomMore = $room - $package->number_rooms;
        $extra = ($roomMore / 10) * $package->price_10_rooms * $month;

        if ($extra > 0) {
            $sum += $extra;
        }

        if (empty($coupon)) {
            return response([
                'status' => 0,
                'message' => 'Không được bỏ trống mã coupon'
            ]);
        }

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

        if (!$check) {
            return [
                'status' => 0,
                'message' => 'Coupon không tồn tại'
            ];
        }

        if ($check->is_active == 0) {
            return [
                'status' => 0,
                'message' => 'Coupon chưa được kích hoạt'
            ];
        }

        $couponId = $check->coupon_id;
        $couponItem = Coupon::find($couponId);
        if (!$couponItem) {
            return [
                'status' => 0,
                'message' => 'Không tìm thấy mã khuyến mại'
            ];
        }

        if (!empty($couponItem->from_date_expire)) {
            if ($couponItem->from_date_expire->greaterThan(Carbon::now())) {
                return [
                    'status' => 0,
                    'message' => 'Coupon chưa thể sử dụng'
                ];
            }
        }

        if (!empty($couponItem->end_date_expire)) {
            if ($couponItem->end_date_expire->lessThan(Carbon::now())) {
                return [
                    'status' => 0,
                    'message' => 'Coupon đã quá hạn sử dụng'
                ];
            }
        }

        if($month < $couponItem->minimum_payment_month)
        {
            return [
                'status' => 0,
                'message' => 'Bạn phải thanh toán tối thiểu '.$couponItem->minimum_payment_month.' để áp dụng coupon'
            ];
        }


        $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 [
                'status' => 0,
                'message' => 'Coupon đã được sử dụng trước đó'
            ];
        }
        $packageApply = $couponItem->package_apply;
        $currentPackage = UserPackage::where('user_id', $this->user->id)->first();

        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 response([
                            'status' => 0,
                            'message' => 'Coupon không áp dụng cho gói cước hiện tại của bạn'
                        ]);

                    }
                }
            }
        }

        $extraMonth = $couponItem->number_month_more;
        $discount = 0;

        if ($couponItem->type != 0) {
            if ($couponItem->type == 1) {
                $discountPercent = $couponItem->percent_reduce;
                $discount = $discountPercent * $sum / 100;
                if ($discount > $couponItem->percent_reduce_max) {
                    if (!empty($couponItem->percent_reduce_max)) {
                        $discount = $couponItem->percent_reduce_max;
                    }
                }
            } else if ($couponItem->type == 2) {
                $discount = $couponItem->amount_reduce;
            }
        }

        return response([
            'status' => 1,
            'data' => [
                'discount' => $discount,
                'extra_month' => $extraMonth
            ]
        ]);

    }

    /**
     * @api {get} /packages Lấy thông tin các gói cước
     * @apiName packages
     * @apiGroup Payment
     * @apiDescription Lấy thông tin các gói cước
     *
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
    public function getPackages(Request $request)
    {
        $packages = Package::all()
            ->map(function ($item) {
                $arr = $item->toArray();
                $arr['banner'] = '/files/' . $item->banner;
                return $arr;
            });
        return response([
            'status' => 1,
            'data' => $packages
        ]);
    }
}
