<?php

namespace App\Http\Controllers;

use App\Models\qr_user;
use App\Models\qr_settings;
use App\Models\qr_selected_subscription;
use App\Models\qr_subscription;
use App\Models\payAuthentication;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;
use App\Mail\website\QRSubscription;
use Illuminate\Support\Facades\Http;

use Illuminate\Http\Request;

class QrSubscriptionController extends Controller
{
  public function QRSubscription(Request $request)
  {
    $Subscription = $request->input('Subscription');
    $QRid = $request->id;

    // Date Years
    $originalDate = Carbon::now();
    $numberOfYears = 100; // Change this to the desired number of months to increase
    $newDateYears = $originalDate->addYears($numberOfYears);
    // Date Years

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


    if ($Subscription == "1") {

      $QR = qr_user::where(['qr_user_id' => $QRid])->get();

      $stateUpdate = qr_user::where(['qr_user_id' => $QRid])->update([
        'qr_user_state' => "1",
      ]);


      $addSubscription = qr_selected_subscription::create([
        'Subscription_id' => 1,
        'qr_subscription_user_id' => $QRid,
        'qr_subscription_DateToBegin' => $originalDate,
        'qr_subscription_DateToEnd' => $newDateYears,
        'qr_subscription_State' => 1,
        'qr_subscription_PaymentState' => 1,
      ]);

      $sendEmail = Mail::to($QR[0]->qr_user_email)->send(new QRSubscription(Session::get('website_user_name'), $QR[0]->qr_user_name, $QR[0]->qr_user_email, "1"));

      if ($stateUpdate && $addSubscription && $sendEmail) {

        Session::flash('DoneSubscription1', 'تم تسجيل الإشتراك');

        return redirect()->back();
      } else {
        # code...
      }
    } else {

      // Session Save 

      Session::put('qr_subscription_DateToBegin', $newDateMonths);
      Session::put('qr_subscription_DateToEnd', $originalDate);
      Session::put('qr_subscription_user_id', $QRid);
      Session::put('qr_subscription_duration', $numberOfMonths);

      // Session Save 


      // Price Validate =======
      $price = $request->input('totalPrice');
      $subscriptionQuery = qr_subscription::where(['qr_subscriptions_id' => 2])->get();
      $subscriptionPriceQuery = number_format($subscriptionQuery[0]->qr_subscriptions_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 =======
    }
  }
  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" => 4623099
    ];
    $response = Http::post('https://accept.paymob.com/api/acceptance/payment_keys', $data);
    return $response->object()->token;
  }
  // Pay Callback
  public function payQR(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 = qr_subscription::where(['qr_subscriptions_id' => 2])->get();

      $QR = qr_user::where(['qr_user_id' => Session::get('qr_subscription_user_id')])->get();

      $stateUpdate = qr_user::where(['qr_user_id' => Session::get('qr_subscription_user_id')])->update([
        'qr_user_state' => "1",
      ]);


      $addSubscription = qr_selected_subscription::create([
        'Subscription_id' => 2,
        'qr_subscription_user_id' => Session::get('qr_subscription_user_id'),
        'qr_subscription_DateToBegin' => Session::get('qr_subscription_DateToBegin'),
        'qr_subscription_DateToEnd' => Session::get('qr_subscription_DateToEnd'),
        'qr_subscription_State' => 1,
        'qr_subscription_PaymentState' => 1,
      ]);

      $sendEmail = Mail::to($QR[0]->qr_user_email)->send(new QRSubscription(Session::get('website_user_name'), $QR[0]->qr_user_name, $QR[0]->qr_user_email, "2"));

      Session::forget([
        'vendor_subscripe_subscription_id',
        'vendor_subscripe_vendor_id',
        'vendor_subscripe_begindate',
        'vendor_subscripe_enddate',
        'vendor_subscripe_vendor_numberOfMonths',
      ]);
    }
  }
  public function stateQR(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 = qr_subscription::where('qr_subscriptions_Type', 2)->get();

        $QR = qr_user::where(['qr_user_id' => Session::get('qr_subscription_user_id')])->get();

        $stateUpdate = qr_user::where(['qr_user_id' => Session::get('qr_subscription_user_id')])->update([
          'qr_user_state' => "1",
        ]);


        $addSubscription = qr_selected_subscription::create([
          'Subscription_id' => 2,
          'qr_subscription_user_id' => Session::get('qr_subscription_user_id'),
          'qr_subscription_DateToBegin' => Session::get('qr_subscription_DateToBegin'),
          'qr_subscription_DateToEnd' => Session::get('qr_subscription_DateToEnd'),
          'qr_subscription_State' => 1,
          'qr_subscription_PaymentState' => 1,
        ]);

        $sendEmail = Mail::to($QR[0]->qr_user_email)->send(new QRSubscription(Session::get('website_user_name'), $QR[0]->qr_user_name, $QR[0]->qr_user_email, "2"));

        Session::forget([
          'qr_subscription_user_id',
          'qr_subscription_DateToBegin',
          'qr_subscription_DateToEnd',
          'qr_subscription_duration',
        ]);
      }

      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 PoststateQR(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;
  }
  public function QRsubscribePrice(Request $request)
  {
    $subscriptions = qr_subscription::where('qr_subscriptions_Type', 2)->get();


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

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

    return number_format($equation, 2);
  }
}
