<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Models\payAuthentication;
use App\Models\vendorsSubscriptions;
use App\Models\subscription;
use Carbon\Carbon;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Illuminate\Support\Facades\Mail;
use App\Mail\website\verifyWebsiteUser;

use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Stevebauman\Location\Facades\Location;

class SubscriptionController extends Controller
{
    public function subscriptionPrice(Request $request)
    {
        $id = $request->input('id');

        $vendorsSubscription = vendorsSubscriptions::where(['vendors_subscriptions_id' => $id, 'vendors_subscriptions_State' => "1"])->get();

        $subscriptions = subscription::where(['subscription_id' => $vendorsSubscription[0]->Subscription_id, 'subscription_State' => "1"])->get();

        $numberOfMonths = $request->input('months');

        $equation = $numberOfMonths * $subscriptions[0]->subscription_Price;

        return  number_format($equation, 2);
    }
    public function subscribe(Request $request)
    {
        $subscriptionid = $request->input('Subscription_id');
        $vendorid = $request->segment(4);

        $originalDate = Carbon::now();
        $numberOfMonths = $request->input('months'); // Change this to the desired number of months to increase

        $newDate = $originalDate->addMonths($numberOfMonths);

        // Session Save 

        Session::put('vendor_subscripe_enddate', $newDate);
        Session::put('vendor_subscripe_begindate', $originalDate);
        Session::put('vendor_subscripe_subscription_id', $subscriptionid);
        Session::put('vendor_subscripe_vendor_id', $vendorid);
        Session::put('vendor_subscripe_vendor_numberOfMonths', $numberOfMonths);

        // Session Save 


        // Price Validate =======
        $price = $request->input('totalPrice');
        $subscriptionQuery = subscription::where(['subscription_id' => $subscriptionid])->get();
        $subscriptionPriceQuery = number_format($subscriptionQuery[0]->subscription_Price * $numberOfMonths, 2);

        if ($price == $subscriptionPriceQuery) {
            $priceCents = 00;

            $priceToSend = intval($price) . $priceCents . $priceCents;
            $token = $this->token();
            $order = $this->makeorder($token, $priceToSend);
            $getPaymentToken = $this->getPaymentToken($token, $order, $priceToSend);
            $paylink = ('https://accept.paymobsolutions.com/api/acceptance/iframes/' . "782117" . '?payment_token=' . $getPaymentToken);
            return redirect()->to($paylink);
        } else {
            return "احا";
        }
        // Price Validate =======

    }
    // Pay ================================================================================================
    public function token()
    {
        $Paymobtoken = "ZXlKaGJHY2lPaUpJVXpVeE1pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SmpiR0Z6Y3lJNklrMWxjbU5vWVc1MElpd2ljSEp2Wm1sc1pWOXdheUk2TmpRME1EWTFMQ0p1WVcxbElqb2lNVFk1TWpRek56WXdOaTQxTnpJeU1UWWlmUS5ZenNhVjFQWHFCeURzQmJ5S3BBcDZCZjVObmdON2hSMU5xQ0pHQ2RqRUdyX1gxaFV0ZHh2WVhjN2RDS2FPR05wZWN5dVBGelFTbENEcHRGclFOMEpsQQ==";
        $response = Http::post('https://accept.paymob.com/api/auth/tokens', ['api_key' => $Paymobtoken]);
        return $response->object()->token;
    }
    public function makeorder($token, $priceToSend)
    {
        $data = [
            "auth_token" => $token,
            "delivery_needed" => "false",
            "amount_cents" => $priceToSend,
            "currency" => "EGP",

            // "merchant_order_id" => 22,
        ];
        $response = Http::post('https://accept.paymob.com/api/ecommerce/orders', $data);
        return $response->object();
    }
    public function getPaymentToken($token, $order, $priceToSend)
    {
        $data = [
            "auth_token" => $token,
            "amount_cents" => $priceToSend,
            "expiration" => 3600,
            "order_id" => $order->id,
            "billing_data" => [
                "apartment" => "803",
                "email" => "claudette09@exa.com",
                "floor" => "42",
                "first_name" => "Clifford",
                "street" => "Ethan Land",
                "building" => "8028",
                "phone_number" => "+86(8)9135210487",
                "shipping_method" => "PKG",
                "postal_code" => "01898",
                "city" => "Jaskolskiburgh",
                "country" => "CR",
                "last_name" => "Nicolas",
                "state" => "Utah",

            ],
            "currency" => "EGP",
            "integration_id" => 4110869
        ];
        $response = Http::post('https://accept.paymob.com/api/acceptance/payment_keys', $data);
        return $response->object()->token;
    }
    // Pay Callback
    public function pay(Request $request)
    {

        echo "haha";
        $query = payAuthentication::where(['pay_authentication_Hash' => $request['hmac']])->exists();

        if ($query) {
        } else {
            payAuthentication::create([
                'pay_authentication_Hash' => $request['hmac'],
                'pay_authentication_State' => 1,
                'pay_authentication_amount_cents' => $request['amount_cents'],
            ]);

            $subscription = subscription::where('subscription_id', Session::get('vendor_subscripe_subscription_id'))->get();

            vendorsSubscriptions::create([
                'Subscription_id' => Session::get('vendor_subscripe_subscription_id'),
                'vendors_subscriptions_vendor_id' => Session::get('vendor_subscripe_vendor_id'),
                'vendors_subscriptions_DateToBegin' => Session::get('vendor_subscripe_begindate'),
                'vendors_subscriptions_DateToEnd' => Session::get('vendor_subscripe_enddate'),
                'vendors_subscriptions_Products_limit' => $subscription[0]->subscription_Products_limit,
                'vendors_subscriptions_Admins_limit' => $subscription[0]->subscription_Admins_limit,
                'vendors_subscriptions_State' => "1",
                'vendors_subscriptions_PaymentState' => "1",
                'vendors_subscriptions_duration' => Session::get('vendor_subscripe_vendor_numberOfMonths'),
            ]);
            Session::forget([
                'vendor_subscripe_subscription_id',
                'vendor_subscripe_vendor_id',
                'vendor_subscripe_begindate',
                'vendor_subscripe_enddate',
                'vendor_subscripe_vendor_numberOfMonths',
            ]);
        }
    }
    public function state(Request $request)           // GET CALLBACK
    {
        $data = request()->query();
        $order = $data['order'];
        $Receivedhmac = $data['hmac'];


        $hmac = $data['hmac'];
        $amount_cents = $data['amount_cents'];
        $created_at = $data['created_at'];
        $currency = $data['currency'];
        $error_occured = $data['error_occured'];
        $has_parent_transaction = $data['has_parent_transaction'];
        $id = $data['id'];
        $integration_id = $data['integration_id'];
        $is_3d_secure = $data['is_3d_secure'];
        $is_auth = $data['is_auth'];
        $is_capture = $data['is_capture'];
        $is_refunded = $data['is_refunded'];
        $is_standalone_payment = $data['is_standalone_payment'];
        $is_voided = $data['is_voided'];
        $order_id = $data['order'];
        $owner = $data['owner'];
        $pending = $data['pending'];
        $source_data_pan = $data['source_data_pan'];
        $source_data_sub_type = $data['source_data_sub_type'];
        $source_data_type = $data['source_data_type'];
        $success = $data['success'];


        $request_string = $amount_cents . $created_at . $currency . $error_occured . $has_parent_transaction . $id . $integration_id . $is_3d_secure . $is_auth . $is_capture . $is_refunded . $is_standalone_payment . $is_voided . $order_id . $owner . $pending . $source_data_pan . $source_data_sub_type . $source_data_type . $success;

        $hased = hash_hmac('SHA512', $request_string, 'BFCE8CEC6D9DC2FCEEE59EEC2C6ECFD0');

        if ($Receivedhmac == $hased) {


            $query = payAuthentication::where(['pay_authentication_Hash' => $data['hmac']])->exists();

            if ($query) {
            } else {
                payAuthentication::create([
                    'pay_authentication_Hash' => $request['hmac'],
                    'pay_authentication_State' => 1,
                    'pay_authentication_amount_cents' => $request['amount_cents'],
                ]);

                $subscription = subscription::where('subscription_id', Session::get('vendor_subscripe_subscription_id'))->get();

                vendorsSubscriptions::create([
                    'Subscription_id' => Session::get('vendor_subscripe_subscription_id'),
                    'vendors_subscriptions_vendor_id' => Session::get('vendor_subscripe_vendor_id'),
                    'vendors_subscriptions_DateToBegin' => Session::get('vendor_subscripe_begindate'),
                    'vendors_subscriptions_DateToEnd' => Session::get('vendor_subscripe_enddate'),
                    'vendors_subscriptions_Products_limit' => $subscription[0]->subscription_Products_limit,
                    'vendors_subscriptions_Admins_limit' => $subscription[0]->subscription_Admins_limit,
                    'vendors_subscriptions_State' => "1",
                    'vendors_subscriptions_PaymentState' => "1",
                    'vendors_subscriptions_duration' => Session::get('vendor_subscripe_vendor_numberOfMonths'),
                ]);
                Session::forget([
                    'vendor_subscripe_subscription_id',
                    'vendor_subscripe_vendor_id',
                    'vendor_subscripe_begindate',
                    'vendor_subscripe_enddate',
                    'vendor_subscripe_vendor_numberOfMonths',
                ]);
            }


            // Get the CSRF token
            // $csrfToken = csrf_token();

            // $response = Http::get(route('pay'), $data);


            // Get the response body
            // $responseBody = $response->body();

            // Check if the request was successful
            // if ($response->successful()) {
            //     // Handle the successful response
            //     return response()->json(['message' => 'Request successful', 'data' => $responseBody]);
            // } else {
            //     // Handle the error response
            //     return response()->json(['message' => 'Request failed', 'error' => $response->body()], $response->status());
            // }


            return view('website.callbacks.state', [
                'id' => $id,
                'order' => $order,
                'success' => $success,
                'pending' => $pending,
                'Receivedhmac' => $Receivedhmac,
                'hased' => $hased,
                'amount_cents' => $amount_cents,
                'created_at' => $created_at,

            ]);
        } else {
            return "error";
        }
    }
    public function Poststate(Request $request)        // POST CALLBACK
    {
        $json = json_decode($request);

        $amount_cents = $json->obj->amount_cents;                         // database
        $order_created_at = $json->obj->order->created_at;                // order created_at
        $currency = $json->obj->currency;                                 // currency// database
        $error_occured = $json->obj->error_occured;                       // error occured
        $has_parent_transaction = $json->obj->has_parent_transaction;     // has_parent_transaction
        $transaction_id = $json->obj->id;                                 // transactionID // database
        $integration_id = $json->obj->integration_id;                     // integration_id
        $is_3d_secure = $json->obj->is_3d_secure;                         // is_3d_secure
        $is_auth = $json->obj->is_auth;                                   // is_auth
        $is_capture = $json->obj->is_capture;                             // is_capture
        $is_refunded = $json->obj->is_refunded;                           // is_refunded
        $is_standalone_payment = $json->obj->is_standalone_payment;       // is_standalone_payment
        $is_voided = $json->obj->is_voided;                               // is_voided
        $order_id = $json->obj->order->id;                                // order ID        // database
        $owner = $json->obj->owner;                                       // owner
        $pending = $json->obj->pending;                                   // pending        // database
        $source_data_pan = $json->obj->source_data->pan;                  // source_data pan
        $source_data_type = $json->obj->source_data->type;                // source_data type
        $source_data_sub_type = $json->obj->source_data->sub_type;        // source_data sub_type
        $success = $json->obj->success;                                   // success        // database




        $secure_hash = $json->obj->data->secure_hash;


        $request_string = $amount_cents . $order_created_at . $currency . $error_occured . $has_parent_transaction . $transaction_id . $integration_id . $is_3d_secure . $is_auth . $is_capture . $is_refunded . $is_standalone_payment . $is_voided . $order_id . $owner . $pending . $source_data_pan . $source_data_sub_type . $source_data_type . $success;

        $hased = hash_hmac('SHA512', $request_string, 'BFCE8CEC6D9DC2FCEEE59EEC2C6ECFD0');


        // Purchase

        // Purchase

        return $secure_hash;
    }

    // Pay Callback


    // Pay ================================================================================================

}
