<?php

namespace App\Http\Controllers;

use YooKassa\Client;
use Illuminate\Http\Request;
use App\Domain\Points\Models\Point;
use App\Domain\Payments\Models\Withdrawal;
use App\Domain\Points\Enums\DirectionEnum;
use App\Domain\PaymentGateway\Services\QiwiService;
use App\Domain\PaymentGateway\Services\UnitpayService;
use App\Domain\PaymentGateway\Services\YookassaService;
use App\Domain\PaymentGateway\Models\PaymentGatewayOrder;
use App\Domain\PaymentGateway\Services\InterkassaService;
use App\Domain\Subscriptions\Service\SubscriptionService;

class MoneyController extends Controller
{

    public function startProcess(Request $request)
    {

       $this->validate($request, [
           'sum' => 'required|integer|numeric',
       ]);

       $sum = (int) abs($request->input('sum'));

       $amount = round(($sum * 0.035) + $sum, 1);

        $order = PaymentGatewayOrder::yookassa($sum);
        $order_number = ['order_number' => $order->number];

        $point = new Point;
        $point->user_id = auth()->user()->id;
        $point->point = $sum;
        $point->type = 'Ожидание поступления';
        $point->direction = DirectionEnum::PENDING();
        $point->meta = json_encode($order_number);
        $point->save();


        return redirect(YookassaService::payments_link($amount, $order, auth()->user()));
    }

    // public function startProcess()
    // {
    //     $amount = filter_input(INPUT_GET, 'sum', FILTER_VALIDATE_INT);

    //     if(empty($amount)){
    //         return redirect()->back();
    //     }

    //     $order = PaymentGatewayOrder::yookassa($amount);
    //     return redirect(YookassaService::payments_link($amount, $order, auth()->user()));
    // }


    public function checkPointPay($id)
    {

        $point = Point::findOrFail($id);

        if($point->direction != 2){
            return redirect()->route('setting.money')->with('error', 'Ошбика');
        }

        $order_number = json_decode($point->meta);
        if(empty($order_number)){
            return redirect()->route('setting.money')->with('error', 'Ошбика');
        }
        $order = PaymentGatewayOrder::where('number', $order_number->order_number)->first();

        if(empty($order)){
            return redirect()->route('setting.money')->with('error', 'Ошбика');
        }

        if($order->status !== 0){
            return redirect()->route('setting.money')->with('error', 'Ошбика');
        }

        $YOOKASSA_SHOP_ID = env('YOOKASSA_SHOP_ID');
        $YOOKASSA_KEY = env('YOOKASSA_KEY');

        $client = new Client();
        $client->setAuth($YOOKASSA_SHOP_ID, $YOOKASSA_KEY);
        $payment = $client->getPaymentInfo($order->system_payment_id);

        if ($payment->getStatus() === "succeeded")
        {
            $order->status = 1;
            $order->save();

            $point->point = $order->amount;
            $point->type = 'Пополнение счета: ' . $order->type . ' # ' . $order->id;
            $point->direction = DirectionEnum::COMING();
            $point->save();

            return redirect()->route('setting.money')->with('success', 'Счет успешно пополнен!');
        }
        else{

            PaymentGatewayOrder::destroy($order->id);
            Point::destroy($point->id);

            return redirect()->route('setting.money')->with('error', 'Платеж не прошел. Попробуйте еще или выберите другой способ оплаты');
        }

    }

    public function paymentStatus($number)
    {

        $order = PaymentGatewayOrder::where('number', $number)->firstOrFail();

        if($order->status !== 0){
            return redirect()->to('/');
        }

        $YOOKASSA_SHOP_ID = env('YOOKASSA_SHOP_ID');
        $YOOKASSA_KEY = env('YOOKASSA_KEY');
        $client = new Client();
        $client->setAuth($YOOKASSA_SHOP_ID, $YOOKASSA_KEY);
        $payment = $client->getPaymentInfo($order->system_payment_id);

        $point = Point::where('meta->order_number', $number)->first();
        if(empty($point)){
            $point = new Point;
            $point->user_id = auth()->user()->id;
        }

        if ($payment->getStatus() === "succeeded")
        {
            $order->status = 1;
            $order->save();



            $point->point = $order->amount;
            $point->type = 'Пополнение счета: ' . $order->type . ' # ' . $order->id;
            $point->direction = DirectionEnum::COMING();
            $point->save();

            return redirect()->route('setting.money')->with('success', 'Счет успешно пополнен!');
        }
        else{
            PaymentGatewayOrder::destroy($order->id);
            Point::destroy($point->id);
            return redirect()->route('setting.money')->with('error', 'Платеж не прошел. Попробуйте еще или выберите другой способ оплаты');
        }

    }


    // public function qiwiStatus($number)
    // {
    //     $YOOKASSA_SHOP_ID = env('YOOKASSA_SHOP_ID');
    //     $YOOKASSA_KEY = env('YOOKASSA_KEY');
    //     $client = new Client();
    //     $client->setAuth($YOOKASSA_SHOP_ID, $YOOKASSA_KEY);
    //     $payment = $client->getPaymentInfo($number);
    //     dd($payment);

    //     $SECRET_KEY = env('QIWI_SECRET');

    //     $order = PaymentGatewayOrder::where('number', $number)->firstOrFail();
    //     if($order->status !== 0){
    //         return redirect()->to('/');
    //     }

    //     $billPayments = new \Qiwi\Api\BillPayments($SECRET_KEY);
    //     $response = $billPayments->getBillInfo($number);

    //     if ($response['status']['value'] === "PAID")
    //     {
    //         $order->status = 1;
    //         $order->save();

    //         $point = new Point;
    //         $point->user_id = auth()->user()->id;
    //         $point->point = $order->amount;
    //         $point->type = 'Пополнение счета: ' . $order->type . ' # ' . $order->id;
    //         $point->direction = DirectionEnum::COMING();
    //         $point->save();

    //         return redirect()->route('setting.money')->with('success', 'Счет успешно пополнен!');
    //     }
    //     else if ($response['status']['value'] === "WAITING")
    //     {
    //         echo "Ваш платеж в обработке \n Не закрывайте страницу и попробуйте обновить страницу позже";
    //         die;
    //     }


    //     PaymentGatewayOrder::destroy($order->id);

    //     $msg_error = 'Заказ завершен с ошибкой';
    //     if($response['status']['value'] === "REJECTED"){
    //         $msg_error .= ' - Счет отклонен';
    //     }
    //     return redirect()->route('setting.money')->with('error', $msg_error);

    // }

    public function unitpayStatus()
    {
        dd(request()->all());
    }

    public function interkassa()
    {
        $amount = filter_input(INPUT_GET, 'ik_am', FILTER_VALIDATE_INT);

        if(empty($amount)){
            return redirect()->back();
        }

        $order = PaymentGatewayOrder::interkassa($amount);

        return redirect(InterkassaService::payments_link($amount, $order->id));
    }

    public function interkassaStatus()
    {
        $ik_co_id = request()->ik_co_id; // Идентификатор кассы
        $ik_inv_id = request()->ik_inv_id; // Идентификатор платежа в системе Интеркасса
        $ik_inv_st = request()->ik_inv_st; // Состояние платежа. - success; fail
        $ik_pm_no = request()->ik_pm_no; // Номер заказа. example - ID_4233

        if($ik_inv_st === 'success'){
            $order = PaymentGatewayOrder::findOrFail($ik_pm_no);
            if($order->status === 1){
                return redirect()->back();
            }

            $order->status = 1;
            $order->system_payment_id = $ik_inv_id;
            $order->save();

            $point = new Point;
            $point->user_id = auth()->user()->id;
            $point->point = $order->amount;
            $point->type = 'Пополнение счета: ' . $order->type . ' # ' . $order->id;
            $point->direction = DirectionEnum::COMING();
            $point->save();

            return redirect()->route('setting.money')->with('success', 'Счет успешно пополнен!');
        }

        return $this->fails($ik_pm_no, $ik_inv_st);

    }

    protected function fails($order_id, $status)
    {
        PaymentGatewayOrder::destroy($order_id);

        $msg_error = 'Заказ завершен с ошибкой';
        if($status === 'canceled'){
            $msg_error = 'Заказ отменен';
        }
        return redirect()->route('setting.money')->with('error', $msg_error);
    }


    public function payouts()
    {
        $amount = request()->amount;
        $user = auth()->user();
        // $bankRequisites = $user->bank_requisites->first();

        if(!$user->isVerifiedForWithdrawal()){
            return redirect()->back()->with('error', 'Нужно верифицировать аккаунт, загрузить копию паспорта и ввести данные бик, инн, расчетный счет');
            // return redirect()->back()->with('error', 'Нужно верифицировать ваш номер телефона');
        }

        // if(empty($bankRequisites)){
        //     return redirect()->back()->with('error', 'Заполните платежные реквизиты');
        // }

        $balance = SubscriptionService::calculate(auth()->user()->id);
        if ($amount > $balance) {
            return redirect()->back()->with('error', 'Недостаточно средств для вывода');
        }

        if($user->status == 1 || $user->status == 2){
            if (!Withdrawal::canRequestWithdrawalPhysical($user->id, $amount)) {
                return redirect()->back()->with('error', 'Превышен лимит выплат за текущий месяц (12000)');
            }
        }else{
            if (!Withdrawal::canRequestWithdrawalLegal($user->id, $amount)) {
                return redirect()->back()->with('error', 'Превышен лимит выплат за текущий месяц (150000)');
            }
        }



        // $requisites = $bankRequisites->requisites;

        // $detailsDescr[] = 'Тип: по номеру телефона';
        // $detailsDescr[] = 'Номер телефона: ' . $user->phone;
        $detailsDescr[] = 'Тип: Банк';
        // $detailsDescr[] = 'Номер карты: ' . $bankRequisites->number;
        $detailsDescr = implode(PHP_EOL, $detailsDescr);

        $point = new Point;
        $point->user_id = auth()->user()->id;
        $point->point = $amount;
        $point->type = 'Вывод средств (ожидает обработки)'; //YSV ENUM!
        $point->direction = DirectionEnum::EXPENSE();
        $point->save();

        $withdrawal = new Withdrawal;
        $withdrawal->point()->associate($point);
        $withdrawal->user()->associate(auth()->user());
        $withdrawal->requisites_id = 1;
        // $withdrawal->requisites()->associate($requisites);
        $withdrawal->amount = $amount;
        $withdrawal->history_payment_details = $detailsDescr;
        $withdrawal->save();



        return redirect()->back()->with('success', 'Запрос на вывод денег успешно отправлен!');
    }
}
