Snippets Collections
import 'package:flutter/material.dart';
import 'package:pets_home/utils.dart';

class CustomSignInButton extends StatelessWidget {
  final String imagePath;
  final String text;
  final VoidCallback onTap;

  const CustomSignInButton({
    Key? key,
    required this.imagePath,
    required this.text,
    required this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.symmetric(horizontal: calculateWidth(31)),
        padding: EdgeInsets.symmetric(horizontal: 0, vertical: calculateHeight(8)),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(32), // Rounded corners
          border: Border.all(
            color: primaryColor, // Border color
            width: 2, // Border width
          ),
        ),
        child: Padding(
          padding: EdgeInsets.only(left: calculateWidth(54)),
          child: Row(
            mainAxisSize: MainAxisSize.min, // Adjusts based on content
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Image.asset(
                imagePath,
                height: calculateHeight(50), // Size of the image
                width: calculateHeight(50),
              ),
              const SizedBox(width: 12), // Spacing between image and text
              Text(
                text,
                style: const TextStyle(
                  color: Colors.brown, // Text color
                  fontSize: 16, // Font size
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}



//call

     Column(
            children: [
              SizedBox(height: calculateHeight(29)),
              CustomSignInButton(
                imagePath: 'assets/google_icon.png', // Google logo path
                text: 'Sign in using Google',
                onTap: () {
                  print('Google Sign-in button tapped');
                  // Google login logic here
                },
              ),
              const SizedBox(height: 16), // Space between buttons
              CustomSignInButton(
                imagePath: 'assets/facebook_icon.png', // Facebook logo path
                text: 'Sign in using Facebook',
                onTap: () {
                  print('Facebook Sign-in button tapped');
                  // Facebook login logic here
                },
              ),
              const SizedBox(height: 16), // Space between buttons
              CustomSignInButton(
                imagePath: 'assets/apple_icon.png', // Apple logo path
                text: 'Sign in using Apple',
                onTap: () {
                  print('Apple Sign-in button tapped');
                  // Apple login logic here
                },
              ),
            ],
          ) 
<?php
// تأكد من تثبيت مكتبة apple-signin-php باستخدام Composer
require_once 'vendor/autoload.php';

use AppleSignIn\ASDecoder;

// إعدادات قاعدة البيانات
$servername = "localhost";
$username = "nullsafety_app";
$password = "gQ0T(DHze!5L";
$dbname = "nullsafety_app";

// إعدادات Apple Sign In
$LOGIN_APPLE_CLIENT_ID = "io.fitness.club";
$LOGIN_APPLE_SECRET = "eyJraWQiOiJMQ1hESDJSTDJSIiwiYWxnIjoiRVMyNTYifQ.eyJpc3MiOiI2TFRESjJITldZIiwiaWF0IjoxNjk3MTQ2MDU2LCJleHAiOjE3MTI2OTgwNTYsImF1ZCI6Imh0dHBzOi8vYXBwbGVpZC5hcHBsZS5jb20iLCJzdWIiOiJpby5maXRuZXNzLmNsdWIifQ.D4YPbDBiRv76ToNUa9Lll1F82uohsgIUzIN4x-NBNahfZuC_A8LTNzFuaBDCBp4m5ohPa9eTc2xoK4NRJjWJWA";

// إنشاء اتصال
$conn = new mysqli($servername, $username, $password, $dbname);

// التحقق من الاتصال
if ($conn->connect_error) {
    die("فشل الاتصال: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // استلام البيانات من Apple
    $id_token = $_POST['id_token'];
    
    try {
        // فك تشفير وتحقق من الـ token
        $appleSignInPayload = ASDecoder::getAppleSignInPayload($id_token);
        
        // استخراج معلومات المستخدم
        $email = $appleSignInPayload->getEmail();
        $user_id = $appleSignInPayload->getUser();
        // الاسم غير متوفر دائمًا، لذا نحتاج للتحقق
        $name = isset($_POST['user']) ? json_decode($_POST['user'])->name : null;
        
        // التحقق مما إذا كان المستخدم موجودًا بالفعل
        $stmt = $conn->prepare("SELECT id FROM users WHERE apple_id = ?");
        $stmt->bind_param("s", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            // المستخدم موجود بالفعل، قم بتحديث المعلومات إذا لزم الأمر
            $stmt = $conn->prepare("UPDATE users SET email = ?, name = ? WHERE apple_id = ?");
            $stmt->bind_param("sss", $email, $name, $user_id);
        } else {
            // مستخدم جديد، قم بإدراجه في قاعدة البيانات
            $stmt = $conn->prepare("INSERT INTO users (apple_id, email, name) VALUES (?, ?, ?)");
            $stmt->bind_param("sss", $user_id, $email, $name);
        }
        
        if ($stmt->execute()) {
            echo "تم تسجيل الدخول وحفظ البيانات بنجاح!";
        } else {
            echo "حدث خطأ أثناء حفظ البيانات: " . $stmt->error;
        }
        
    } catch (Exception $e) {
        echo "حدث خطأ: " . $e->getMessage();
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <title>تسجيل الدخول باستخدام Apple</title>
</head>
<body>
    <div id="appleid-signin" data-color="black" data-border="true" data-type="sign in"></div>
    <script type="text/javascript" src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
    <script type="text/javascript">
        AppleID.auth.init({
            clientId : '<?php echo $LOGIN_APPLE_CLIENT_ID; ?>',
            scope : 'name email',
            redirectURI : 'https://developer.null-safety.com/',
            state : 'YOUR_STATE_VALUE'
        });
    </script>
</body>
</html>
import 'package:flutter/material.dart';

class HighlightTextSearch extends StatelessWidget {
  final String data;
  final String? searchText;
  final bool enable;
  final TextStyle style;
  final Color highlightColor;

  const HighlightTextSearch({
    super.key,
    this.searchText,
    this.enable = true,
    required this.data,
    required this.style,
    this.highlightColor = Colors.amber,
  });

  @override
  Widget build(BuildContext context) {
    if (searchText == null || searchText!.isEmpty && enable == true) {
      return Text(
        data,
        style: style,
        overflow: TextOverflow.ellipsis,
        maxLines: 1,
      );
    }

    final lowerCaseUserName = data.toLowerCase();
    final lowerCaseSearchText = searchText!.toLowerCase();
    final highlightedSpans = <TextSpan>[];

    int start = 0;
    while (start < lowerCaseUserName.length) {
      final index = lowerCaseUserName.indexOf(lowerCaseSearchText, start);
      if (index == -1) {
        highlightedSpans.add(TextSpan(
          text: data.substring(start),
          style: style,
        ));
        break;
      }

      if (index > start) {
        highlightedSpans.add(TextSpan(
          text: data.substring(start, index),
          style: style,
        ));
      }

      highlightedSpans.add(TextSpan(
        text: data.substring(index, index + lowerCaseSearchText.length),
        style: style.copyWith(color: highlightColor),
      ));

      start = index + lowerCaseSearchText.length;
    }

    return RichText(
      text: TextSpan(
        children: highlightedSpans,
      ),
      overflow: TextOverflow.ellipsis,
      maxLines: 1,
    );
  }
}
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../screens/SignUpScreen.dart';

class UserModel {
  String userID;
  String firstName;
  String lastName;
  String email;
  String imageURL;
  bool emailVerified;
  bool profileCompleted;
  String fcmToken;
  String osType;
  String country;
  String flagCode;
  int dateOfBirth;
  String bio;
  Map<String, dynamic> geo; // New geo field
  bool onlineStatus; // New onlineStatus field

  // Default constructor with named parameters
  UserModel({
    this.userID = '',
    this.firstName = '',
    this.lastName = '',
    this.email = '',
    this.imageURL = '',
    this.emailVerified = false,
    this.profileCompleted = false,
    this.fcmToken = '',
    this.osType = '',
    this.country = '',
    this.flagCode = '',
    this.dateOfBirth = 0,
    this.bio = '',
    this.geo = const {}, // Initialize the geo field with an empty map
    this.onlineStatus = false, // Initialize the onlineStatus field
  });

  // Factory constructor to create UserModel from Firestore document
  factory UserModel.fromDocument(DocumentSnapshot document) {
    return UserModel(
      userID: document['userID'] ?? '',
      firstName: document['firstName'] ?? '',
      lastName: document['lastName'] ?? '',
      email: document['email'] ?? '',
      imageURL: document['imageURL'] ?? '',
      emailVerified: document['emailVerified'] ?? false,
      profileCompleted: document['profileCompleted'] ?? false,
      fcmToken: document['fcmToken'] ?? '',
      osType: document['osType'] ?? '',
      country: document['country'] ?? '',
      flagCode: document['flagCode'] ?? '',
      dateOfBirth: document['dateOfBirth'] ?? 0,
      bio: document['bio'] ?? '',
      geo: Map<String, dynamic>.from(document['geo'] ?? {}), // New geo field
      onlineStatus: document['onlineStatus'] ?? false, // New onlineStatus field
    );
  }

  // Factory constructor to create UserModel from a map
  factory UserModel.fromLinkedMap(Map<String, dynamic> map) {
    return UserModel(
      userID: map['userID'] ?? '',
      firstName: map['firstName'] ?? '',
      lastName: map['lastName'] ?? '',
      email: map['email'] ?? '',
      imageURL: map['imageURL'] ?? '',
      emailVerified: map['emailVerified'] ?? false,
      profileCompleted: map['profileCompleted'] ?? false,
      fcmToken: map['fcmToken'] ?? '',
      osType: map['osType'] ?? '',
      country: map['country'] ?? '',
      flagCode: map['flagCode'] ?? '',
      dateOfBirth: map['dateOfBirth'] ?? 0,
      bio: map['bio'] ?? '',
      geo: Map<String, dynamic>.from(map['geo'] ?? {}), // New geo field
      onlineStatus: map['onlineStatus'] ?? false, // New onlineStatus field
    );
  }

  // Method to convert UserModel to a map
  Map<String, dynamic> toMap() {
    return {
      'userID': userID,
      'firstName': firstName,
      'lastName': lastName,
      'email': email,
      'imageURL': imageURL,
      'emailVerified': emailVerified,
      'profileCompleted': profileCompleted,
      'fcmToken': fcmToken,
      'osType': osType,
      'country': country,
      'flagCode': flagCode,
      'dateOfBirth': dateOfBirth,
      'bio': bio,
      'geo': geo, // New geo field
      'onlineStatus': onlineStatus, // New onlineStatus field
    };
  }

  static Future<UserModel?> fetchCurrentUser(String userId, {bool fetchSnapshot = true}) async {
    User? user = FirebaseAuth.instance.currentUser;

    if (user == null) {
      print('User not logged in');
      return null;
    }

    if (userId.isEmpty) {
      userId = user.uid;
    }

    try {
      if (fetchSnapshot) {
        DocumentSnapshot documentSnapshot = await FirebaseFirestore.instance
            .collection('Users')
            .doc(userId)
            .get();

        if (documentSnapshot.exists) {
          return UserModel.fromDocument(documentSnapshot);
        } else {
          print('No document found');
          return null;
        }
      } else {
        // Fetch essential user details if fetchSnapshot is false
        DocumentSnapshot documentSnapshot = await FirebaseFirestore.instance
            .collection('Users')
            .doc(userId)
            .get();

        if (documentSnapshot.exists) {
          return UserModel.fromDocument(documentSnapshot);
        } else {
          print('No document found');
          return null;
        }
      }
    } catch (e) {
      print('Failed to fetch document: $e');
      return null;
    }
  }


  logOut(context) async {
    try {
      await FirebaseAuth.instance.signOut();
      Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => const SignUpScreen()), (route) => false);
    } catch (e) {
      print('Logout failed: $e');
    }
  }
}
if (!function_exists('dd')) {
    function dd(...$vars)
    {
        // ألوان مختلفة ومتناغمة
        $colors = [
            '#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#c2c2f0',
            '#ffb3e6', '#c2f0c2', '#ffccff', '#ffb3b3', '#c2c2c2'
        ];
        $colorCount = count($colors);
        
        // الحصول على معلومات إضافية
        $backtrace = debug_backtrace();
        $debugInfo = [
            'line' => $backtrace[0]['line'],
            'file' => $backtrace[0]['file'],
            'function' => $backtrace[1]['function'] ?? 'N/A',
            'request' => $_REQUEST,
            'session' => $_SESSION ?? []
        ];

        // عرض المعلومات الافتراضية إذا لم يتم تمرير أي متغيرات
        if (empty($vars)) {
            $vars[] = [
                'file' => $debugInfo['file'],
                'line' => $debugInfo['line'],
                'function' => $debugInfo['function'],
                'request' => $debugInfo['request'],
                'session' => $debugInfo['session'],
            ];
        }

        echo '<div style="font-family: Arial, sans-serif; line-height: 1.5;">';
        
        foreach ($vars as $index => $var) {
            // حدد اللون بناءً على الفهرس
            $color = $colors[$index % $colorCount];
            
            echo '<div style="background-color: ' . $color . '; padding: 10px; border-radius: 5px; margin-bottom: 10px; color: #fff;">';
            
            // عنوان البلوك
            echo '<strong>Breakpoint (' . $debugInfo['file'] . ' on line ' . $debugInfo['line'] . ') ---> Function: ' . $debugInfo['function'] . '</strong><br>';
            echo '<strong>Request Data:</strong><br>';
            echo '<pre>' . json_encode($debugInfo['request'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</pre>';
            echo '<strong>Session Data:</strong><br>';
            echo '<pre>' . json_encode($debugInfo['session'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</pre>';
            
            // عرض المتغيرات
            echo '<strong>Variable ' . ($index + 1) . ':</strong><br>';
            if (is_array($var) || is_object($var)) {
                echo '<pre>' . json_encode($var, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</pre>';
            } elseif (is_bool($var) || is_null($var)) {
                var_dump($var);
            } else {
                echo htmlspecialchars($var, ENT_QUOTES, 'UTF-8');
            }
            
            echo '</div>';
        }
        
        echo '</div>';
        die(1);
    }
}
<?php
namespace App\Http\Controllers\Callback;

use App\Models\Gig;
use App\Models\User;
use App\Models\Order;
use Razorpay\Api\Api;
use App\Models\OrderItem;
use App\Models\GigUpgrade;
use Illuminate\Support\Str;
use App\Models\OrderInvoice;
use Illuminate\Http\Request;
use App\Models\DepositWebhook;
use App\Models\CheckoutWebhook;
use App\Models\OrderItemUpgrade;
use App\Models\DepositTransaction;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use App\Models\AutomaticPaymentGateway;
use App\Notifications\User\Buyer\OrderPlaced;
use App\Notifications\User\Seller\PendingOrder;

class RazorpayController extends Controller
{
    public $gateway = "razorpay";
    public $status  = "paid";
    public $settings;


    /**
     * Payment gateway callback
     *
     * @param Request $request
     * @return mixed
     */
    public function callback(Request $request)
    {
        try {
            
            // Get payment gateway settings
            $settings       = AutomaticPaymentGateway::where('slug', $this->gateway)
                                                     ->where('is_active', true)
                                                     ->firstOrFail();

            // Set settings
            $this->settings = $settings;

            // Get payment id
            $payment_id     = $request->get('payment_id');

            // Get order id
            $order_id       = $request->get('order_id');

            // Get signature
            $signature      = $request->get('signature');

            // Get action
            $action         = $request->get('action');

            // Check webhook event
            if ( $payment_id && $order_id && $signature ) {

                // Check if payment succeeded
                $response = $this->verify($payment_id, $order_id, $signature);

                // Check if payment succeeded
                if ( is_array($response) && $response['success'] === TRUE) {

                    // Check if deposit callback
                    if ($action === "D") {
                        
                        // Get saved webhook data in our database
                        $data = DepositWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
        
                        // Handle deposit callback
                        $this->deposit($data->user_id, $data->amount, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('deposit');

                    }
    
                    // Check if checkout callback
                    if ($action === "G") {
                        
                        // Get saved webhook data in our database
                        $data = CheckoutWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
    
                        // Get cart
                        $cart = $data->data['cart'];
    
                        // Get user
                        $user = User::where('id', $data->data['buyer_id'])->firstOrFail();
        
                        // Handle deposit callback
                        $this->checkout($cart, $user, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('gigs');
    
                    }

                }

            }

            // In case failed redirect to home page
            return redirect('/');

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Verify if payment succeeded
     *
     * @param string $id
     * @return array
     */
    private function verify($payment_id, $order_id, $signature)
    {
        try {

            // Get payment gateway keys
            $key_id        = $this->settings?->settings['key_id'];
            $key_secret    = $this->settings?->settings['key_secret'];

            // Set api
            $api           = new Api($key_id, $key_secret);

            // Let's verify first the signature
            $api->utility->verifyPaymentSignature([
                'razorpay_signature'  => $signature,
                'razorpay_payment_id' => $payment_id,
                'razorpay_order_id'   => $order_id
            ]);

            // Fetch this payment
            $fetch_payment = $api->payment->fetch($payment_id);

            // Check if payment authorized
            if ($fetch_payment->status === 'authorized') {
                
                // Let capture this payment
                $payment = $api->payment->fetch($payment_id)->capture([
                    'amount'   => $fetch_payment->amount,
                    'currency' => $fetch_payment->currency
                ]);

            } else if ($fetch_payment->status === 'captured') {
                
                // Set payment
                $payment = $fetch_payment;

            } else {

                // Payment failed
                return [
                    'success'  => false,
                    'message'  => __('messages.t_we_could_not_handle_ur_payment')
                ];

            }

            // Check if payment succeeded
            if ( $payment && $payment->status === 'captured' ) {
                
                // Done
                return [
                    'success'  => true,
                    'response' => $payment
                ];

            } else {

                // Failed
                return [
                    'success' => false,
                    'message' => __('messages.t_error_stripe_payment_failed')
                ];

            }

        } catch (\Throwable $th) {
            
            // Error
            return [
                'success' => false,
                'message' => __('messages.t_toast_something_went_wrong')
            ];

        }
    }


    /**
     * Deposit funds into user's account
     *
     * @param int $user_id
     * @param mixed $amount
     * @param string $payment_id
     * @return void
     */
    private function deposit($user_id, $amount, $payment_id)
    {
        try {
            
            // Set amount
            $amount                  = convertToNumber($amount);
            
            // Calculate fee from this amount
            $fee                     = convertToNumber($this->fee('deposit', $amount)); 

            // Make transaction
            $deposit                 = new DepositTransaction();
            $deposit->user_id        = $user_id;
            $deposit->transaction_id = $payment_id;
            $deposit->payment_method = $this->gateway;
            $deposit->amount_total   = $amount;
            $deposit->amount_fee     = $fee;
            $deposit->amount_net     = $amount - $fee;
            $deposit->currency       = $this->settings->currency;
            $deposit->exchange_rate  = $this->settings->exchange_rate;
            $deposit->status         = $this->status;
            $deposit->ip_address     = request()->ip();
            $deposit->save();

            // Get user
            $user                    = User::where('id', $user_id)->firstOrFail();

            // Add funds
            $user->balance_available = convertToNumber($user->balance_available) + convertToNumber($deposit->amount_net);
            $user->save();

            // Send  a notification
            $this->notification('deposit', $user);

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Checkout
     *
     * @param array $cart
     * @param object $user
     * @param string $payment_id
     * @return void
     */
    private function checkout($cart, $user, $payment_id)
    {
        try {

            // Set empty variables
            $subtotal = 0;
            $total    = 0;
            $tax      = 0;
            $fee      = 0;

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Add gig price to subtotal
                $subtotal += convertToNumber($item['gig']['price']) * convertToNumber($item['quantity']);

                // Check if item has upgrades
                $upgrades  = $item['upgrades'];

                // Loop through upgrades
                if ( isset($upgrades) && is_array($upgrades) && count($upgrades) ) {
                    
                    // Loop through upgrades
                    foreach ($upgrades as $j => $upgrade) {
                        
                        // Check if upgrade checked
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            // Add upgrade price to subtotal
                            $subtotal += convertToNumber($upgrade['price']) * convertToNumber($item['quantity']);

                        }

                    }

                }

            }

            // Get commission settings
            $commission_settings = settings('commission');

            // Check if taxes enabled
            if ($commission_settings->enable_taxes) {
                
                // Check if type of taxes percentage
                if ($commission_settings->tax_type === 'percentage') {
                    
                    // Set tax amount
                    $tax       = convertToNumber(bcmul($subtotal, $commission_settings->tax_value) / 100);

                } else {
                    
                    // Set tax amount
                    $tax       = convertToNumber($commission_settings->tax_value);

                }

            }

            // Calculate payment gateway fee
            $fee                   = convertToNumber($this->fee( 'gigs', $subtotal ));
            
            // Calculate total price
            $total                 = $subtotal + $tax + $fee;
        
            // Get user billing address
            $billing_info          = $user->billing;

            // Set unique id for this order
            $uid                   = uid();

            // Get buyer id
            $buyer_id              = $user->id;

            // Save order
            $order                 = new Order();
            $order->uid            = $uid;
            $order->buyer_id       = $buyer_id;
            $order->total_value    = $total;
            $order->subtotal_value = $subtotal;
            $order->taxes_value    = $tax;
            $order->save();

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Get gig
                $gig = Gig::where('uid', $item['id'])->with('owner')->active()->first();

                // Check if gig exists
                if ($gig) {
                    
                    // Set quantity
                    $quantity        = isset($item['quantity']) ? convertToNumber($item['quantity']) : 1;

                    // Set gig upgrades
                    $upgrades        = isset($item['upgrades']) && is_array($item['upgrades']) && count($item['upgrades']) ? $item['upgrades'] : [];

                    // Set empty variable
                    $upgrades_amount = 0;

                    // Loop through upgrades
                    foreach ($upgrades as $index => $upgrade) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            $upgrades_amount += convertToNumber($upgrade['price']) * $quantity;

                        }

                    }

                    // Set item total price
                    $item_total = $upgrades_amount + ( convertToNumber($item['gig']['price']) * $quantity );

                    // Calculate commission first
                    if ($commission_settings->commission_from === 'orders') {
                        
                        // Check commission type
                        if ($commission_settings->commission_type === 'percentage') {
                            
                            // Calculate commission
                            $commission = convertToNumber($commission_settings->commission_value) * $item_total / 100;
    
                        } else {
    
                            // Fixed amount
                            $commission = convertToNumber($commission_settings->commission_value);
    
                        }

                    } else {
                        
                        // No commission
                        $commission = 0;

                    }

                    // Save order item
                    $order_item                         = new OrderItem();
                    $order_item->uid                    = uid();
                    $order_item->order_id               = $order->id;
                    $order_item->gig_id                 = $gig->id;
                    $order_item->owner_id               = $gig->user_id;
                    $order_item->quantity               = $quantity;
                    $order_item->has_upgrades           = count($upgrades) ? true : false;
                    $order_item->total_value            = $item_total;
                    $order_item->profit_value           = $item_total - $commission;
                    $order_item->commission_value       = $commission;
                    $order_item->save();

                    // Loop through upgrades again
                    foreach ($upgrades as $index => $value) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                        
                            // Get upgrade
                            $upgrade = GigUpgrade::where('uid', $value['id'])->where('gig_id', $gig->id)->first();
    
                            // Check if upgrade exists
                            if ($upgrade) {
                                
                                // Save item upgrade
                                $order_item_upgrade             = new OrderItemUpgrade();
                                $order_item_upgrade->item_id    = $order_item->id;
                                $order_item_upgrade->title      = $upgrade->title;
                                $order_item_upgrade->price      = $upgrade->price;
                                $order_item_upgrade->extra_days = $upgrade->extra_days;
                                $order_item_upgrade->save();
    
                            }

                        }
                        
                    }

                    // Update seller pending balance
                    $gig->owner()->update([
                        'balance_pending' => convertToNumber($gig->owner->balance_pending) + convertToNumber($order_item->profit_value)
                    ]);

                    // Increment orders in queue
                    $gig->increment('orders_in_queue');

                    // Order item placed successfully
                    // Let's notify the seller about new order
                    $gig->owner->notify( (new PendingOrder($order_item))->locale(config('app.locale')) );

                    // Check user's level
                    check_user_level($buyer_id);

                    // Send notification
                    notification([
                        'text'    => 't_u_received_new_order_seller',
                        'action'  => url('seller/orders/details', $order_item->uid),
                        'user_id' => $order_item->owner_id
                    ]);

                }

            }

            // Save invoice
            $invoice                 = new OrderInvoice();
            $invoice->order_id       = $order->id;
            $invoice->payment_method = $this->gateway;
            $invoice->payment_id     = $payment_id;
            $invoice->firstname      = $billing_info->firstname ?? $user->username;
            $invoice->lastname       = $billing_info->lastname ?? $user->username;
            $invoice->email          = $user->email;
            $invoice->company        = !empty($billing_info->company) ? clean($billing_info->company) : null;
            $invoice->address        = !empty($billing_info->address) ? clean($billing_info->address) : "NA";
            $invoice->status         = 'paid';
            $invoice->save();

            // Update balance
            $user->update([
                'balance_purchases' => convertToNumber($user->balance_purchases) + convertToNumber($total)
            ]);

            // Now everything succeeded
            // Let's empty the cart
            session()->forget('cart');

            // Now let's notify the buyer that his order has been placed
            $user->notify( (new OrderPlaced($order))->locale(config('app.locale')) );

        } catch (\Throwable $th) {
            
            // Error
            throw $th;

        }
    }


    /**
     * Calculate fee value
     *
     * @param string $type
     * @param mixed $amount
     * @return mixed
     */
    private function fee($type, $amount = null)
    {
        try {
            
            // Set amount for deposit
            $amount = convertToNumber($amount) * $this->settings?->exchange_rate / settings('currency')->exchange_rate;

            // Remove long decimal
            $amount = convertToNumber( number_format($amount, 2, '.', '') );

            // Check fee type
            switch ($type) {
    
                // Deposit
                case 'deposit':
    
                    // Get deposit fixed fee
                    if (isset($this->settings->fixed_fee['deposit'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['deposit']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get deposit percentage fee
                    if (isset($this->settings->percentage_fee['deposit'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['deposit']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
                    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
                    
                    // Return fee value
                    return number_format($fee_value, 2, '.', '');
    
                break;

                // Gigs
                case 'gigs':

                    // Get gigs fixed fee
                    if (isset($this->settings->fixed_fee['gigs'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['gigs']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get gigs percentage fee
                    if (isset($this->settings->percentage_fee['gigs'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['gigs']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
    
                    // Return fee value
                    return $fee_value;

                break;
    
            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return 0;

        }
    }


    /**
     * Calculate exchange rate
     *
     * @param mixed $amount
     * @param mixed $exchange_rate
     * @param boolean $formatted
     * @param string $currency
     * @return mixed
     */
    private function exchange($amount, $exchange_rate, $formatted = false, $currency = null)
    {
        try {

            // Convert amount to number
            $amount                = convertToNumber($amount);

            // Get currency settings
            $currency_settings     = settings('currency');

            // Get default currency exchange rate
            $default_exchange_rate = convertToNumber($currency_settings->exchange_rate);

            // Get exchanged amount
            $exchanged_amount      = convertToNumber( $amount *  $default_exchange_rate / $exchange_rate );

            // Check if we have to return a formatted value
            if ($formatted) {
                
                return money( $exchanged_amount, $currency, true )->format();

            }

            // Return max deposit
            return convertToNumber(number_format( $exchanged_amount, 2, '.', '' ));

        } catch (\Throwable $th) {

            // Something went wrong
            return $amount;

        }
    }


    /**
     * Send a notification to user
     *
     * @param string $type
     * @param object $user
     * @return void
     */
    private function notification($type, $user)
    {
        try {
            
            // Check notification type
            switch ($type) {

                // Deposit funds
                case 'deposit':
                    


                break;

                // Gig checkout
                case 'gig':
                    
                    

                break;

                // Project payment
                case 'project':
                    
                    

                break;

                // Bid payment
                case 'bid':
                    
                    

                break;

            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return;

        }
    }


    /**
     * Redirecting
     *
     * @param string $type
     * @param string $status
     * @return void
     */
    private function redirect($type, $status = 'success')
    {
        // Check where to redirect
        switch ($type) {

            // Deposit history
            case 'deposit':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_ur_transaction_has_completed'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_mollie_payment_pending'));

                }
                

            break;

            // Gigs order
            case 'gigs':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_submit_ur_info_now_seller_start_order'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_mollie_payment_pending'));

                }

            break;

        }
    }
}
<?php
namespace App\Http\Controllers\Callback;

use App\Models\Gig;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\GigUpgrade;
use App\Models\OrderInvoice;
use Illuminate\Http\Request;
use App\Models\DepositWebhook;
use App\Models\CheckoutWebhook;
use App\Models\OrderItemUpgrade;
use App\Models\DepositTransaction;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use App\Models\AutomaticPaymentGateway;
use App\Notifications\User\Buyer\OrderPlaced;
use App\Notifications\User\Seller\PendingOrder;

class PaymobPkController extends Controller
{
    public $gateway = "paymob-pk";
    public $status  = "paid";
    public $settings;


    /**
     * Payment gateway callback
     *
     * @param Request $request
     * @return mixed
     */
    public function callback(Request $request)
    {
        try {
            
            // Get payment gateway settings
            $settings       = AutomaticPaymentGateway::where('slug', $this->gateway)
                                                     ->where('is_active', true)
                                                     ->firstOrFail();

            // Set settings
            $this->settings = $settings;

            // Get transaction id
            $transaction_id = $request->get('id');

            // Check webhook event
            if ( $transaction_id ) {

                // Check if payment succeeded
                $response = $this->verify($transaction_id);
                
                // Check if payment succeeded
                if ( is_array($response) && $response['success'] === TRUE) {
                    
                    // Get action
                    $action   = $response['response']['obj']['order']['shipping_data']['shipping_method'];

                    // Check if deposit callback
                    if ( isset($action) && $action === "D" ) {
                        
                        // Get saved webhook data in our database
                        $data = DepositWebhook::where('payment_id', $transaction_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
        
                        // Handle deposit callback
                        $this->deposit($data->user_id, $data->amount, $transaction_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('deposit');

                    }
    
                    // Check if checkout callback
                    if ( isset($action) && $action === "G" ) {
                        
                        // Get saved webhook data in our database
                        $data = CheckoutWebhook::where('payment_id', $transaction_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
    
                        // Get cart
                        $cart = $data->data['cart'];
    
                        // Get user
                        $user = User::where('id', $data->data['buyer_id'])->firstOrFail();
        
                        // Handle deposit callback
                        $this->checkout($cart, $user, $transaction_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('gigs');
    
                    }

                }

            }

            // In case failed redirect to home page
            return redirect('/');

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Verify if payment succeeded
     *
     * @param string $id
     * @return array
     */
    private function verify($id)
    {
        try {

            // Get auth token
            $auth    = Http::acceptJson()->post('https://pakistan.paymob.com/api/auth/tokens', [
                                            'api_key' => $this->settings?->settings['api_key'],
                                        ])->json();

            // Check if token is set
            if (isset($auth['token'])) {

                // Get payment details
                $payment = Http::withToken($auth['token'])
                                ->get("https://pakistan.paymob.com/api/acceptance/transactions/$id")
                                ->json();

                // Check if payment succeeded
                if ( is_array($payment) && isset($payment['obj']['success']) && $payment['obj']['success'] == true ) {
                    
                    // Done
                    return [
                        'success'  => true,
                        'response' => $payment
                    ];

                } else {

                    // Failed
                    return [
                        'success' => false,
                        'message' => __('messages.t_error_stripe_payment_failed')
                    ];

                }

            } else {

                // Failed
                return [
                    'success' => false,
                    'message' => __('messages.t_error_stripe_payment_failed')
                ];

            }

        } catch (\Throwable $th) {
            
            // Error
            return [
                'success' => false,
                'message' => __('messages.t_toast_something_went_wrong')
            ];

        }
    }


    /**
     * Deposit funds into user's account
     *
     * @param int $user_id
     * @param mixed $amount
     * @param string $payment_id
     * @return void
     */
    private function deposit($user_id, $amount, $payment_id)
    {
        try {
            
            // Set amount
            $amount                  = convertToNumber($amount);
            
            // Calculate fee from this amount
            $fee                     = convertToNumber($this->fee('deposit', $amount)); 

            // Make transaction
            $deposit                 = new DepositTransaction();
            $deposit->user_id        = $user_id;
            $deposit->transaction_id = $payment_id;
            $deposit->payment_method = $this->gateway;
            $deposit->amount_total   = $amount;
            $deposit->amount_fee     = $fee;
            $deposit->amount_net     = $amount - $fee;
            $deposit->currency       = $this->settings->currency;
            $deposit->exchange_rate  = $this->settings->exchange_rate;
            $deposit->status         = $this->status;
            $deposit->ip_address     = request()->ip();
            $deposit->save();

            // Get user
            $user                    = User::where('id', $user_id)->firstOrFail();

            // Add funds
            $user->balance_available = convertToNumber($user->balance_available) + convertToNumber($deposit->amount_net);
            $user->save();

            // Send  a notification
            $this->notification('deposit', $user);

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Checkout
     *
     * @param array $cart
     * @param object $user
     * @param string $payment_id
     * @return void
     */
    private function checkout($cart, $user, $payment_id)
    {
        try {

            // Set empty variables
            $subtotal = 0;
            $total    = 0;
            $tax      = 0;
            $fee      = 0;

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Add gig price to subtotal
                $subtotal += convertToNumber($item['gig']['price']) * convertToNumber($item['quantity']);

                // Check if item has upgrades
                $upgrades  = $item['upgrades'];

                // Loop through upgrades
                if ( isset($upgrades) && is_array($upgrades) && count($upgrades) ) {
                    
                    // Loop through upgrades
                    foreach ($upgrades as $j => $upgrade) {
                        
                        // Check if upgrade checked
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            // Add upgrade price to subtotal
                            $subtotal += convertToNumber($upgrade['price']) * convertToNumber($item['quantity']);

                        }

                    }

                }

            }

            // Get commission settings
            $commission_settings = settings('commission');

            // Check if taxes enabled
            if ($commission_settings->enable_taxes) {
                
                // Check if type of taxes percentage
                if ($commission_settings->tax_type === 'percentage') {
                    
                    // Set tax amount
                    $tax       = convertToNumber(bcmul($subtotal, $commission_settings->tax_value) / 100);

                } else {
                    
                    // Set tax amount
                    $tax       = convertToNumber($commission_settings->tax_value);

                }

            }

            // Calculate payment gateway fee
            $fee                   = convertToNumber($this->fee( 'gigs', $subtotal ));
            
            // Calculate total price
            $total                 = $subtotal + $tax + $fee;
        
            // Get user billing address
            $billing_info          = $user->billing;

            // Set unique id for this order
            $uid                   = uid();

            // Get buyer id
            $buyer_id              = $user->id;

            // Save order
            $order                 = new Order();
            $order->uid            = $uid;
            $order->buyer_id       = $buyer_id;
            $order->total_value    = $total;
            $order->subtotal_value = $subtotal;
            $order->taxes_value    = $tax;
            $order->save();

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Get gig
                $gig = Gig::where('uid', $item['id'])->with('owner')->active()->first();

                // Check if gig exists
                if ($gig) {
                    
                    // Set quantity
                    $quantity        = isset($item['quantity']) ? convertToNumber($item['quantity']) : 1;

                    // Set gig upgrades
                    $upgrades        = isset($item['upgrades']) && is_array($item['upgrades']) && count($item['upgrades']) ? $item['upgrades'] : [];

                    // Set empty variable
                    $upgrades_amount = 0;

                    // Loop through upgrades
                    foreach ($upgrades as $index => $upgrade) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            $upgrades_amount += convertToNumber($upgrade['price']) * $quantity;

                        }

                    }

                    // Set item total price
                    $item_total = $upgrades_amount + ( convertToNumber($item['gig']['price']) * $quantity );

                    // Calculate commission first
                    if ($commission_settings->commission_from === 'orders') {
                        
                        // Check commission type
                        if ($commission_settings->commission_type === 'percentage') {
                            
                            // Calculate commission
                            $commission = convertToNumber($commission_settings->commission_value) * $item_total / 100;
    
                        } else {
    
                            // Fixed amount
                            $commission = convertToNumber($commission_settings->commission_value);
    
                        }

                    } else {
                        
                        // No commission
                        $commission = 0;

                    }

                    // Save order item
                    $order_item                         = new OrderItem();
                    $order_item->uid                    = uid();
                    $order_item->order_id               = $order->id;
                    $order_item->gig_id                 = $gig->id;
                    $order_item->owner_id               = $gig->user_id;
                    $order_item->quantity               = $quantity;
                    $order_item->has_upgrades           = count($upgrades) ? true : false;
                    $order_item->total_value            = $item_total;
                    $order_item->profit_value           = $item_total - $commission;
                    $order_item->commission_value       = $commission;
                    $order_item->save();

                    // Loop through upgrades again
                    foreach ($upgrades as $index => $value) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                        
                            // Get upgrade
                            $upgrade = GigUpgrade::where('uid', $value['id'])->where('gig_id', $gig->id)->first();
    
                            // Check if upgrade exists
                            if ($upgrade) {
                                
                                // Save item upgrade
                                $order_item_upgrade             = new OrderItemUpgrade();
                                $order_item_upgrade->item_id    = $order_item->id;
                                $order_item_upgrade->title      = $upgrade->title;
                                $order_item_upgrade->price      = $upgrade->price;
                                $order_item_upgrade->extra_days = $upgrade->extra_days;
                                $order_item_upgrade->save();
    
                            }

                        }
                        
                    }

                    // Update seller pending balance
                    $gig->owner()->update([
                        'balance_pending' => convertToNumber($gig->owner->balance_pending) + convertToNumber($order_item->profit_value)
                    ]);

                    // Increment orders in queue
                    $gig->increment('orders_in_queue');

                    // Order item placed successfully
                    // Let's notify the seller about new order
                    $gig->owner->notify( (new PendingOrder($order_item))->locale(config('app.locale')) );

                    // Check user's level
                    check_user_level($buyer_id);

                    // Send notification
                    notification([
                        'text'    => 't_u_received_new_order_seller',
                        'action'  => url('seller/orders/details', $order_item->uid),
                        'user_id' => $order_item->owner_id
                    ]);

                }

            }

            // Save invoice
            $invoice                 = new OrderInvoice();
            $invoice->order_id       = $order->id;
            $invoice->payment_method = $this->gateway;
            $invoice->payment_id     = $payment_id;
            $invoice->firstname      = $billing_info->firstname ?? $user->username;
            $invoice->lastname       = $billing_info->lastname ?? $user->username;
            $invoice->email          = $user->email;
            $invoice->company        = !empty($billing_info->company) ? clean($billing_info->company) : null;
            $invoice->address        = !empty($billing_info->address) ? clean($billing_info->address) : "NA";
            $invoice->status         = 'paid';
            $invoice->save();

            // Update balance
            $user->update([
                'balance_purchases' => convertToNumber($user->balance_purchases) + convertToNumber($total)
            ]);

            // Now everything succeeded
            // Let's empty the cart
            session()->forget('cart');

            // Now let's notify the buyer that his order has been placed
            $user->notify( (new OrderPlaced($order))->locale(config('app.locale')) );

        } catch (\Throwable $th) {
            
            // Error
            throw $th;

        }
    }


    /**
     * Calculate fee value
     *
     * @param string $type
     * @param mixed $amount
     * @return mixed
     */
    private function fee($type, $amount = null)
    {
        try {
            
            // Set amount for deposit
            $amount = convertToNumber($amount) * $this->settings?->exchange_rate / settings('currency')->exchange_rate;

            // Remove long decimal
            $amount = convertToNumber( number_format($amount, 2, '.', '') );

            // Check fee type
            switch ($type) {
    
                // Deposit
                case 'deposit':
    
                    // Get deposit fixed fee
                    if (isset($this->settings->fixed_fee['deposit'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['deposit']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get deposit percentage fee
                    if (isset($this->settings->percentage_fee['deposit'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['deposit']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
                    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
                    
                    // Return fee value
                    return number_format($fee_value, 2, '.', '');
    
                break;

                // Gigs
                case 'gigs':

                    // Get gigs fixed fee
                    if (isset($this->settings->fixed_fee['gigs'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['gigs']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get gigs percentage fee
                    if (isset($this->settings->percentage_fee['gigs'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['gigs']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
    
                    // Return fee value
                    return $fee_value;

                break;
    
            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return 0;

        }
    }


    /**
     * Calculate exchange rate
     *
     * @param mixed $amount
     * @param mixed $exchange_rate
     * @param boolean $formatted
     * @param string $currency
     * @return mixed
     */
    private function exchange($amount, $exchange_rate, $formatted = false, $currency = null)
    {
        try {

            // Convert amount to number
            $amount                = convertToNumber($amount);

            // Get currency settings
            $currency_settings     = settings('currency');

            // Get default currency exchange rate
            $default_exchange_rate = convertToNumber($currency_settings->exchange_rate);

            // Get exchanged amount
            $exchanged_amount      = convertToNumber( $amount *  $default_exchange_rate / $exchange_rate );

            // Check if we have to return a formatted value
            if ($formatted) {
                
                return money( $exchanged_amount, $currency, true )->format();

            }

            // Return max deposit
            return convertToNumber(number_format( $exchanged_amount, 2, '.', '' ));

        } catch (\Throwable $th) {

            // Something went wrong
            return $amount;

        }
    }


    /**
     * Send a notification to user
     *
     * @param string $type
     * @param object $user
     * @return void
     */
    private function notification($type, $user)
    {
        try {
            
            // Check notification type
            switch ($type) {

                // Deposit funds
                case 'deposit':
                    


                break;

                // Gig checkout
                case 'gig':
                    
                    

                break;

                // Project payment
                case 'project':
                    
                    

                break;

                // Bid payment
                case 'bid':
                    
                    

                break;

            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return;

        }
    }


    /**
     * Redirecting
     *
     * @param string $type
     * @param string $status
     * @return void
     */
    private function redirect($type, $status = 'success')
    {
        // Check where to redirect
        switch ($type) {

            // Deposit history
            case 'deposit':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_ur_transaction_has_completed'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_mollie_payment_pending'));

                }
                

            break;

            // Gigs order
            case 'gigs':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_submit_ur_info_now_seller_start_order'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_mollie_payment_pending'));

                }

            break;

        }
    }
}
<?php
namespace App\Http\Controllers\Callback;

use App\Models\Gig;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\GigUpgrade;
use Illuminate\Support\Str;
use App\Models\OrderInvoice;
use Illuminate\Http\Request;
use App\Models\DepositWebhook;
use App\Models\CheckoutWebhook;
use App\Models\OrderItemUpgrade;
use App\Models\DepositTransaction;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use App\Models\AutomaticPaymentGateway;
use App\Notifications\User\Buyer\OrderPlaced;
use App\Notifications\User\Seller\PendingOrder;

class FlutterwaveController extends Controller
{
    public $gateway = "flutterwave";
    public $status  = "paid";
    public $settings;


    /**
     * Payment gateway callback
     *
     * @param Request $request
     * @return mixed
     */
    public function callback(Request $request)
    {
        try {
            
            // Get payment gateway settings
            $settings       = AutomaticPaymentGateway::where('slug', $this->gateway)
                                                     ->where('is_active', true)
                                                     ->firstOrFail();

            // Set settings
            $this->settings = $settings;

            // Get transaction id
            $transaction_id = $request->get('transaction_id');

            // Check webhook event
            if ( $transaction_id ) {

                // Check if payment succeeded
                $response = $this->verify($transaction_id);
                
                // Check if payment succeeded
                if ( is_array($response) && $response['success'] === TRUE) {
                    
                    // Get order id
                    $order_id = $response['response']['data']['tx_ref'];

                    // Check if deposit callback
                    if (Str::startsWith($order_id, "DD")) {
                        
                        // Get saved webhook data in our database
                        $data = DepositWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
        
                        // Handle deposit callback
                        $this->deposit($data->user_id, $data->amount, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('deposit');

                    }
    
                    // Check if checkout callback
                    if (Str::startsWith($order_id, "GG")) {
                        
                        // Get saved webhook data in our database
                        $data = CheckoutWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
    
                        // Get cart
                        $cart = $data->data['cart'];
    
                        // Get user
                        $user = User::where('id', $data->data['buyer_id'])->firstOrFail();
        
                        // Handle deposit callback
                        $this->checkout($cart, $user, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('gigs');
    
                    }

                }

            }

            // In case failed redirect to home page
            return redirect('/');

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Verify if payment succeeded
     *
     * @param string $id
     * @return array
     */
    private function verify($id)
    {
        try {

            // Get payment gateway keys
            $secret_key = $this->settings?->settings['secret_key'];

            $response   = Http::withHeaders([
                                    'Authorization' => 'Bearer ' . $secret_key,
                                    'Accept'        => 'application/json',
                                ])->get("https://api.flutterwave.com/v3/transactions/$id/verify")->json();

            // Check if payment succeeded
            if ( is_array($response) && $response['status'] === 'success' ) {
                
                // Done
                return [
                    'success'  => true,
                    'response' => $response
                ];

            } else {

                // Failed
                return [
                    'success' => false,
                    'message' => __('messages.t_error_stripe_payment_failed')
                ];

            }

        } catch (\Throwable $th) {
            
            // Error
            return [
                'success' => false,
                'message' => __('messages.t_toast_something_went_wrong')
            ];

        }
    }


    /**
     * Deposit funds into user's account
     *
     * @param int $user_id
     * @param mixed $amount
     * @param string $payment_id
     * @return void
     */
    private function deposit($user_id, $amount, $payment_id)
    {
        try {
            
            // Set amount
            $amount                  = convertToNumber($amount);
            
            // Calculate fee from this amount
            $fee                     = convertToNumber($this->fee('deposit', $amount)); 

            // Make transaction
            $deposit                 = new DepositTransaction();
            $deposit->user_id        = $user_id;
            $deposit->transaction_id = $payment_id;
            $deposit->payment_method = $this->gateway;
            $deposit->amount_total   = $amount;
            $deposit->amount_fee     = $fee;
            $deposit->amount_net     = $amount - $fee;
            $deposit->currency       = $this->settings->currency;
            $deposit->exchange_rate  = $this->settings->exchange_rate;
            $deposit->status         = $this->status;
            $deposit->ip_address     = request()->ip();
            $deposit->save();

            // Get user
            $user                    = User::where('id', $user_id)->firstOrFail();

            // Add funds
            $user->balance_available = convertToNumber($user->balance_available) + convertToNumber($deposit->amount_net);
            $user->save();

            // Send  a notification
            $this->notification('deposit', $user);

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Checkout
     *
     * @param array $cart
     * @param object $user
     * @param string $payment_id
     * @return void
     */
    private function checkout($cart, $user, $payment_id)
    {
        try {

            // Set empty variables
            $subtotal = 0;
            $total    = 0;
            $tax      = 0;
            $fee      = 0;

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Add gig price to subtotal
                $subtotal += convertToNumber($item['gig']['price']) * convertToNumber($item['quantity']);

                // Check if item has upgrades
                $upgrades  = $item['upgrades'];

                // Loop through upgrades
                if ( isset($upgrades) && is_array($upgrades) && count($upgrades) ) {
                    
                    // Loop through upgrades
                    foreach ($upgrades as $j => $upgrade) {
                        
                        // Check if upgrade checked
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            // Add upgrade price to subtotal
                            $subtotal += convertToNumber($upgrade['price']) * convertToNumber($item['quantity']);

                        }

                    }

                }

            }

            // Get commission settings
            $commission_settings = settings('commission');

            // Check if taxes enabled
            if ($commission_settings->enable_taxes) {
                
                // Check if type of taxes percentage
                if ($commission_settings->tax_type === 'percentage') {
                    
                    // Set tax amount
                    $tax       = convertToNumber(bcmul($subtotal, $commission_settings->tax_value) / 100);

                } else {
                    
                    // Set tax amount
                    $tax       = convertToNumber($commission_settings->tax_value);

                }

            }

            // Calculate payment gateway fee
            $fee                   = convertToNumber($this->fee( 'gigs', $subtotal ));
            
            // Calculate total price
            $total                 = $subtotal + $tax + $fee;
        
            // Get user billing address
            $billing_info          = $user->billing;

            // Set unique id for this order
            $uid                   = uid();

            // Get buyer id
            $buyer_id              = $user->id;

            // Save order
            $order                 = new Order();
            $order->uid            = $uid;
            $order->buyer_id       = $buyer_id;
            $order->total_value    = $total;
            $order->subtotal_value = $subtotal;
            $order->taxes_value    = $tax;
            $order->save();

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Get gig
                $gig = Gig::where('uid', $item['id'])->with('owner')->active()->first();

                // Check if gig exists
                if ($gig) {
                    
                    // Set quantity
                    $quantity        = isset($item['quantity']) ? convertToNumber($item['quantity']) : 1;

                    // Set gig upgrades
                    $upgrades        = isset($item['upgrades']) && is_array($item['upgrades']) && count($item['upgrades']) ? $item['upgrades'] : [];

                    // Set empty variable
                    $upgrades_amount = 0;

                    // Loop through upgrades
                    foreach ($upgrades as $index => $upgrade) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            $upgrades_amount += convertToNumber($upgrade['price']) * $quantity;

                        }

                    }

                    // Set item total price
                    $item_total = $upgrades_amount + ( convertToNumber($item['gig']['price']) * $quantity );

                    // Calculate commission first
                    if ($commission_settings->commission_from === 'orders') {
                        
                        // Check commission type
                        if ($commission_settings->commission_type === 'percentage') {
                            
                            // Calculate commission
                            $commission = convertToNumber($commission_settings->commission_value) * $item_total / 100;
    
                        } else {
    
                            // Fixed amount
                            $commission = convertToNumber($commission_settings->commission_value);
    
                        }

                    } else {
                        
                        // No commission
                        $commission = 0;

                    }

                    // Save order item
                    $order_item                         = new OrderItem();
                    $order_item->uid                    = uid();
                    $order_item->order_id               = $order->id;
                    $order_item->gig_id                 = $gig->id;
                    $order_item->owner_id               = $gig->user_id;
                    $order_item->quantity               = $quantity;
                    $order_item->has_upgrades           = count($upgrades) ? true : false;
                    $order_item->total_value            = $item_total;
                    $order_item->profit_value           = $item_total - $commission;
                    $order_item->commission_value       = $commission;
                    $order_item->save();

                    // Loop through upgrades again
                    foreach ($upgrades as $index => $value) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                        
                            // Get upgrade
                            $upgrade = GigUpgrade::where('uid', $value['id'])->where('gig_id', $gig->id)->first();
    
                            // Check if upgrade exists
                            if ($upgrade) {
                                
                                // Save item upgrade
                                $order_item_upgrade             = new OrderItemUpgrade();
                                $order_item_upgrade->item_id    = $order_item->id;
                                $order_item_upgrade->title      = $upgrade->title;
                                $order_item_upgrade->price      = $upgrade->price;
                                $order_item_upgrade->extra_days = $upgrade->extra_days;
                                $order_item_upgrade->save();
    
                            }

                        }
                        
                    }

                    // Update seller pending balance
                    $gig->owner()->update([
                        'balance_pending' => convertToNumber($gig->owner->balance_pending) + convertToNumber($order_item->profit_value)
                    ]);

                    // Increment orders in queue
                    $gig->increment('orders_in_queue');

                    // Order item placed successfully
                    // Let's notify the seller about new order
                    $gig->owner->notify( (new PendingOrder($order_item))->locale(config('app.locale')) );

                    // Check user's level
                    check_user_level($buyer_id);

                    // Send notification
                    notification([
                        'text'    => 't_u_received_new_order_seller',
                        'action'  => url('seller/orders/details', $order_item->uid),
                        'user_id' => $order_item->owner_id
                    ]);

                }

            }

            // Save invoice
            $invoice                 = new OrderInvoice();
            $invoice->order_id       = $order->id;
            $invoice->payment_method = $this->gateway;
            $invoice->payment_id     = $payment_id;
            $invoice->firstname      = $billing_info->firstname ?? $user->username;
            $invoice->lastname       = $billing_info->lastname ?? $user->username;
            $invoice->email          = $user->email;
            $invoice->company        = !empty($billing_info->company) ? clean($billing_info->company) : null;
            $invoice->address        = !empty($billing_info->address) ? clean($billing_info->address) : "NA";
            $invoice->status         = 'paid';
            $invoice->save();

            // Update balance
            $user->update([
                'balance_purchases' => convertToNumber($user->balance_purchases) + convertToNumber($total)
            ]);

            // Now everything succeeded
            // Let's empty the cart
            session()->forget('cart');

            // Now let's notify the buyer that his order has been placed
            $user->notify( (new OrderPlaced($order))->locale(config('app.locale')) );

        } catch (\Throwable $th) {
            
            // Error
            throw $th;

        }
    }


    /**
     * Calculate fee value
     *
     * @param string $type
     * @param mixed $amount
     * @return mixed
     */
    private function fee($type, $amount = null)
    {
        try {
            
            // Set amount for deposit
            $amount = convertToNumber($amount) * $this->settings?->exchange_rate / settings('currency')->exchange_rate;

            // Remove long decimal
            $amount = convertToNumber( number_format($amount, 2, '.', '') );

            // Check fee type
            switch ($type) {
    
                // Deposit
                case 'deposit':
    
                    // Get deposit fixed fee
                    if (isset($this->settings->fixed_fee['deposit'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['deposit']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get deposit percentage fee
                    if (isset($this->settings->percentage_fee['deposit'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['deposit']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
                    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
                    
                    // Return fee value
                    return number_format($fee_value, 2, '.', '');
    
                break;

                // Gigs
                case 'gigs':

                    // Get gigs fixed fee
                    if (isset($this->settings->fixed_fee['gigs'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['gigs']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get gigs percentage fee
                    if (isset($this->settings->percentage_fee['gigs'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['gigs']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
    
                    // Return fee value
                    return $fee_value;

                break;
    
            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return 0;

        }
    }


    /**
     * Calculate exchange rate
     *
     * @param mixed $amount
     * @param mixed $exchange_rate
     * @param boolean $formatted
     * @param string $currency
     * @return mixed
     */
    private function exchange($amount, $exchange_rate, $formatted = false, $currency = null)
    {
        try {

            // Convert amount to number
            $amount                = convertToNumber($amount);

            // Get currency settings
            $currency_settings     = settings('currency');

            // Get default currency exchange rate
            $default_exchange_rate = convertToNumber($currency_settings->exchange_rate);

            // Get exchanged amount
            $exchanged_amount      = convertToNumber( $amount *  $default_exchange_rate / $exchange_rate );

            // Check if we have to return a formatted value
            if ($formatted) {
                
                return money( $exchanged_amount, $currency, true )->format();

            }

            // Return max deposit
            return convertToNumber(number_format( $exchanged_amount, 2, '.', '' ));

        } catch (\Throwable $th) {

            // Something went wrong
            return $amount;

        }
    }


    /**
     * Send a notification to user
     *
     * @param string $type
     * @param object $user
     * @return void
     */
    private function notification($type, $user)
    {
        try {
            
            // Check notification type
            switch ($type) {

                // Deposit funds
                case 'deposit':
                    


                break;

                // Gig checkout
                case 'gig':
                    
                    

                break;

                // Project payment
                case 'project':
                    
                    

                break;

                // Bid payment
                case 'bid':
                    
                    

                break;

            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return;

        }
    }


    /**
     * Redirecting
     *
     * @param string $type
     * @param string $status
     * @return void
     */
    private function redirect($type, $status = 'success')
    {
        // Check where to redirect
        switch ($type) {

            // Deposit history
            case 'deposit':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_ur_transaction_has_completed'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_mollie_payment_pending'));

                }
                

            break;

            // Gigs order
            case 'gigs':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_submit_ur_info_now_seller_start_order'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_mollie_payment_pending'));

                }

            break;

        }
    }
}
<?php
namespace App\Http\Controllers\Callback;

use App\Models\Gig;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\GigUpgrade;
use Illuminate\Support\Str;
use App\Models\OrderInvoice;
use Illuminate\Http\Request;
use App\Models\DepositWebhook;
use App\Models\CheckoutWebhook;
use App\Models\OrderItemUpgrade;
use App\Models\DepositTransaction;
use App\Http\Controllers\Controller;
use App\Models\AffiliateTransaction;
use App\Models\AffiliateRegisteration;
use App\Models\AutomaticPaymentGateway;
use App\Notifications\User\Buyer\OrderPlaced;
use App\Notifications\User\Seller\PendingOrder;
use Srmklive\PayPal\Services\PayPal as PayPalClient;

class PaypalController extends Controller
{
    public $gateway = "paypal";
    public $status  = "paid";
    public $settings;


    /**
     * Payment gateway callback
     *
     * @param Request $request
     * @return mixed
     */
    public function callback(Request $request)
    {
        try {
            
            // Get payment gateway settings
            $settings       = AutomaticPaymentGateway::where('slug', $this->gateway)
                                                     ->where('is_active', true)
                                                     ->firstOrFail();

            // Set settings
            $this->settings = $settings;

            // Get transaction id
            $transaction_id = $request->get('order');

            // Check webhook event
            if ( $transaction_id ) {

                // Check if payment succeeded
                $response = $this->verify($transaction_id);
                
                // Check if payment succeeded
                if ( is_array($response) && $response['success'] === TRUE) {
                    
                    // Get order id
                    $order_id = $response['response']['purchase_units'][0]['payments']['captures'][0]['invoice_id'];

                    // Check if deposit callback
                    if (Str::startsWith($order_id, "D-")) {
                        
                        // Get saved webhook data in our database
                        $data = DepositWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
        
                        // Handle deposit callback
                        $this->deposit($data->user_id, $data->amount, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('deposit');

                    }
    
                    // Check if checkout callback
                    if (Str::startsWith($order_id, "G-")) {
                        
                        // Get saved webhook data in our database
                        $data = CheckoutWebhook::where('payment_id', $order_id)
                                                ->where('payment_method', $this->gateway)
                                                ->where('status', 'pending')
                                                ->firstOrFail();
    
                        // Get cart
                        $cart = $data->data['cart'];
    
                        // Get user
                        $user = User::where('id', $data->data['buyer_id'])->firstOrFail();
        
                        // Handle deposit callback
                        $this->checkout($cart, $user, $order_id);

                        // Delete saved webhook data in our database
                        $data->delete();

                        // Redirecting
                        return $this->redirect('gigs');
    
                    }

                }

            }

            // In case failed redirect to home page
            return redirect('/');

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Verify if payment succeeded
     *
     * @param string $id
     * @return array
     */
    private function verify($id)
    {
        
            // Get payment gateway keys
            $client_id     = $this->settings?->settings['client_id'];
            $client_secret = $this->settings?->settings['client_secret'];
            $env           = $this->settings?->settings['env'];

            // Set gateway config
            $config = [
                'mode' => 'sandbox' ,
                'live' => [
                    'client_id'     => $client_id,
                    'client_secret' => $client_secret,
                    'app_id'        => '',
                ],
                'sandbox' => [
                    'client_id'     => $client_id,
                    'client_secret' => $client_secret,
                    'app_id'        => '',
                ],
                'payment_action' => 'Sale',
                'currency'       => $this->settings?->currency,
                'notify_url'     => 'https://2lancer.ma/paypal/notify',
                'locale'         => 'en_US',
                'validate_ssl'   => true,
            ];

            // Set paypal provider and config
            $client = new PayPalClient();
    
            // Set client credentials
            $client->setApiCredentials($config);

            // Get paypal access token
            $client->getAccessToken();

            // Capture this order
            $order  = $client->capturePaymentOrder($id);

            // Check if payment succeeded
            if ( is_array($order) && isset($order['status']) && $order['status'] === 'COMPLETED' ) {
                
                // Done
                return [
                    'success'  => true,
                    'response' => $order
                ];

            } else {

                // Failed
                return [
                    'success' => false,
                    'message' => __('messages.t_error_stripe_payment_failed')
                ];

            }

       
    }


    /**
     * Deposit funds into user's account
     *
     * @param int $user_id
     * @param mixed $amount
     * @param string $payment_id
     * @return void
     */
    private function deposit($user_id, $amount, $payment_id)
    {
        try {
            
            // Set amount
            $amount                  = convertToNumber($amount);
            
            // Calculate fee from this amount
            $fee                     = convertToNumber($this->fee('deposit', $amount)); 

            // Make transaction
            $deposit                 = new DepositTransaction();
            $deposit->user_id        = $user_id;
            $deposit->transaction_id = $payment_id;
            $deposit->payment_method = $this->gateway;
            $deposit->amount_total   = $amount;
            $deposit->amount_fee     = $fee;
            $deposit->amount_net     = $amount - $fee;
            $deposit->currency       = $this->settings->currency;
            $deposit->exchange_rate  = $this->settings->exchange_rate;
            $deposit->status         = $this->status;
            $deposit->ip_address     = request()->ip();
            $deposit->save();

            // Get user
            $user                    = User::where('id', $user_id)->firstOrFail();

            // Add funds
            $user->balance_available = convertToNumber($user->balance_available) + convertToNumber($deposit->amount_net);
            $user->save();

            // Send  a notification
            $this->notification('deposit', $user);

        } catch (\Throwable $th) {

            // Error
            throw $th;

        }
    }


    /**
     * Checkout
     *
     * @param array $cart
     * @param object $user
     * @param string $payment_id
     * @return void
     */
    private function checkout($cart, $user, $payment_id)
    {
        try {

            // Set empty variables
            $subtotal = 0;
            $total    = 0;
            $tax      = 0;
            $fee      = 0;

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Add gig price to subtotal
                $subtotal += convertToNumber($item['gig']['price']) * convertToNumber($item['quantity']);

                // Check if item has upgrades
                $upgrades  = $item['upgrades'];

                // Loop through upgrades
                if ( isset($upgrades) && is_array($upgrades) && count($upgrades) ) {
                    
                    // Loop through upgrades
                    foreach ($upgrades as $j => $upgrade) {
                        
                        // Check if upgrade checked
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            // Add upgrade price to subtotal
                            $subtotal += convertToNumber($upgrade['price']) * convertToNumber($item['quantity']);

                        }

                    }

                }

            }

            // Get commission settings
            $commission_settings = settings('commission');

            // Check if taxes enabled
            if ($commission_settings->enable_taxes) {
                
                // Check if type of taxes percentage
                if ($commission_settings->tax_type === 'percentage') {
                    
                    // Set tax amount
                    $tax       = convertToNumber(bcmul($subtotal, $commission_settings->tax_value) / 100);

                } else {
                    
                    // Set tax amount
                    $tax       = convertToNumber($commission_settings->tax_value);

                }

            }

            // Calculate payment gateway fee
            $fee                   = convertToNumber($this->fee( 'gigs', $subtotal ));
            
            // Calculate total price
            $total                 = $subtotal + $tax + $fee;
        
            // Get user billing address
            $billing_info          = $user->billing;

            // Set unique id for this order
            $uid                   = uid();

            // Get buyer id
            $buyer_id              = $user->id;

            // Save order
            $order                 = new Order();
            $order->uid            = $uid;
            $order->buyer_id       = $buyer_id;
            $order->total_value    = $total;
            $order->subtotal_value = $subtotal;
            $order->taxes_value    = $tax;
            $order->save();

            // Loop through items in cart
            foreach ($cart as $key => $item) {
                    
                // Get gig
                $gig = Gig::where('uid', $item['id'])->with('owner')->active()->first();

                // Check if gig exists
                if ($gig) {
                    
                    // Set quantity
                    $quantity        = isset($item['quantity']) ? convertToNumber($item['quantity']) : 1;

                    // Set gig upgrades
                    $upgrades        = isset($item['upgrades']) && is_array($item['upgrades']) && count($item['upgrades']) ? $item['upgrades'] : [];

                    // Set empty variable
                    $upgrades_amount = 0;

                    // Loop through upgrades
                    foreach ($upgrades as $index => $upgrade) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                            
                            $upgrades_amount += convertToNumber($upgrade['price']) * $quantity;

                        }

                    }

                    // Set item total price
                    $item_total = $upgrades_amount + ( convertToNumber($item['gig']['price']) * $quantity );

                    // Calculate commission first
                    if ($commission_settings->commission_from === 'orders') {
                        
                        // Check commission type
                        if ($commission_settings->commission_type === 'percentage') {
                            
                            // Calculate commission
                            $commission = convertToNumber($commission_settings->commission_value) * $item_total / 100;
    
                        } else {
    
                            // Fixed amount
                            $commission = convertToNumber($commission_settings->commission_value);
    
                        }

                    } else {
                        
                        // No commission
                        $commission = 0;

                    }

                    // Save order item
                    $order_item                         = new OrderItem();
                    $order_item->uid                    = uid();
                    $order_item->order_id               = $order->id;
                    $order_item->gig_id                 = $gig->id;
                    $order_item->owner_id               = $gig->user_id;
                    $order_item->quantity               = $quantity;
                    $order_item->has_upgrades           = count($upgrades) ? true : false;
                    $order_item->total_value            = $item_total;
                    $order_item->profit_value           = $item_total - $commission;
                    $order_item->commission_value       = $commission;
                    $order_item->save();

                    // Loop through upgrades again
                    foreach ($upgrades as $index => $value) {
                        
                        // Check if upgrade is selected
                        if ( isset($upgrade['checked']) && $upgrade['checked'] == 1 ) {
                        
                            // Get upgrade
                            $upgrade = GigUpgrade::where('uid', $value['id'])->where('gig_id', $gig->id)->first();
    
                            // Check if upgrade exists
                            if ($upgrade) {
                                
                                // Save item upgrade
                                $order_item_upgrade             = new OrderItemUpgrade();
                                $order_item_upgrade->item_id    = $order_item->id;
                                $order_item_upgrade->title      = $upgrade->title;
                                $order_item_upgrade->price      = $upgrade->price;
                                $order_item_upgrade->extra_days = $upgrade->extra_days;
                                $order_item_upgrade->save();
    
                            }

                        }
                        
                    }

                    // Update seller pending balance
                    $gig->owner()->update([
                        'balance_pending' => convertToNumber($gig->owner->balance_pending) + convertToNumber($order_item->profit_value)
                    ]);

                    // Increment orders in queue
                    $gig->increment('orders_in_queue');

                    // Order item placed successfully
                    // Let's notify the seller about new order
                    $gig->owner->notify( (new PendingOrder($order_item))->locale(config('app.locale')) );

                    // Check user's level
                    check_user_level($buyer_id);

                    // Send notification
                    notification([
                        'text'    => 't_u_received_new_order_seller',
                        'action'  => url('seller/orders/details', $order_item->uid),
                        'user_id' => $order_item->owner_id
                    ]);

                }

            }

            // Save invoice
            $invoice                 = new OrderInvoice();
            $invoice->order_id       = $order->id;
            $invoice->payment_method = $this->gateway;
            $invoice->payment_id     = $payment_id;
            $invoice->firstname      = $billing_info->firstname ?? $user->username;
            $invoice->lastname       = $billing_info->lastname ?? $user->username;
            $invoice->email          = $user->email;
            $invoice->company        = !empty($billing_info->company) ? clean($billing_info->company) : null;
            $invoice->address        = !empty($billing_info->address) ? clean($billing_info->address) : "NA";
            $invoice->status         = 'paid';
            $invoice->save();

            // Update balance
            $user->update([
                'balance_purchases' => convertToNumber($user->balance_purchases) + convertToNumber($total)
            ]);

            // Now everything succeeded
            // Let's empty the cart
            session()->forget('cart');

            // Now let's notify the buyer that his order has been placed
            $user->notify( (new OrderPlaced($order, $total))->locale(config('app.locale')) );

            //check for affiliate registeration and check if expired 
            if(settings('affiliate')->is_enabled)
            {
            $affiliate_register =AffiliateRegisteration::where('user_id', $buyer_id)
                                                        ->where('expires_at','>',now())
                                                        ->first() ;
            if($affiliate_register){
                
                // get referral user
                $referral_user = User::where('id', $affiliate_register->referral_id)->first();
                
                // calculate referral earning
                $referral_earning =(convertToNumber(settings('affiliate')->profit_percentage)/100)*convertToNumber($total);
                   
                // add credit to referral wallet
                $referral_balance = convertToNumber($referral_user->balance_available) + $referral_earning;
                $referral_user->update(['balance_available'=>$referral_balance]);

                // create new affiliate transaction
                $affiliate_transaction = new AffiliateTransaction();
                $affiliate_transaction->user_id = $buyer_id ;
                $affiliate_transaction->referral_id = $referral_user->id ;
                $affiliate_transaction->order_id = $order->id ;
                $affiliate_transaction->referral_earning = $referral_earning ;
                $affiliate_transaction->save();
            }
            }


        } catch (\Throwable $th) {
            
            // Error
            throw $th;

        }
    }


    /**
     * Calculate fee value
     *
     * @param string $type
     * @param mixed $amount
     * @return mixed
     */
    private function fee($type, $amount = null)
    {
        try {
            
            // Set amount for deposit
            $amount = convertToNumber($amount) * $this->settings?->exchange_rate / settings('currency')->exchange_rate;

            // Remove long decimal
            $amount = convertToNumber( number_format($amount, 2, '.', '') );

            // Check fee type
            switch ($type) {
    
                // Deposit
                case 'deposit':
    
                    // Get deposit fixed fee
                    if (isset($this->settings->fixed_fee['deposit'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['deposit']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get deposit percentage fee
                    if (isset($this->settings->percentage_fee['deposit'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['deposit']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
                    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
                    
                    // Return fee value
                    return number_format($fee_value, 2, '.', '');
    
                break;

                // Gigs
                case 'gigs':

                    // Get gigs fixed fee
                    if (isset($this->settings->fixed_fee['gigs'])) {
                        
                        // Set fixed fee
                        $fee_fixed = convertToNumber($this->settings->fixed_fee['gigs']);
    
                    } else {
    
                        // No fixed fee
                        $fee_fixed = 0;
    
                    }
    
                    // Get gigs percentage fee
                    if (isset($this->settings->percentage_fee['gigs'])) {
                        
                        // Set percentage fee
                        $fee_percentage = convertToNumber($this->settings->percentage_fee['gigs']);
    
                    } else {
    
                        // No percentage fee
                        $fee_percentage = 0;
    
                    }
    
                    // Calculate percentage of this amount 
                    $fee_percentage_amount = $this->exchange( $fee_percentage * $amount / 100, $this->settings->exchange_rate );

                    // Calculate exchange rate of this fixed fee
                    $fee_fixed_exchange    = $this->exchange( $fee_fixed,  $this->settings->exchange_rate);
    
                    // Calculate fee value and visible text
                    if ($fee_fixed > 0 && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount) + convertToNumber($fee_fixed_exchange);
    
                    } else if (!$fee_fixed && $fee_percentage > 0) {
                        
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_percentage_amount);
    
                    } else if ($fee_fixed > 0 && !$fee_percentage) {
    
                        // Calculate fee value
                        $fee_value = convertToNumber($fee_fixed_exchange);
                        
                    } else if (!$fee_percentage && !$fee_fixed) {
                        
                        // Calculate fee value
                        $fee_value = 0;
    
                    }
    
                    // Return fee value
                    return $fee_value;

                break;
    
            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return 0;

        }
    }


    /**
     * Calculate exchange rate
     *
     * @param mixed $amount
     * @param mixed $exchange_rate
     * @param boolean $formatted
     * @param string $currency
     * @return mixed
     */
    private function exchange($amount, $exchange_rate, $formatted = false, $currency = null)
    {
        try {

            // Convert amount to number
            $amount                = convertToNumber($amount);

            // Get currency settings
            $currency_settings     = settings('currency');

            // Get default currency exchange rate
            $default_exchange_rate = convertToNumber($currency_settings->exchange_rate);

            // Get exchanged amount
            $exchanged_amount      = convertToNumber( $amount *  $default_exchange_rate / $exchange_rate );

            // Check if we have to return a formatted value
            if ($formatted) {
                
                return money( $exchanged_amount, $currency, true )->format();

            }

            // Return max deposit
            return convertToNumber(number_format( $exchanged_amount, 2, '.', '' ));

        } catch (\Throwable $th) {

            // Something went wrong
            return $amount;

        }
    }


    /**
     * Send a notification to user
     *
     * @param string $type
     * @param object $user
     * @return void
     */
    private function notification($type, $user)
    {
        try {
            
            // Check notification type
            switch ($type) {

                // Deposit funds
                case 'deposit':
                    


                break;

                // Gig checkout
                case 'gig':
                    
                    

                break;

                // Project payment
                case 'project':
                    
                    

                break;

                // Bid payment
                case 'bid':
                    
                    

                break;

            }

        } catch (\Throwable $th) {
            
            // Something went wrong
            return;

        }
    }


    /**
     * Redirecting
     *
     * @param string $type
     * @param string $status
     * @return void
     */
    private function redirect($type, $status = 'success')
    {
        // Check where to redirect
        switch ($type) {

            // Deposit history
            case 'deposit':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_ur_transaction_has_completed'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/deposit/history')->with('success', __('messages.t_mollie_payment_pending'));

                }
                

            break;

            // Gigs order
            case 'gigs':
                
                // Check if payment succeeded
                if ($status === 'success') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_submit_ur_info_now_seller_start_order'));

                } else if ($status === 'pending') {
                    
                    // Redirect to deposit history page
                    return redirect('account/orders')->with('success', __('messages.t_mollie_payment_pending'));

                }

            break;

        }
    }
}
import 'package:flutter/material.dart';

class Responsive extends StatelessWidget {
  final Widget mobile;
  final Widget? tablet;
  final Widget desktop;

  const Responsive({
    Key? key,
    required this.mobile,
    this.tablet,
    required this.desktop,
  }) : super(key: key);

// This size work fine on my design, maybe you need some customization depends on your design

  // This isMobile, isTablet, isDesktop helep us later
  static bool isMobile(BuildContext context) =>
      MediaQuery.of(context).size.width < 850;

  static bool isTablet(BuildContext context) =>
      MediaQuery.of(context).size.width < 1100 &&
          MediaQuery.of(context).size.width >= 850;

  static bool isDesktop(BuildContext context) =>
      MediaQuery.of(context).size.width >= 1100;

  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    // If our width is more than 1100 then we consider it a desktop
    if (size.width >= 1100) {
      return desktop;
    }
    // If width it less then 1100 and more then 850 we consider it as tablet
    else if (size.width >= 850 && tablet != null) {
      return tablet!;
    }
    // Or less then that we called it mobile
    else {
      return mobile;
    }
  }
}
/// Usage


 CustomPaint(
                        painter: SegmentBorderPainter(
                          divisions: 3, // Number of divisions
                          gradient: const LinearGradient(
                            colors: [
                              Colors.orange,
                              Colors.orange,
                              Colors.red,
                              Colors.red,
                            ],
                          ),
                        ), 
                        child: Container(
                          height: 58.r,
                          width: 58.r,
                          child: SizedBox.shrink(),
                          ),
                        ),
                      ),


/// CODE

class SegmentBorderPainter extends CustomPainter {
  final int divisions;
  final double strokeWidth;
  final Gradient gradient;

  SegmentBorderPainter({
    required this.divisions,
    this.strokeWidth = 3.0,
    required this.gradient,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final Paint paint = Paint()
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke;

    final double radius = size.width / 2;
    final double angle = (2 * 3.141592653589793) / divisions;
    const double startAngle = -3.141592653589793 / 2;

    paint.shader = gradient.createShader(
      Rect.fromCircle(center: Offset(radius, radius), radius: radius),
    );

    if (divisions == 1) {
      canvas.drawCircle(Offset(radius, radius), radius, paint);
    } else if (divisions == 2) {
      for (int i = 0; i < divisions; i++) {
        canvas.drawArc(
          Rect.fromCircle(center: Offset(radius, radius), radius: radius),
          startAngle + i * angle + 0.08,
          angle * 0.95,
          false,
          paint,
        );
      }
    } else {
      for (int i = 0; i < divisions; i++) {
        canvas.drawArc(
          Rect.fromCircle(center: Offset(radius, radius), radius: radius),
          startAngle + i * angle + 0.05,
          angle * 0.95,
          false,
          paint,
        );
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
import 'package:flutter/material.dart';
import 'package:shalestin/Screens/home.dart';
  
  void main() => runApp(const MyApp());
  
  class MyApp extends StatelessWidget {
    const MyApp({super.key});
  
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
 routes: {
        'Home': (context) => const Home(),
      },
        initialRoute: 'Home',
        debugShowCheckedModeBanner: false,

      );
    }
  }
import 'dart:developer';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:easy_localization/easy_localization.dart';

import '../../features/auth/core/models/token_response_model.dart';
import 'api_exceptions.dart';

abstract class FirebaseAuthApiClient {

  Future<void> signIn(String phoneNumber, Function(String) codeSent);

  Future<TokenResponseModel> verifyOTP(String verificationId, String smsCode);
  Future<void> signUpWithOTP(String phoneNumber, Function(String) codeSent);
}

class FirebaseAuthApiClientImpl extends FirebaseAuthApiClient {
  final FirebaseAuth _auth;

  FirebaseAuthApiClientImpl(this._auth);

  @override
  Future<void> signIn(String phoneNumber, Function(String) codeSent) async {
    try {
      final phone = "+$phoneNumber";
      log('Signing in with phone number: $phone');
      await _auth.verifyPhoneNumber(
        phoneNumber: phone,
        verificationCompleted: (PhoneAuthCredential credential) async {
          await _auth.signInWithCredential(credential);
          print("Credential $credential");
        },
        verificationFailed: (FirebaseAuthException e) {
          print("Error $e");
          throw _handleError(e, tr('otpSignUpError'));
        },
        codeSent: (String verificationId, int? resendToken) {
          print("Code send code send ");
          codeSent(verificationId);
        },
        codeAutoRetrievalTimeout: (String verificationId) {},
      );
    } catch (e) {
      log('Sign in error: $e');
      throw _handleError(e, tr('otpSignInError'));
    }
  }

  @override
  Future<TokenResponseModel> verifyOTP(
      String verificationId, String smsCode) async {
    try {
      PhoneAuthCredential credential = PhoneAuthProvider.credential(
        verificationId: verificationId,
        smsCode: smsCode,
      );
      print("Credenrial $credential");
      print("verificationId $verificationId smsCode $smsCode ");
      final data = await _auth.signInWithCredential(credential);

      final token = await data.user!.getIdToken();


      if(token == null) {

      throw _handleError( ExceptionWithMessage(tr('tokenNotFound')), tr('tokenNotFound'));
      }
      print("Token $token");


      return TokenResponseModel.fromJson(data, token);
    } catch (e) {
      throw _handleError(e, tr('otpVerificationError'));
    }
  }

  @override
  Future<void> signUpWithOTP(
      String phoneNumber, Function(String) codeSent) async {
    try {
      final phone = "+$phoneNumber";
      print(phone);
      await _auth.verifyPhoneNumber(
        phoneNumber: phone,
        verificationCompleted: (PhoneAuthCredential credential) async {
          await _auth.signInWithCredential(credential);
          print("Credential $credential");
        },
        verificationFailed: (FirebaseAuthException e) {
          print("Error $e");
          throw _handleError(e, tr('otpSignUpError'));
        },
        codeSent: (String verificationId, int? resendToken) {
          codeSent(verificationId);
        },
        codeAutoRetrievalTimeout: (String verificationId) {},
      );
    } catch (e) {
      throw _handleError(e, tr('otpSignUpError'));
    }
  }

  Exception _handleError(dynamic error, String defaultMessage) {
    if (error is FirebaseAuthException) {
      switch (error.code) {
        case 'invalid-verification-code':
          return ExceptionWithMessage(tr('invalidVerificationCode'));
        case 'user-disabled':
          return UnauthorisedException();
        case 'too-many-requests':
          return ExceptionWithMessage(tr('tooManyRequests'));
        case 'operation-not-allowed':
          return ExceptionWithMessage(tr('operationNotAllowed'));
        default:
          return ExceptionWithMessage('$defaultMessage: ${error.message}');
      }
    }
    return ExceptionWithMessage(defaultMessage);
  }
}
import 'dart:io';

import 'package:firebase_storage/firebase_storage.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';

import 'api_exceptions.dart';

abstract class FirebaseStorageClient {
  Future<String> uploadFile(String path, String filePath);
  Future<void> downloadFile(String path, String downloadToPath);
  Future<void> deleteFile(String path);
  Future<String> getFileUrl(String path);
}

class FirebaseStorageClientImpl extends FirebaseStorageClient {
  final FirebaseStorage _storage;

  FirebaseStorageClientImpl(this._storage);

  @override
  Future<String> uploadFile(String path, String filePath) async {
    try {
      final ref = _storage.ref().child(path);
      final uploadTask = ref.putFile(File(filePath));
      await uploadTask.whenComplete(() {});
      return await ref.getDownloadURL();
    } catch (e) {
      throw _handleError(e, tr('errorUploadingFile'));
    }
  }

  @override
  Future<void> downloadFile(String path, String downloadToPath) async {
    try {
      final ref = _storage.ref().child(path);
      final file = File(downloadToPath);
      await ref.writeToFile(file);
    } catch (e) {
      throw _handleError(e, tr('errorDownloadingFile'));
    }
  }

  @override
  Future<void> deleteFile(String path) async {
    try {
      final ref = _storage.ref().child(path);
      await ref.delete();
    } catch (e) {
      throw _handleError(e, tr('errorDeletingFile'));
    }
  }

  @override
  Future<String> getFileUrl(String path) async {
    try {
      final ref = _storage.ref().child(path);
      return await ref.getDownloadURL();
    } catch (e) {
      throw _handleError(e, tr('errorGettingFileUrl'));
    }
  }

  Exception _handleError(dynamic error, String defaultMessage) {
    if (error is FirebaseException) {
      switch (error.code) {
        case 'permission-denied':
          return UnauthorisedException();
        case 'not-found':
          return Exception(defaultMessage);
        default:
          return ExceptionWithMessage('$defaultMessage: ${error.message}');
      }
    }
    return Exception(defaultMessage);
  }
}
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';

import 'api_exceptions.dart';

enum FirebaseApiFilterType {
  isEqualTo,
  isNotEqualTo,
  isGreaterThan,
  isGreaterThanOrEqualTo,
  isLessThan,
  isLessThanOrEqualTo,
  arrayContains,
  arrayContainsAny,
  whereIn,
  whereNotIn,
  isNull,
}

class FirebaseFilterEntity {
  final String field;
  final FirebaseApiFilterType operator;
  final dynamic value;

  FirebaseFilterEntity({
    required this.field,
    required this.operator,
    required this.value,
  });
}

abstract class FirebaseApiClient {
  Future<dynamic> get(String collection,{int limit = 20 ,List<FirebaseFilterEntity>? filters});
  Future<dynamic> getById(String collection, String id);
  Future<dynamic> postWithId(String collection, {required Map<String, dynamic> params});
  Future<void> post(String collection, {required String id, required Map<String, dynamic> params});
  Future<void> putWithId(String collection, {required String id, required Map<String, dynamic> params});
  Future<void> put(String collection, {required Map<String, dynamic> params});
  Future<void> deleteDoc(String collection, String id);
}

class FirebaseApiClientImpl extends FirebaseApiClient {
  final FirebaseFirestore _client;

  FirebaseApiClientImpl(this._client);

  @override
  Future<dynamic> get(String collection,{int limit = 20 ,List<FirebaseFilterEntity>? filters}) async {
    try {
      Query query = _client.collection(collection);

      if (filters != null) {
        for (var filter in filters) {
          switch (filter.operator) {
            case FirebaseApiFilterType.isEqualTo:
              query = query.where(filter.field, isEqualTo: filter.value);
              break;
            case FirebaseApiFilterType.isNotEqualTo:
              query = query.where(filter.field, isNotEqualTo: filter.value);
              break;
            case FirebaseApiFilterType.isGreaterThan:
              query = query.where(filter.field, isGreaterThan: filter.value);
              break;
            case FirebaseApiFilterType.isGreaterThanOrEqualTo:
              query = query.where(filter.field, isGreaterThanOrEqualTo: filter.value);
              break;
            case FirebaseApiFilterType.isLessThan:
              query = query.where(filter.field, isLessThan: filter.value);
              break;
            case FirebaseApiFilterType.isLessThanOrEqualTo:
              query = query.where(filter.field, isLessThanOrEqualTo: filter.value);
              break;
            case FirebaseApiFilterType.arrayContains:
              query = query.where(filter.field, arrayContains: filter.value);
              break;
            case FirebaseApiFilterType.arrayContainsAny:
              query = query.where(filter.field, arrayContainsAny: filter.value);
              break;
            case FirebaseApiFilterType.whereIn:
              query = query.where(filter.field, whereIn: filter.value);
              break;
            case FirebaseApiFilterType.whereNotIn:
              query = query.where(filter.field, whereNotIn: filter.value);
              break;
            case FirebaseApiFilterType.isNull:
              query = query.where(filter.field, isNull: filter.value);
              break;
            default:
              throw ArgumentError('Unsupported operator: ${filter.operator}');
          }
        }
      }

      final response = await query.limit(limit).get();
      return response.docs.map((doc) => doc.data()).toList();
    } catch (e) {
      throw _handleError(e, tr('errorGettingDataCollection'));
    }
  }

  @override
  Future<dynamic> getById(String collection, String id) async {
    try {
      final response = await _client.collection(collection).doc(id).get();
      if (!response.exists) {
        throw Exception('Document with ID $id not found in collection $collection');
      }
      return response.data();
    } catch (e) {
      throw _handleError(e, tr('errorGettingDocumentById'));
    }
  }

  @override
  Future<void> put(String collection, {required Map<String, dynamic> params}) async {
    if (!params.containsKey('id')) {
      throw ArgumentError(tr('documentIdIsRequiredToUpdate'));
    }
    try {
      await _client.collection(collection).doc(params['id']).update(params);
    } catch (e) {
      throw _handleError(e, tr('errorUpdatingDocument'));
    }
  }

  @override
  Future<void> deleteDoc(String collection, String id) async {
    try {
      await _client.collection(collection).doc(id).delete();
    } catch (e) {
      throw _handleError(e, tr('errorDeletingDocument'));
    }
  }

  Exception _handleError(dynamic error, String defaultMessage) {
    if (error is FirebaseException) {
      switch (error.code) {
        case 'permission-denied':
          return UnauthorisedException();
        case 'not-found':
          return Exception(defaultMessage);
        default:
          return ExceptionWithMessage('$defaultMessage: ${error.message}');
      }
    }
    return Exception(defaultMessage);
  }

  @override
  Future<void> post(String collection, {required String id, required Map<String, dynamic> params}) async {
    try {
      await _client.collection(collection).doc(id).set(params);
    } catch (e) {
      throw _handleError(e, tr('errorPostingDataCollection'));
    }
  }


  @override
  Future<dynamic> postWithId(String collection, {required Map<String, dynamic> params}) async {
    try {
      debugPrint("Post data $collection\n$params");
      await _client.collection(collection).doc(params['id']).set(params);
      return params;
    } catch (e) {
      throw _handleError(e, tr('errorPostingDataCollection'));
    }
  }


  @override
  Future<void> putWithId(String collection, {required String id, required Map<String, dynamic> params}) async {
    try {
      await _client.collection(collection).doc(id).update(params);
    } catch (e) {
      throw _handleError(e, tr('errorUpdatingDocument'));
    }
  }
}
import 'dart:convert';
import 'package:http/http.dart' as http;

class ApiService<T> {
  final String _baseUrl;

  ApiService(this._baseUrl);

  Future<List<T>> getAll(T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.get(Uri.parse(_baseUrl));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body) as List;
      return jsonData.map((data) => fromJson(data)).toList();
    } else {
      throw Exception('Failed to load data');
    }
  }

  Future<List<T>> search(String query, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.get(Uri.parse('$_baseUrl?search=$query'));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body) as List;
      return jsonData.map((data) => fromJson(data)).toList();
    } else {
      throw Exception('Failed to search data');
    }
  }

  Future<T> create(Map<String, dynamic> data, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.post(
      Uri.parse(_baseUrl),
      headers: {'Content-Type': 'application/json'},
      body: json.encode(data),
    );
    if (response.statusCode == 201) {
      return fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to create data');
    }
  }

  Future<T> update(int id, Map<String, dynamic> data, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.put(
      Uri.parse('$_baseUrl/$id'),
      headers: {'Content-Type': 'application/json'},
      body: json.encode(data),
    );
    if (response.statusCode == 200) {
      return fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to update data');
    }
  }

  Future<void> delete(int id) async {
    final response = await http.delete(Uri.parse('$_baseUrl/$id'));
    if (response.statusCode != 204) {
      throw Exception('Failed to delete data');
    }
  }
}
//=============================================
class Note {
  final int id;
  final String title;
  final String content;

  Note({required this.id, required this.title, required this.content});

  factory Note.fromJson(Map<String, dynamic> json) {
    return Note(
      id: json['id'],
      title: json['title'],
      content: json['content'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'content': content,
    };
  }
}

final notesService = ApiService<Note>('http://10.0.2.2:8000/api/notes');

// Get all notes
final notes = await notesService.getAll(Note.fromJson);

// Search for notes
final searchResults = await notesService.search('keyword', Note.fromJson);

// Create a new note
final newNote = await notesService.create(
  {
    'title': 'New Note',
    'content': 'This is a new note',
  },
  Note.fromJson,
);

// Update a note
final updatedNote = await notesService.update(
  newNote.id,
  {
    'title': 'Updated Note',
    'content': 'This is an updated note',
  },
  Note.fromJson,
);

// Delete a note
await notesService.delete(updatedNote.id);
https://i.diawi.com/vfhSW1  
void main()
{
  
  //odd r even
	var a= 4;
  if(a%2==0){
    print("even");
  }else{
    print("odd");
  }
  
  if(a>0){
    print("+ve");
  }else{
    print("-ve");
  }
    
  
  //sum of n natural num
  s(n){
    return (n*(n+1))/2;
  }
  s(a);
  print(s(a));
  
}
https://webapp.diawi.com/install/U1m5Zb
class fontstyle {
  static FontWeight? Fontweights({FWT fontWeight = FWT.regular}) {
    switch (FWT) {
      case FWT.bold:
        return FontWeight.w700;
      case FWT.semiBold:
        return FontWeight.w600;
      case FWT.medium:
        return FontWeight.w500;
      case FWT.regular:
        return FontWeight.w400;
      case FWT.light:
        return FontWeight.w300;
      default:
        return FontWeight.w400;
    }
  }

  static TextStyle f14(
      {required Color colors, FWT? fontweight, double height = 0.0}) {
    return TextStyle(
        fontSize: 14.sp,
        fontFamily: "Poppins",
        fontWeight: Fontweights(fontWeight: fontweight!),
        color: Colors.amberAccent);
  }

  static TextStyle f12(
      {required Color colors, FWT? fontweight, double height = 0.0}) {
    return TextStyle(
        fontSize: 12.sp,
        fontFamily: "Poppins",
        fontWeight: Fontweights(fontWeight: fontweight!),
        color: Colors.amberAccent);
  }
}
class Splashbinding extends Bindings {
  @override
  void dependencies() {
    Get.put<SplashController>(SplashController());
    Get.lazyPut(() => SignupController());
  }
}
      
////////////////////////

final SharedPreferences pref =
                                        await SharedPreferences.getInstance();
                                    pref.setString("email",
                                        model.Login_Emailcontroller.value.text);

////////////
class SplashController extends GetxController
    with GetSingleTickerProviderStateMixin {
  @override
  void onInit() {
    super.onInit();
    Future.delayed(
      const Duration(seconds: 2),
      () async {
        final SharedPreferences pref = await SharedPreferences.getInstance();
        final u = pref.get("email");
        u != null ? Get.toNamed("/HomeScreen") : Get.toNamed("loginScreen");
      },
    );
  }
}

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Errorpage extends StatefulWidget {
  const Errorpage({super.key});

  @override
  State<Errorpage> createState() => _ErrorpageState();
}

class _ErrorpageState extends State<Errorpage> {
  @override
  void initState() {
    super.initState();
    getval2();
    Data1;
  }

  bool? Data1;
  Future<void> getval2() async {
    try {
      final res = await http.get(Uri.parse("https://reqres.in/api/users/23"));

      if (res.statusCode == 404) {
        setState(() {
          Data1 = false;
        });
        print(Data1);
      }
    } catch (e) {
      print('Error fetching data: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Container(
          child: Data1 == false
              ? const Text("404 : PAGE NOT FOUND")
              : const Text("PAGE FOUND")),
    ));
  }
}
class Get1 {
  Data data;
  Support support;

  Get1({required this.data, required this.support});

  factory Get1.fromJson(Map<String, dynamic> json) => Get1(
        data: Data.fromJson(json["data"]),
        support: Support.fromJson(json["support"]),
      );

  Map<String, dynamic> toJson() => {
        "data": data.toJson(),
        "support": support.toJson(),
      };
}

class Data {
  int id;
  String email;
  String firstName;
  String lastName;
  String avatar;

  Data({
    required this.id,
    required this.email,
    required this.firstName,
    required this.lastName,
    required this.avatar,
  });

  factory Data.fromJson(Map<String, dynamic> json) => Data(
        id: json["id"],
        email: json["email"],
        firstName: json["first_name"],
        lastName: json["last_name"],
        avatar: json["avatar"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "email": email,
        "first_name": firstName,
        "last_name": lastName,
        "avatar": avatar,
      };
}

class Support {
  String url;
  String text;

  Support({
    required this.url,
    required this.text,
  });

  factory Support.fromJson(Map<String, dynamic> json) => Support(
        url: json["url"],
        text: json["text"],
      );

  Map<String, dynamic> toJson() => {
        "url": url,
        "text": text,
      };
}

/////////////////////
  
  
  
  
  
   List<Get1> Data = [];
  List<Get1> Support = [];

  @override
  void initState() {
    super.initState();
    getval();
  }

  Future<void> getval() async {
    try {
      final res = await http.get(Uri.parse("https://reqres.in/api/users/2"));
      Get1 val = Get1.fromJson(json.decode(res.body));
      setState(() {
        Data.add(val);
      });
      if (res.statusCode == 200) {
        print(Data);
      }
    } catch (e) {
      print('Error fetching data: $e');
    }
  }
  
  
  
  /////////////////////////////
  Text(
                                  "Mail : ${Data[0].data.email}",
                                  style: const TextStyle(
                                      fontSize: 20,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold),
                                ),
 Expanded(
                  child: WebView(
                    initialUrl: Data[0].support.url,
                    // "https://reqres.in/#support-heading",
                    onWebViewCreated: (WebViewController webViewController) {
                      _controller.complete(webViewController);
                    },
                    javascriptMode: JavascriptMode.unrestricted,
                    onWebResourceError: (WebResourceError error) {
                      print('----------------------: $error-----------------');
                    },
                  ),
                ),  
  
  
Step 1 : Download Link : https://docs.flutter.dev/get-started/install/macos/mobile-ios?tab=download
Step 2 : Paste UnZip file in Users/Apple/Development folder.
Step 3 : add this path to .zshenv file 
export PATH=/Users/apple/development/flutter/bin:$PATH
Step 4 : Run terminal Command flutter doctor
import 'dart:io';

import 'package:dartz/dartz.dart';

import '../api/api_exceptions.dart';
import '../entities/app_error.dart';

Future<Either<AppError, T>> action<T>({required Future<T> task}) async {
  try {
    final response = await task;

    return Right(response);
  } on SocketException {
    return const Left(AppError(appErrorType: AppErrorType.network));
  } on UnauthorisedException {
    return const Left(AppError(appErrorType: AppErrorType.unauthorised));
  } on ExceptionWithMessage catch (e) {
    return Left(
        AppError(appErrorType: AppErrorType.msgError, errorMessage: e.message));
  } on Exception {
    return const Left(AppError(appErrorType: AppErrorType.api));
  }
}
class Num{
  int _x;
  
  Num(this._x);
  
  int get x => _x;
}

void main(){
 	Num num1 = Num(5);
  print(num1.x);
}
class Employee{
  String empName;
  DateTime joiningDate;
  
  Employee(this.empName, this.joiningDate);
  
  int get daysOfWork{
    return DateTime.now().difference(joiningDate).inDays;
  }
}

void main(){
  Employee m = Employee("Manish", DateTime(2023,07,12));
  print(m.daysOfWork);
}
class Employee{
  String _empName;
  double _empSalary;
  
  Employee(this._empName, this._empSalary);
  
  String get empName => _empName;
  
  set empName(String empName) {
    if(empName.length >= 3 && empName.length <= 25){
      _empName = empName;
    } else {
      print("EmpName should be of appropriate length");
    }
  } 
  
  
  double get empSalary => _empSalary;
}

void main(){
  Employee manish = Employee("Manish Basnet" , 20000);
  manish.empName = "MB";
  print(manish.empName);
  print(manish.empSalary);
}
class Employee{
  String empName;
  double empSalary;
  
  Employee(this.empName, this.empSalary);
}

void main(){
  Employee manish = Employee("Manish Basnet" , 20000);
  print(manish.empName);
  print(manish.empSalary);
}
import 'package:flutter/material.dart';

#set( $CamelCaseName = "" )
#set( $part = "" )
#foreach($part in $NAME.split("_"))
    #set( $CamelCaseName = "${CamelCaseName}$part.substring(0,1).toUpperCase()$part.substring(1).toLowerCase()" )
#end
#parse("File Header.java")
class ${CamelCaseName} extends StatelessWidget {
  const ${CamelCaseName}({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
     return Container();
  }
}
import 'package:flutter/material.dart';

#set( $CamelCaseName = "" )
#set( $part = "" )
#foreach($part in $NAME.split("_"))
    #set( $CamelCaseName = "${CamelCaseName}$part.substring(0,1).toUpperCase()$part.substring(1).toLowerCase()" )
#end
#parse("File Header.java")
class ${CamelCaseName} extends StatelessWidget {
  static route() =>
      MaterialPageRoute(builder: (context) => ${CamelCaseName}());
  const ${CamelCaseName}({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
     return Scaffold(
      body:  
       Column(
          children: [],
        ),
     
    );
  }
}
import 'package:flutter/material.dart';

class Application extends StatelessWidget {
  const Application({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: YourScreen(),
    );
  }
}
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
import 'package:path_provider/path_provider.dart';

import '../../features/auth/core/datasources/auth_local_data_source.dart';
import 'api_constants.dart';
import 'api_exceptions.dart';

abstract class ApiClient {
  Future<dynamic> get(String path,
      {bool withParse = true,
      Map<String, dynamic>? params,
      Map<dynamic, dynamic>? filter});
  Future<dynamic> post(String path,
      {required Map<String, dynamic> params, bool withToken = false});
  Future<dynamic> patch(String path, {required Map<String, dynamic> params});
  Future<dynamic> put(String path, {required Map<String, dynamic> params});
  Future<dynamic> download({required String fileUrl});
  Future<dynamic> deleteWithBody(String path,
      {Map<String, dynamic>? params, bool withParse = false});
}

class ApiClientImpl extends ApiClient {
  final AuthLocalDataSource _authenticationLocalDataSource;
  final Dio clientDio;

  ApiClientImpl(this.clientDio, this._authenticationLocalDataSource);

  @override
  Future<dynamic> download({required String fileUrl}) async {
    String sessionId = await _authenticationLocalDataSource.getToken() ?? "";
    clientDio.interceptors
        .removeWhere((interceptor) => interceptor is DioCacheInterceptor);
    final header = {'Authorization': "Bearer $sessionId"};
    final Directory dir = await getApplicationDocumentsDirectory();

    try {
      await clientDio.download(fileUrl, dir.path,
          options: Options(headers: header));
    } catch (e) {
      throw Exception("Error downloading file: $e");
    }
  }

  @override
  Future<dynamic> get(String path,
      {bool withParse = true,
      Map<dynamic, dynamic>? filter,
      Map<String, dynamic>? params}) async {
    String sessionId = await _authenticationLocalDataSource.getToken() ?? "";
    final Map<String, dynamic> header =
        sessionId.isNotEmpty ? {'Authorization': "Bearer $sessionId"} : {};
    final pth = _buildUrl(path, params);

    final response = await _tryCatch(() => clientDio.get(pth,
        options: Options(contentType: "application/json", headers: header)));
    return _errorHandler(response, withParse: withParse);
  }

  @override
  Future<dynamic> patch(String path,
      {required Map<dynamic, dynamic> params}) async {
    String sessionId = await _authenticationLocalDataSource.getToken() ?? "";
    final header = {
      'Accept': 'application/json',
      if (sessionId.isNotEmpty) 'Authorization': "Bearer $sessionId"
    };

    final response = await _tryCatch(() => clientDio.patch(_buildUrl(path),
        data: jsonEncode(params), options: Options(headers: header)));
    return _errorHandler(response);
  }

  @override
  Future put(String path, {required Map<String, dynamic> params}) async {
    String sessionId = await _authenticationLocalDataSource.getToken() ?? "";
    final header = {
      'Accept': 'application/json',
      if (sessionId.isNotEmpty) 'Authorization': "Bearer $sessionId"
    };

    final response = await _tryCatch(() => clientDio.put(_buildUrl(path),
        data: jsonEncode(params), options: Options(headers: header)));
    return _errorHandler(response);
  }

  @override
  Future<dynamic> deleteWithBody(String path,
      {Map<String, dynamic>? params, bool withParse = true}) async {
    String sessionId = await _authenticationLocalDataSource.getToken() ?? "";
    final header = {'Authorization': "Bearer $sessionId"};

    final response = await _tryCatch(() => clientDio.delete(_buildUrl(path),
        data: jsonEncode(params), options: Options(headers: header)));
    return _errorHandler(response, withParse: withParse);
  }

  @override
  Future<dynamic> post(String path,
      {required Map<String, dynamic> params, bool withToken = false}) async {
    String sessionId = await _authenticationLocalDataSource.getToken() ?? "";
    final header = {
      "Content-type": "application/json",
      "Accept": "*/*",
      if (sessionId.isNotEmpty) 'Authorization': "Bearer $sessionId"
    };

    final response = await _tryCatch(() => clientDio.post(_buildUrl(path),
        data: jsonEncode(params), options: Options(headers: header)));
    return _errorHandler(response);
  }

  Future<Response> _tryCatch(Future<Response> Function() function) async {
    try {
      try {
        final Response response = await function();

        return response;
      } on DioException catch (error) {
        print("ERROR CATCH $error");

        throw   ExceptionWithMessage('Unknown error occurred ${error.toString()}');
      }
    } on DioException catch (e) {
      final response = e.response;
      if (response == null) {
        throw const ExceptionWithMessage('Unknown error occurred');
      }

      _handleError(response);
      throw const ExceptionWithMessage('Unhandled error occurred');
    } catch (error) {
      throw const ExceptionWithMessage('Unknown error occurred');
    }
  }

  void _handleError(Response response) {
    String msg = "unknown_error";
    if (response.statusCode != null) {
      if (response.statusCode! >= 500) {
        throw const ExceptionWithMessage("Server is down (500)");
      }

      var responseData =
          response.data is String ? jsonDecode(response.data) : response.data;

      if (responseData is Map<String, dynamic>) {
        msg = responseData["error"] ?? responseData["message"] ?? msg;
        if (responseData["message"] is List &&
            responseData["message"].isNotEmpty) {
          msg = responseData["message"][0];
        }
      }
    }

    print("response.statusCode ${response.statusCode}");

    switch (response.statusCode) {
      case 400:
      case 403:
      case 405:
      case 409:
        throw ExceptionWithMessage(msg);
      case 401:
        throw UnauthorisedException();

      default:
        throw Exception(response.statusMessage);
    }
  }

  dynamic _errorHandler(Response response, {bool withParse = true}) {
    if (response.statusCode == 200 ||
        response.statusCode == 201 ||
        response.statusCode == 204) {
      return withParse
          ? Map<String, dynamic>.from(response.data)
          : response.data;
    }
    _handleError(response);
  }

  String _buildUrl(String path, [Map<dynamic, dynamic>? params]) {
    if (params == null || params.isEmpty) {
      return '${ApiConstants.baseApiUrl}$path';
    }
    final paramsString =
        params.entries.map((e) => '${e.key}=${e.value}').join('&');
    return '${ApiConstants.baseApiUrl}$path?$paramsString';
  }
}
class UnauthorisedException implements Exception {}

class ExceptionWithMessage implements Exception {
  final String message;
  const ExceptionWithMessage(this.message);
}
import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';



part 'network_state.dart';

class NetworkCubit extends Cubit<NetworkState> {
  final NetworkInfo networkService;

  NetworkCubit({required this.networkService}) : super(NetworkInitial()) {
    listenConnection();
  }

  static bool _isOnline = false;

  bool get isOnline => _isOnline;

  listenConnection() async {
    networkService.connectionStream.listen((status) {

      if(status == InternetConnectionStatus.connected) {
        _isOnline = true;
        emit(NetworkConnectedState());
      }else {
        _isOnline = false;
        emit(NetworkLostState());
      }
    });
  }
}
import 'package:equatable/equatable.dart';

class NoParams extends Equatable {
  @override
  List<Object> get props => [];
}
import 'package:equatable/equatable.dart';

class AppError extends Equatable {
  final AppErrorType appErrorType;
  final String errorMessage;
  const AppError( {required this.appErrorType, this.errorMessage = ''});

  @override
  List<Object> get props => [appErrorType];
}

enum AppErrorType {
  api,
  network,
  database,
  unauthorised,
  sessionDenied,
  msgError,
  emailValidation
}
import 'package:dartz/dartz.dart';

import '../entities/app_error.dart';

abstract class UseCase<Type, Params> {
  Future<Either<AppError, Type>> call(Params params);
}
import 'package:internet_connection_checker/internet_connection_checker.dart';

abstract class NetworkInfo {
  Stream<InternetConnectionStatus>  get connectionStream;
}

class NetworkInfoImpl implements NetworkInfo {
  late InternetConnectionChecker connectionChecker =
      InternetConnectionChecker();

  @override
  Stream<InternetConnectionStatus> get connectionStream => connectionChecker.onStatusChange;
}
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyScrollableScreen(),
    );
  }
}

class MyScrollableScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Scrollable Screen'),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Column(
            children: List.generate(
              18, // Number of main views
              (rowIndex) => Container(
                height: 80, // Set the height of each row
                margin: EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.black, width: 1.0),
                ),
                child: Row(
                  children: List.generate(
                    20, // Number of labels
                    (columnIndex) => Container(
                      width: 80, // Set the width of each label
                      child: Center(
                        child: Text('Label $columnIndex'),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hive Tutorial',
      home: FutureBuilder(
        future: Hive.openBox('contacts'),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError)
              return Text(snapshot.error.toString());
            else
              return ContactPage();
          }
          // Although opening a Box takes a very short time,
          // we still need to return something before the Future completes.
          else
            return Scaffold();
        },
      ),
    );
  }

  @override
  void dispose() {
    Hive.close();
    super.dispose();
  }
}
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Container(
      color: const Color.fromARGB(255, 96, 106, 114),
      child: Center(
        child: Column(
          children: [
          const  Text(
              'Brand',
              style: TextStyle(
                color: Colors.white,
                fontSize: 100,
                fontWeight: FontWeight.bold,
                fontStyle: FontStyle.italic,
                letterSpacing: 2.0,
              decoration: TextDecoration.none
              ),
            ),
         const   Text(
              'builder',
              style: TextStyle(
                color: Colors.white,
                fontSize: 60,
                fontWeight: FontWeight.bold,
                fontStyle: FontStyle.italic,
                letterSpacing: 2.0,
           decoration: TextDecoration.none
              ),
            ),
         const   Text(
              'an IT company',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.bold,
                fontStyle: FontStyle.italic,
                letterSpacing: 2.0,
                decoration: TextDecoration.none
              ),
            ),
          const  SizedBox(height: 30),
           const  Text(
              'Our services',
              style: TextStyle(
                color: Colors.white,
                fontSize: 20,
                decoration: TextDecoration.none,
              ),
            ),
         const   SizedBox(height: 20),
            Wrap(
              alignment: WrapAlignment.start,
              spacing: 20, // Adjust spacing between service items
              runSpacing: 20, // Adjust run spacing
              children: [
              
                ServiceItem(
                  icon: Icons.palette,
                  text: 'Branding',
                ),
                ServiceItem(
                  icon: Icons.design_services,
                  text: 'UX/UI Design',
                ),
                ServiceItem(
                  icon: Icons.mobile_screen_share,
                  text: 'Mobile App Development',
                ),
                ServiceItem(
                  icon: Icons.storage,
                  text: 'Server Management',
                ),
                  ServiceItem(
                  icon: Icons.shop,
                  text: 'Digital Marketing',
                ),
                // Add more services here
              ],
            ),
          ],
        ),
      ),
    ),
  ));
}

class ServiceItem extends StatelessWidget {
  final IconData icon;
  final String text;

  ServiceItem({required this.icon, required this.text});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 160.0, // Adjust the width of each service box
      height: 160.0, // Adjust the height of each service box
      decoration: BoxDecoration(
        border: Border.all(
          color: Colors.white,
          width: 2.0,
        ),
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            icon,
            color: Colors.white,
            size: 40,
          ),
          const SizedBox(height: 5),
          Text(
            text,
            textAlign: TextAlign.center,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 14,
              decoration: TextDecoration.none,
              fontWeight: FontWeight.bold,
              letterSpacing: 1.0,
              shadows: [
                Shadow(
                  color: Colors.black,
                  blurRadius: 3.0,
                  offset: Offset(2, 2),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
class MyHomePage extends StatefulWidget{
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => MyHomePageState();
  }

  class MyHomePageState extends State<MyHomePage>{
    String _name = "Sumi";
    Widget build(BuildContext context){
      return Scaffold(
        body: Center(child: ElevatedButton(
          child: Text(_name),
          onPressed: (){
            setState(() {
              
            });
            _name = _name == "Sumi"?"Roma":"Sumi";
          },
        ),
      ),
     );
    }
  }
import 'package:flutter/material.dart';

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int count = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("$count"),
      ),
      floatingActionButton: FloatingActionButton(onPressed: (){
        setState(() {
          count++;
        });
      },
      child: const Icon(Icons.add),),
    );
  }
}
import 'package:flutter/material.dart';

class StatelessPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Stateless Widget'),
          backgroundColor: Colors.white,
        ),
        backgroundColor: Colors.red,
        body: Placeholder(),
      ),
    );
  }
}
++++++++++++++++getFcm.dart+++++++++++++
  
  Future<String?> getFcmToken() async {
  if(Platform.isIOS){
    String? fcmKey = await FirebaseMessaging.instance.getToken();
    return fcmKey;
  }

  String? fcmKey = await FirebaseMessaging.instance.getToken();
  return fcmKey;
  }

++++++++++++++++++++++++++++++++++++++++

final CollectionReference _tokensCollection =
      FirebaseFirestore.instance.collection('users');

Future<void> saveFCMTokenToFirestore() async {
  // Get the FCM token
  String? fcmToken = await getFcmToken();
  if (fcmToken != null) {
    // Create a document with the FCM token in Firestore
    await _tokensCollection.doc(globals.email).set({
      'token': fcmToken,
      'tokenCreatedAt': FieldValue.serverTimestamp(),
    });
  } else {
    print('Failed to retrieve FCM token');
  }
}
Cryptocurrency development is the process of creating a digital currency that is secured by cryptography and operates independently of a central authority. It involves designing and building a blockchain-based platform that allows for secure, transparent, and decentralized transactions. The cryptocurrency market is rapidly growing, and businesses are increasingly looking to integrate blockchain technology into their operations. A reputable cryptocurrency development company like Shamla Tech can provide valuable expertise and guidance to ensure a successful implementation. Shamla Tech specializes in providing comprehensive blockchain solutions to clients, including the creation of new cryptocurrencies, blockchain-based software applications, and custom smart contract development. 

Know more: https://shamlatech.com/cryptocurrency-development/
import 'package:flutter/material.dart';

class AppContext {
  static BuildContext? _context;

  static void set(BuildContext context) {
    _context = context;
  }

  static BuildContext get() {
    return _context!;
  }
}
import 'package:cryptocornars/common/utils/app_context.dart';
import 'package:cryptocornars/constants/global_variable.dart';
import 'package:flutter/material.dart';

class Toast {
  static void show(String msg, BuildContext context, double height) {
    Color textColor = Colors.white;
    Color backgroundColor = Colors.blueAccent;
    dismiss();
    Toast._createView(msg, context, backgroundColor, textColor, height);
  }

  static OverlayEntry? _overlayEntry;
  static bool isVisible = false;


  static void _createView(String msg, BuildContext context, Color background,

      Color textColor, double height) async {
    var overlayState = Overlay.of(context);
    AppContext.get();
    final themeData = Theme.of(context);

    _overlayEntry = OverlayEntry(
      builder: (BuildContext context) => _ToastAnimatedWidget(
        height: height,
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          child: Container(
            alignment: Alignment.center,
            width: MediaQuery.of(context).size.width,
            child: Container(
              decoration: BoxDecoration(
                color: GlobalVariable.whiteSmoke,
                borderRadius: BorderRadius.circular(10),
              ),
              margin: const EdgeInsets.symmetric(horizontal: 20),
              padding: const EdgeInsets.fromLTRB(16, 10, 16, 10),
              child: Text(
                msg,
                style: themeData.textTheme.bodyLarge?.copyWith(
                  color: GlobalVariable.platinum,
                  fontFamily: 'Roboto',
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        ),
      ),
    );
    isVisible = true;
    overlayState.insert(_overlayEntry!);
  }

  static dismiss() async {
    if (!isVisible) {
      return;
    }
    isVisible = false;
    _overlayEntry?.remove();
  }
}

class _ToastAnimatedWidget extends StatefulWidget {
  const _ToastAnimatedWidget({
    Key? key,
    required this.child,
    required this.height,
  }) : super(key: key);
  final double height;
  final Widget child;

  @override
  _ToastWidgetState createState() => _ToastWidgetState();
}

class _ToastWidgetState extends State<_ToastAnimatedWidget>
    with SingleTickerProviderStateMixin {
  bool get _isVisible => true; //update this value later

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
        bottom: widget.height,
        child: AnimatedOpacity(
          duration: const Duration(seconds: 2),
          opacity: _isVisible ? 1.0 : 0.0,
          child: widget.child,
        ));
  }
}
class _MyNavigationBarState extends State<MyNavigationBar > {
  int _currentTabIndex = 0;

  @override
  Widget build(BuildContext context) {
    final _kTabPages = <Widget>[
      Page1(),
      Page2(),
      Page3(),
      Container(),
    ];
    final _kBottmonNavBarItems = <BottomNavigationBarItem>[
      const BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
      const BottomNavigationBarItem(icon: Icon(Icons.network_cell), label: 'Prices'),
      const BottomNavigationBarItem(icon: Icon(Icons.add_circle), label: 'Trade'),
      const BottomNavigationBarItem(icon: Icon(Icons.account_balance_wallet), label: 'Wallet'),
    ];
    assert(_kTabPages.length == _kBottmonNavBarItems.length);
    final bottomNavBar = BottomNavigationBar(
      items: _kBottmonNavBarItems,
      currentIndex: _currentTabIndex,
      type: BottomNavigationBarType.fixed,
      onTap: (int index) {
        if(index == 3){
          showBottomSheet();
          return;
        }

        setState(() {
          _currentTabIndex = index;
        });
      },
    );
    return Scaffold(
      body: _kTabPages[_currentTabIndex],
      bottomNavigationBar: bottomNavBar,
      ),
    );
  }
}

showBottomSheet(){
      Container _buildBottomSheet(BuildContext context) {
    return Container(
      height: 300,
      padding: const EdgeInsets.all(8.0),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.blue, width: 2.0),
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: ListView(
        children: <Widget>[
          const ListTile(title: Text('Bottom sheet')),
          const TextField(
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              icon: Icon(Icons.attach_money),
              labelText: 'Enter an integer',
            ),
          ),
          Container(
            alignment: Alignment.center,
            child: ElevatedButton.icon(
              icon: const Icon(Icons.save),
              label: const Text('Save and close'),
              onPressed: () => Navigator.pop(context),
            ),
          )
        ],
      ),
    );
  }
}
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  final TextEditingController controller = TextEditingController();
  final _form = GlobalKey<FormState>();

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  bool isValid = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        margin: const EdgeInsets.all(10),
        child: Column(
          children: [
            Form(
              key: _form,
              child: FormField(
                validator: (val) =>
                    val == null || val == '' ? 'Type Something!' : null,
                builder: (formfielstate) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                     mainAxisSize: MainAxisSize.min,
                    children: [
                      TextField(
                        controller: controller,
                        decoration: const InputDecoration(labelText: 'Enter'),
                      ),
                      if (formfielstate.hasError)
                        Padding(
                          padding: const EdgeInsets.only(top: 10),
                          child: Text(
                            formfielstate.errorText!,
                            style: const TextStyle(color: Colors.red),
                          ),
                        ),

                    ],
                  );
                },
              ),
            ),
            Align(
              alignment: Alignment.center,
              child: ElevatedButton(
                onPressed: () {
                  if (_form.currentState!.validate()) {}
                },
                child: const Text('Click'),
              ),
            )
          ],
        ),
      ),
    );
  }
}
// TextFormField(
//                 controller: controller,
//                 decoration: const InputDecoration(
//                   errorStyle: TextStyle(
//                     textBaseline: TextBaseline.alphabetic
//                   ),
//                     hintText: 'Enter',
//                     border: OutlineInputBorder(
//                         borderSide: BorderSide(
//                       color: Colors.black38,
//                     )),
//                     enabledBorder: OutlineInputBorder(
//                         borderSide: BorderSide(
//                       color: Colors.black38,
//                     ))),
//                 validator: (val) {
//                   if (val == null || val.isEmpty) {
//                     return 'Enter your Enter';
//                   }
//
//                   return null;
//                 },
//               ),
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:healum/utils/trackers.dart';
import 'package:intl/intl.dart';

class DataBase {
  final database = FirebaseFirestore.instance;

  isUserAdded(String uid) async {
    return (await database.collection("users").doc(uid).get()).exists;
  }

  addUser(String uid) async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    await database
        .collection('users')
        .doc(uid)
        .set((await deviceInfo.androidInfo).toMap());
  }

  pushTrackerData(
      Tracker tracker, String uid, Map<String, dynamic> trackerData) async {
    DateTime dateTime = DateTime.now();
    Map<String, dynamic> data = {
      "date_added_on": Timestamp.now(),
      "day_added_on": DateFormat('EEEE').format(dateTime)
    };
    data.addEntries(trackerData.entries);
    await database
        .collection('users')
        .doc(uid)
        .collection(tracker.key)
        .doc()
        .set(data);
  }

  getFirstTrackerData(Tracker tracker, String uid) async {
    try {
      return (await database
              .collection('users')
              .doc(uid)
              .collection(tracker.key)
              .orderBy("date_added_on", descending: true)
              .limit(1)
              .get())
          .docChanges
          .first
          .doc
          .data()['value']
          .toString();
    } catch (_) {
      return null;
    }
  }

  updateSpecificTrackerDataByTimestamp(
      Tracker tracker, String uid, Timestamp timestamp) async {
    final doc = (await database
            .collection('users')
            .doc(uid)
            .collection(tracker.key)
            .where("date_added_on", isEqualTo: timestamp)
            .limit(1)
            .get())
        .docChanges
        .first
        .doc
        .reference;
    Map existingData = (await doc.get()).data();
    print(existingData);
    existingData['value'] = tracker.value;
    var batch = database.batch();
    batch.update(doc, existingData);
    await batch.commit();
  }

  Future<List> getAllTrackerData(Tracker tracker, String uid) async {
    try {
      var snapshotList = (await database
              .collection('users')
              .doc(uid)
              .collection(tracker.key)
              .orderBy("date_added_on", descending: true)
              .get())
          .docChanges;
      List<Map<String, dynamic>> mapList =
          snapshotList.map((e) => e.doc.data()).toList();
      return mapList;
    } catch (_) {
      return null;
    }
  }
}
1. createState(): When the Framework is instructed to build a StatefulWidget, it immediately calls createState()

2. mounted is true: When createState creates your state class, a buildContext is assigned to that state. buildContext is, overly simplified, the place in the widget tree in which this widget is placed. Here's a longer explanation. All widgets have a bool this.mounted property. It is turned true when the buildContext is assigned. It is an error to call setState when a widget is unmounted.

3. initState(): This is the first method called when the widget is created (after the class constructor, of course.) initState is called once and only once. It must call super.initState().

4. didChangeDependencies(): This method is called immediately after initState on the first time the widget is built.

5. build(): This method is called often. It is required, and it must return a Widget.

6. didUpdateWidget(Widget oldWidget): If the parent widget changes and has to rebuild this widget (because it needs to give it different data), but it's being rebuilt with the same runtimeType, then this method is called. This is because Flutter is re-using the state, which is long lived. In this case, you may want to initialize some data again, as you would in initState.

7. setState(): This method is called often from the framework itself and from the developer. Its used to notify the framework that data has changed

8. deactivate(): Deactivate is called when State is removed from the tree, but it might be reinserted before the current frame change is finished. This method exists basically because State objects can be moved from one point in a tree to another.

9. dispose(): dispose() is called when the State object is removed, which is permanent. This method is where you should unsubscribe and cancel all animations, streams, etc.

10. mounted is false: The state object can never remount, and an error is thrown is setState is called.
import 'dart:isolate';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: BodyWidget(),
      ),
    );
  }
}

class BodyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          CircularProgressIndicator(),
          ElevatedButton(
            child: Text('start'),
            onPressed: () async {

              //ReceivePort is to listen for the isolate to finish job
              final receivePort = ReceivePort();
              // here we are passing method name and sendPort instance from ReceivePort as listener
              await Isolate.spawn(
                  computationallyExpensiveTask, receivePort.sendPort);

              //It will listen for isolate function to finish
              receivePort.listen((sum) {
                print(sum);
              });
            },
          )
        ],
      ),
    );
  }
}

// this function should be either top level(outside class) or static method
void computationallyExpensiveTask(SendPort sendPort) {
  print('heavy work started');
  var sum = 0;
  for (var i = 0; i <= 1000000000; i++) {
    sum += i;
  }
  print('heavy work finished');
  //Remember there is no return, we are sending sum to listener defined defore.
  sendPort.send(sum);
}
import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
       home: Home()
  ));
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  TextEditingController textarea = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Multi Line TextField"),
            backgroundColor: Colors.redAccent,
         ),
          body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children: [
                   TextField(
                      controller: textarea,
                      keyboardType: TextInputType.multiline,
                      maxLines: 4,
                      decoration: InputDecoration( 
                         hintText: "Enter Remarks",
                         focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(width: 1, color: Colors.redAccent)
                         )
                      ),
                       
                   ),

                   ElevatedButton(
                     onPressed: (){
                         print(textarea.text);
                     }, 
                     child: Text("Get TextField Value")
                    )
               ],
             ),
          )
      );
  }
}
class MySwitcher extends StatelessWidget {
  const MySwitcher({super.key});

  @override
  Widget build(BuildContext context) {
    final status = context.select((MyBloc bloc) => bloc.state.status);
    switch (status) {
      case MyStatus.initial:
      case MyStatus.loading:
        return const Center(child: CircularProgressIndicator());
      case MyStatus.success:
        return const MyView();
      case MyStatus.error:
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text('Something went wrong.'),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () {
                  context.read<MyBloc>().add(MyDataRequested());
                },
                child: const Text('Try again'),
              ),
            ],
          ),
        );
    }
  }
}
// PAGE
class MyPage extends StatelessWidget {
  const MyPage({super.key});
 
  static String path = 'my';
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // Inject Bloc(s)
      body: BlocProvider(
        create: (context) => MyBloc(
          dependency: context.read<Dependency>(),
        )..add(MyDataRequested()),
        // SWITCHER
        // MySwitcher, and all its nested child Widgets, will have access to MyBloc
        child: const MySwitcher(),
      ),
    );
  }
}
class MyBloc extends Bloc<MyEvent, MyState> {
  MyBloc({required Dependency dependency})
      : _dependency = dependency,
        super(const MyState()) {
    on<MyDataRequested>(_dataRequested);
  }

  final Dependency _dependency;

  FutureOr<void> _dataRequested(
    MyDataRequested event,
    Emitter<MyState> emit,
  ) async {
    emit(state.copyWith(status: MyStatus.loading));
    try {
      final myAsyncData = await _dependency.asyncCall();
      emit(
        state.copyWith(
          myAsyncData: myAsyncData,
          status: MyStatus.success,
        ),
      );
    } catch (error, stackTrace) {
      addError(error, stackTrace);
      emit(state.copyWith(status: MyStatus.error));
    }
  }
}
enum MyStatus { initial, loading, success, error }

class MyState extends Equatable {
  const MyState({
    this.myAsyncData,
    this.status = MyStatus.initial,
  });

  final AsyncData? myAsyncData;
  final MyStatus status;

  @override
  List<Object> get props => [myAsyncData, status];

  // Creates a new state with the changed data keeping the BlocState immutable
  MyState copyWith({
    AsyncData? myAsyncData,
    MyStatus? status,
  }) {
    return MyState(
      myAsyncData: myAsyncData ?? this.myAsyncData,
      status: status ?? this.status,
    );
  }
}
// PAGE
class MyPage extends StatelessWidget {
  const MyPage({super.key});
 
  static String path = 'my';
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // Inject Bloc(s)
      body: BlocProvider(
        create: (context) => MyBloc(dependency: context.read<Dependency>()),
        // VIEW
        // MyView, and all its nested child Widgets, will have access to MyBloc
        child: const MyView(),
      ),
    );
  }
}
import 'dart:ui' show ImageFilter;

import 'package:flutter/material.dart';

class BlurContainer extends StatelessWidget {
  final Widget child;
  final double? height;
  final double? width;
  final double elevation;
  final double blur;
  final EdgeInsetsGeometry padding;
  final Color color;
  final BorderRadius borderRadius;
  final String? image;
  final AlignmentGeometry? imageAlignment;

  const BlurContainer({
    Key? key,
    required this.child,
    this.height,
    this.width,
    this.blur = 5,
    this.elevation = 0,
    this.padding = const EdgeInsets.all(8),
    this.color = Colors.transparent,
    this.borderRadius = const BorderRadius.all(Radius.circular(20)),
    this.image,
    this.imageAlignment,
  }) : super(key: key);

  const BlurContainer.square({
    Key? key,
    required this.child,
    double? dimension,
    this.blur = 5,
    this.elevation = 0,
    this.padding = const EdgeInsets.all(8),
    this.color = Colors.transparent,
    this.borderRadius = const BorderRadius.all(Radius.circular(20)),
    this.image,
    this.imageAlignment,
  })  : width = dimension,
        height = dimension,
        super(key: key);

  const BlurContainer.expand({
    Key? key,
    required this.child,
    this.blur = 5,
    this.elevation = 0,
    this.padding = const EdgeInsets.all(8),
    this.color = Colors.transparent,
    this.borderRadius = BorderRadius.zero,
    this.image,
    this.imageAlignment,
  })  : width = double.infinity,
        height = double.infinity,
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      elevation: elevation,
      color: Colors.transparent,
      borderRadius: borderRadius,
      child: ClipRRect(
        borderRadius: borderRadius,
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),
          child: Container(
            height: height,
            width: width,
            padding: padding,
            decoration: BoxDecoration(
                color: color,
                image: image != null
                    ? DecorationImage(
                        image: AssetImage(image!),
                        alignment: imageAlignment ?? Alignment.center,
                      )
                    : null),
            child: child,
          ),
        ),
      ),
    );
  }
}
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class BlocLoggerObserver extends BlocObserver {
  @override
  void onCreate(BlocBase bloc) {
    super.onCreate(bloc);
    _log("bloc created: $bloc");
  }

  @override
  void onClose(BlocBase bloc) {
    super.onClose(bloc);
    _log("bloc closed: $bloc");
  }

  @override
  void onChange(BlocBase bloc, Change change) {
    super.onChange(bloc, change);
    _log("bloc changed: $bloc, $change");
  }

  @override
  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
    super.onError(bloc, error, stackTrace);
    _log("bloc error: $bloc, $error, $stackTrace");
  }

  @override
  void onEvent(Bloc bloc, Object? event) {
    super.onEvent(bloc, event);
    _log("bloc event: $bloc, $event");
  }


  void _log(message) {
    if (kDebugMode) {
      print(message);
    }
  }
}
import 'package:flutter/material.dart';

extension ImagePreloadExtention on Image {
  void preload({
    VoidCallback? onImageLoaded,
    VoidCallback? onError,
  }) {
    image
        .resolve(ImageConfiguration())
        .addListener(ImageStreamListener((ImageInfo info, bool syncCall) {
          onImageLoaded?.call();
        }, onError: (Object exception, StackTrace? stackTrace) {
          onError?.call();
        }));
  }
}

extension PreloadImageProviderExtension on ImageProvider {
  void preload({
    VoidCallback? onImageLoaded,
    VoidCallback? onError,
  }) {
    this
        .resolve(ImageConfiguration())
        .addListener(ImageStreamListener((ImageInfo info, bool syncCall) {
          onImageLoaded?.call();
        }, onError: (Object exception, StackTrace? stackTrace) {
          onError?.call();
        }));
  }
}
       Image.network(
                  widget.networkUrl,
                  fit: BoxFit.fill,
                  loadingBuilder: (BuildContext context, Widget child,
                      ImageChunkEvent? loadingProgress) {
                    if (loadingProgress == null) return child;
                    return Center(
                      child: CircularProgressIndicator(
                        value: loadingProgress.expectedTotalBytes != null
                            ? loadingProgress.cumulativeBytesLoaded /
                                loadingProgress.expectedTotalBytes!
                            : null,
                      ),
                    );
                  },
                ),
BarChart(
    ...
    domainAxis: charts.OrdinalAxisSpec(
              renderSpec: charts.SmallTickRendererSpec(labelRotation: 60),
       ),
 ),
Column(
    children: [
        if (_selectedIndex == 0) ...[
          DayScreen(),
        ] else ...[
          StatsScreen(),
        ],
    ],
 ),
import 'package:flutter/material.dart';

class FormValidator {
  static String? empty(
    String? value,
    String errorMessage,
  ) {
    if (value == null || value.length <= 3) {
      return 'Required';
    }
    return null;
  }

  static String? validateEmail(value) {
    bool emailValid = RegExp(
            r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
        .hasMatch(value ?? '');
    if (value == null || value.isEmpty || !emailValid) {
      return 'Please enter email';
    }
    return null;
  }

  static String? password(String? value) {
    if (empty(value, 'Required') != null) {
      return empty(value, 'Required');
    }

    RegExp regEx = RegExp(r"(?=.*[A-Z])\w+");

    if (value!.length < 8 || !regEx.hasMatch(value)) {
      return 'Please enter password';
    }

    return null;
  }

  static String? passwordConfirm(value, TextEditingController controller) {
    if (value == null || value.isEmpty) {
      return 'Required';
    }

    if (value.toString() != controller.text) {
      return 'Required';
    }

    return null;
  }
}
Container(
                      width: 200.0,
                      height: 200.0,
                      decoration: BoxDecoration(
                        color: const Color(0xff7c94b6),
                        image: DecorationImage(
                          image: NetworkImage(
                              'https://media-exp1.licdn.com/dms/image/C5603AQEzw6Dk3IPgHA/profile-displayphoto-shrink_800_800/0/1608714667178?e=1650499200&v=beta&t=LOwP7T4YXz7as8iYcmzjrtdBcAVMBUN5hGSkSgSDl-8'),
                          fit: BoxFit.cover,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(95.0)),
                        border: Border.all(
                          color: Color(0xFFe0e0e0),
                          width: 4.0,
                        ),
                      ),
                    ),
 ListTile(
              title: Text(
                'Exit',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 18,
                ),
              ),
              trailing: Icon(
                Icons.logout,
              ),
              onTap: () {
                exit(0);
              },
            ),
Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            SizedBox(
                              width: 200.0,
                              height: 25.0,
                              child: Container(
                                width: 200,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  color: Colors.red,
                                ),
                                child: Text(
                                  categoris[index].categoryName,
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      fontSize: 21, color: Colors.black),
                                ),
                              ),
                            ),
                          ]),
                  Text(
                    'Password',
                    style: TextStyle(
                      color: Colors.white,
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.black26),
                    ),
                    child: TextFormField(
                      decoration: InputDecoration(
                        labelText: 'Enter Password Here',
                        labelStyle: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                        prefixIcon: Icon(Icons.lock),
                        contentPadding: EdgeInsets.all(5),
                      ),
                    ),
                  ),
        showDialog<dynamic>(
            useRootNavigator: false,
            barrierDismissible: false,
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(
                  Utils.getString(context, 'report_item'),
                ),
                content: TextField(
                  controller: showdialogText,
                  keyboardType: TextInputType.multiline,
                  textInputAction: TextInputAction.newline,
                  minLines: 1,
                  maxLines: 5,
                  onChanged: (value) {
                    setState(() {
                      valueText = value;
                    });
                  },
                ),
                actions: <Widget>[
                  Container(
                    padding: EdgeInsets.all(5),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: ElevatedButton.icon(
                            icon: const Icon(Icons.cancel),
                            label: Text(
                              Utils.getString(context, 'cancel'),
                            ),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            style: ElevatedButton.styleFrom(
                              primary: Colors.red,
                              onPrimary: Colors.white,
                            ),
                          ),
                        ),
                        const SizedBox(width: 5),
                        Expanded(
                            flex: 1,
                            child: ElevatedButton.icon(
                              icon: const Icon(Icons.save),
                              label: Text(
                                Utils.getString(context, 'save'),
                              ),
                              onPressed: () async {
                                await PsProgressDialog.showDialog(context);
                                final UserReportItemParameterHolder userReportItemParameterHolder = UserReportItemParameterHolder(
                                  itemId: widget.itemId,
                                  reportedUserId: widget.reportedUserId,
                                  message: valueText,
                                );
                                final PsResource<ApiStatus> _apiStatus = await widget.userProvider!.userReportItem(userReportItemParameterHolder.toMap());

                                if (_apiStatus.data != null && _apiStatus.data!.status != null) {
                                  await widget.itemDetailProvider.deleteLocalProductCacheById(widget.itemId, widget.reportedUserId);
                                }

                                PsProgressDialog.dismissDialog();
                                Navigator.pushReplacementNamed(
                                  context,
                                  RoutePaths.home,
                                );
                              },
                              style: ElevatedButton.styleFrom(
                                primary: Colors.green,
                                onPrimary: Colors.white,
                              ),
                            )),
                      ],
                    ),
                  ),
                ],
              );
            });
 body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Center(
            child: Container(
              child: ListView.builder(
                itemCount: 10,
                itemBuilder: (context, index) => Container(
                  height: 200,
                  width: 200,
                  color: Colors.blueGrey[300],
                ),
              ),
              height: 300,
              width: 400,
            ),
          ),
        ],
      ),
Container(
                                child: Text(
                                  items[index].itemName,
                                  style: TextStyle(
                                      color: Colors.black, fontSize: 30),
                                  textAlign: TextAlign.center,
                                ), //Text
                                height: 40,
                                width: 400,
                                  decoration:
                               BoxDecoration(
                  border: Border.all(color: Colors.black38, width: 3),
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.5),
                      spreadRadius: 5,
                      blurRadius: 5,
                      offset: Offset(0, 3), // changes position of shadow
                    ),
                  ],
                  color: Colors.white,
                  image: DecorationImage(
                    image: AssetImage(filterList[index].itemImg),
                    fit: BoxFit.contain,
                  ),
                ),
child: Padding(
                        padding: EdgeInsets.all(5),
                        child: Container(
                          height: 100,
                          width: 350,
                          color: Colors.amber[700],
                          child: Text(items[index].itemName), //Text
                        ),
                      ),
child: Text(
                      categoris[index].categoryName,
                      style: TextStyle(color: Colors.black, fontSize: 40),
                      textAlign: TextAlign.center,
                    ),
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}
IconButton(
          onPressed: () {
            print('It was pressed');
          },
            tooltip: 'Menu Bar',
          iconSize: 40,
          icon: Icon(Icons.menu),
          color: Colors.black,
        )
 appBar: PreferredSize(
        preferredSize: Size.fromHeight(90),
        child: AppBar(
          title: Text(
            'About This App',
            style: TextStyle(fontSize: 28),
          ),
          centerTitle: true,
          backgroundColor: Color(0xffbf360c),
          elevation: 10,
          shadowColor: Color(0xff3f51b5),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(25),
              bottomRight: Radius.circular(25),
            ),
          ),
        ),
      ),
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Text_input(),
      ),
    );
body: Stack(
        children: [
          Positioned(
            bottom: 20,
            right: 10,
            height: 25,
            width: 75,
            child: ElevatedButton(
              onPressed: () {
                Navigator.pop(
                  context,
                  MaterialPageRoute(
                    builder: (builder) => Text_input(),
                  ),
                );
              },
              child: Text('Back'),
            ),
          )
        ],
      ),
 TextField(
            decoration: InputDecoration(
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20)),
                focusColor: Colors.amber,
                hintText: '@gmail.com',
                labelText: 'Your email',
                prefixIcon: Icon(Icons.account_circle_sharp)),
            onChanged: (value) {}),
hasSpecialCharacters = password.contains(new RegExp(r'[!@#$%^&*(),.?":{}|<>]')); 

  final bool isNumeric = password.contains(RegExp('[0-9]'));
  final bool isLowerCase = password.contains(RegExp("(?:[^a-z]*[a-z]){1}"));
  final bool isUpperCase = password.contains(RegExp("(?:[^A-Z]*[A-Z]){1}"));
InputDecoration(
   isDense: true,
   prefixIcon:Text("\$"),
   prefixIconConstraints: BoxConstraints(minWidth: 0, minHeight: 0),
),
RichText(
  text: TextSpan(
    text: 'Hello ',
    style: DefaultTextStyle.of(context).style,
    children: const <TextSpan>[
      TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
      TextSpan(text: ' world!'),
    ],
  ),
)
RotatedBox(quarterTurns:turns,
  child: AspectRatio(
    aspectRatio: _controller.value.aspectRatio,
    child:  Stack(
      alignment: Alignment.bottomCenter,
      children: [

        VideoPlayer(_controller),
        _ControlsOverlay(controller: _controller,onClickCallback:(){
          setState(() {
            if( turns==0)
              turns=1;
            else turns=0;
          });
        }),
        VideoProgressIndicator(_controller, allowScrubbing: true),

      ],

    ),),
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
      child: RaisedButton(
        onPressed: _incrementCounter,
        child: Text('Increment Counter'),
        ),
      ),
    ),
  ));
}

_incrementCounter() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int counter = (prefs.getInt('counter') ?? 0) + 1;
  print('Pressed $counter times.');
  await prefs.setInt('counter', counter);
}
@override
Widget build(BuildContext context) {

  return new FutureBuilder<User>(
      future: userInfo,
      builder: (BuildContext context, AsyncSnapshot<User> snapshot) 
    {
      switch(snapshot.connectionState) {
        case ConnectionState.none:
          _showDialog(context);
          return Container();
        case ConnectionState.waiting:
          return new Center(
            child: new CircularProgressIndicator());
        case ConnectionState.active:
          return new Text('');
        case ConnectionState.done:
          if(snapshot.hasError) {
            error = snapshot.error;
            _showDialog(context);
            return Container();
          } else {
            return Container();
          }
      }
  });
import 'dart:async';
import 'dart:isolate';
main() async {
  var receivePort = new ReceivePort();
  await Isolate.spawn(echo, receivePort.sendPort);
// The 'echo' isolate sends it's SendPort as the first message
  var sendPort = await receivePort.first;
var msg = await sendReceive(sendPort, "bye");
  print('received $msg');
  msg = await sendReceive(sendPort, "hello");
  print('received $msg');
}
// the entry point for the isolate
echo(SendPort sendPort) async {
  // Open the ReceivePort for incoming messages.
  var port = new ReceivePort();
// Notify any other isolates what port this isolate listens to.
  sendPort.send(port.sendPort);
await for (var msg in port) {
    var data = msg[0];
    SendPort replyTo = msg[1];
    replyTo.send(data);
    if (data == "hello") port.close();
  }
}
/// sends a message on a port, receives the response,
/// and returns the message
Future sendReceive(SendPort port, msg) {
  ReceivePort response = new ReceivePort();
  port.send([msg, response.sendPort]);
  return response.first;
}
TextField(
 enabled: false, // to trigger disabledBorder
 decoration: InputDecoration(
   filled: true,
   fillColor: Color(0xFFF2F2F2),
   focusedBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.red),
   ),
   disabledBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.orange),
   ),
   enabledBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.green),
   ),
   border: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,)
   ),
   errorBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.black)
   ),
   focusedErrorBorder: OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(4)),
     borderSide: BorderSide(width: 1,color: Colors.yellowAccent)
   ),
   hintText: "HintText",
   hintStyle: TextStyle(fontSize: 16,color: Color(0xFFB3B1B1)),
   errorText: snapshot.error,
 ),
 controller: _passwordController,
 onChanged: _authenticationFormBloc.onPasswordChanged,
                            obscureText: false,
),
class AppColors {
  static MaterialColor hex(String hex) =>
      AppColors._factoryColor(AppColors._getColorHexFromStr(hex));

  static MaterialColor _factoryColor(int color) {
    return MaterialColor(color, <int, Color>{
      50: Color(color),
      100: Color(color),
      200: Color(color),
      300: Color(color),
      400: Color(color),
      500: Color(color),
      600: Color(color),
      700: Color(color),
      800: Color(color),
      900: Color(color),
    });
  }

  static int _getColorHexFromStr(String colorStr) {
    colorStr = "FF" + colorStr;
    colorStr = colorStr.replaceAll("#", "");
    int val = 0;
    int len = colorStr.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = colorStr.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        val = 0xFFFFFFFF;
      }
    }
    return val;
  }
}

// Example: In your app
// ...
class MyExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
    	height: 100.0,
      	width: 100.0,
      	decoration: BoxDecoration(
    		color: AppColors.hex('#000000'),	
    ),
    );
  }
}
Column( 
  crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( child: Text('${payment.name}',textAlign: TextAlign.left,), color: Colors.redAccent, ), ...... )
 decoration: BoxDecoration(
          border: Border(
            top: BorderSide(width: 16.0, color: Colors.lightBlue.shade600),
            bottom: BorderSide(width: 16.0, color: Colors.lightBlue.shade900),
          ),
          color: Colors.white,
        ),
extension StringExtension on String {
    String capitalize() {
      return "${this[0].toUpperCase()}${this.substring(1)}";
    }
}
appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(signedIn ? 'Home' : 'Sign In'),
      ),
Container(
      height: 120.0,
      width: 120.0,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(
              'assets/assets/alucard.jpg'),
          fit: BoxFit.fill,
        ),
        shape: BoxShape.circle,
      ),
    )
const color = const Color(0xffb74093); // Second `const` is optional in assignments.
Text(
  'Hello world',
  style: TextStyle(
    decoration: TextDecoration.underline,
  ),
)
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text('IntrinsicWidth')),
    body: Center(
      child: IntrinsicWidth(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            RaisedButton(
              onPressed: () {},
              child: Text('Short'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('A bit Longer'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('The Longest text button'),
            ),
          ],
        ),
      ),
    ),
  );
}
void main() {
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();


  testWidgets('some test', (WidgetTester tester) async {
    await binding.setSurfaceSize(Size(640, 1136));
    print(binding.createViewConfiguration());
 ...
void main() {
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();


  testWidgets('some test', (WidgetTester tester) async {
    await binding.setSurfaceSize(Size(640, 1136));
    print(binding.createViewConfiguration());
 ...
void main() {
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();


  testWidgets('some test', (WidgetTester tester) async {
    await binding.setSurfaceSize(Size(640, 1136));
    print(binding.createViewConfiguration());
 ...
final List<String> entries = <String>['A', 'B', 'C'];
final List<int> colorCodes = <int>[600, 500, 100];

ListView.separated(
  padding: const EdgeInsets.all(8),
  itemCount: entries.length,
  itemBuilder: (BuildContext context, int index) {
    return Container(
      height: 50,
      color: Colors.amber[colorCodes[index]],
      child: Center(child: Text('Entry ${entries[index]}')),
    );
  },
  separatorBuilder: (BuildContext context, int index) => const Divider(),
);
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text('IntrinsicWidth')),
    body: Center(
      child: IntrinsicHeight(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            RaisedButton(
              onPressed: () {},
              child: Text('Short'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('A bit Longer'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('The Longest text button'),
            ),
          ],
        ),
      ),
    ),
  );
}
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text('IntrinsicWidth')),
    body: Center(
      child: IntrinsicWidth(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            RaisedButton(
              onPressed: () {},
              child: Text('Short'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('A bit Longer'),
            ),
            RaisedButton(
              onPressed: () {},
              child: Text('The Longest text button'),
            ),
          ],
        ),
      ),
    ),
  );
}
import 'package:flutter/material.dart';

void main() {
  runApp(
    new MaterialApp(
      title: 'Hello World App',
      home: new myApp(),
    )
  );
}

class myApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Hello World App'),
      ),
      body: new Center(
        child: new Text(
          'Hello, world!'
        ),
      ),
    );
  }
}
Text("Border test",
    style: TextStyle(
      inherit: true,
      fontSize: 48.0,
      color: Colors.pink,
      shadows: [
        Shadow( // bottomLeft
          offset: Offset(-1.5, -1.5),
          color: Colors.white
        ),
        Shadow( // bottomRight
          offset: Offset(1.5, -1.5),
          color: Colors.white
        ),
        Shadow( // topRight
          offset: Offset(1.5, 1.5),
          color: Colors.white
        ),
        Shadow( // topLeft
          offset: Offset(-1.5, 1.5),
          color: Colors.white
        ),
      ]
    ),
);
String capitalize(String s) {
  if (s == null || s.isEmpty) {
    return s;
  }
  return s.length < 1 ? s.toUpperCase() : s[0].toUpperCase() + s.substring(1);
}
star

Tue Oct 22 2024 07:13:41 GMT+0000 (Coordinated Universal Time)

#dart #flutter #custom #signin
star

Thu Sep 19 2024 20:16:29 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http #2lancer
star

Tue Sep 03 2024 09:19:58 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Sun Sep 01 2024 08:07:50 GMT+0000 (Coordinated Universal Time)

#dart #flutter #user #usermodel
star

Sat Aug 17 2024 01:20:17 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http #2lancer
star

Sat Aug 17 2024 00:58:14 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http #2lancer
star

Sat Aug 17 2024 00:56:17 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http #2lancer
star

Sat Aug 17 2024 00:55:54 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http #2lancer
star

Sat Aug 17 2024 00:54:26 GMT+0000 (Coordinated Universal Time) https://2lancer.ma/page/terms

#flutter #laravel #api #http #2lancer
star

Sun Aug 04 2024 01:49:39 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Tue Jul 23 2024 21:02:10 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Sat Jul 13 2024 11:08:00 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http
star

Tue Jul 09 2024 20:07:28 GMT+0000 (Coordinated Universal Time)

#flutter #dart #firebase
star

Tue Jul 09 2024 20:06:40 GMT+0000 (Coordinated Universal Time)

#flutter #dart #firebase
star

Tue Jul 02 2024 23:35:43 GMT+0000 (Coordinated Universal Time)

#flutter #dart #firebase
star

Wed Jun 19 2024 08:07:51 GMT+0000 (Coordinated Universal Time)

#flutter #laravel #api #http
star

Thu May 02 2024 11:22:09 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Thu May 02 2024 06:58:49 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Mon Apr 29 2024 12:38:22 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Thu Apr 25 2024 07:51:39 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Fri Apr 12 2024 07:49:03 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Fri Apr 05 2024 13:36:55 GMT+0000 (Coordinated Universal Time) https://reqres.in/api/users/23

#dart #flutter
star

Fri Apr 05 2024 12:46:26 GMT+0000 (Coordinated Universal Time) https://reqres.in/api/users/2

#dart #flutter
star

Fri Mar 22 2024 07:02:08 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Fri Jan 19 2024 18:23:36 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Fri Jan 19 2024 16:22:19 GMT+0000 (Coordinated Universal Time)

#flutter
star

Fri Jan 19 2024 16:10:34 GMT+0000 (Coordinated Universal Time)

#flutter
star

Fri Jan 19 2024 15:52:09 GMT+0000 (Coordinated Universal Time)

#flutter
star

Fri Jan 19 2024 12:46:34 GMT+0000 (Coordinated Universal Time)

#flutter
star

Fri Jan 12 2024 11:46:34 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Fri Jan 12 2024 11:46:15 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Fri Jan 12 2024 11:45:42 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Fri Jan 12 2024 09:29:57 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Tue Jan 09 2024 10:10:05 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Tue Jan 09 2024 10:07:36 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Tue Jan 09 2024 10:06:29 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Tue Jan 09 2024 10:06:00 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Tue Jan 09 2024 10:05:23 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Tue Jan 09 2024 10:04:46 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Wed Nov 29 2023 10:25:06 GMT+0000 (Coordinated Universal Time)

#flutter #dart #scroll
star

Wed Oct 11 2023 08:13:18 GMT+0000 (Coordinated Universal Time) https://resocoder.com/2019/09/30/hive-flutter-tutorial-lightweight-fast-database/

#flutter
star

Tue Sep 05 2023 05:21:02 GMT+0000 (Coordinated Universal Time) s

#flutter
star

Sun Aug 06 2023 09:09:48 GMT+0000 (Coordinated Universal Time)

#flutter
star

Fri Aug 04 2023 11:43:55 GMT+0000 (Coordinated Universal Time)

#flutter
star

Wed Aug 02 2023 12:31:13 GMT+0000 (Coordinated Universal Time)

#flutter
star

Sat Jun 24 2023 13:17:30 GMT+0000 (Coordinated Universal Time)

#flutter
star

Tue May 23 2023 10:37:50 GMT+0000 (Coordinated Universal Time) https://shamlatech.com/cryptocurrency-development/

#flutter #c# #c++
star

Mon May 08 2023 10:35:05 GMT+0000 (Coordinated Universal Time) https://shamlatech.com/paxful-clone-script/

#flutter #c# #c++
star

Tue Mar 21 2023 07:34:59 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Tue Mar 21 2023 07:34:30 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Thu Feb 16 2023 11:01:26 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/69482360/flutter-open-modal-bottom-sheet-on-bottom-navigation-bar-item-click

#dart #flutter
star

Wed Feb 15 2023 18:26:11 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Sun Nov 27 2022 15:32:15 GMT+0000 (Coordinated Universal Time)

#flutter
star

Tue Nov 08 2022 10:57:04 GMT+0000 (Coordinated Universal Time)

#flutter
star

Tue Nov 08 2022 10:52:17 GMT+0000 (Coordinated Universal Time) https://codingwithtashi.medium.com/isoltate-flutter-dart-multithreading-cf5f67de9b46

#flutter #dart
star

Wed Oct 19 2022 04:21:14 GMT+0000 (Coordinated Universal Time) https://medium.com/@mibcoder/folder-creation-in-flutter-a554c238b7e8

#dart #flutter
star

Mon Oct 10 2022 22:46:16 GMT+0000 (Coordinated Universal Time) https://www.fluttercampus.com/guide/176/how-to-make-multi-line-textfield-input-textarea-in-flutter/

#dart #flutter
star

Thu Oct 06 2022 15:54:44 GMT+0000 (Coordinated Universal Time)

#dart #flutter #bloc #page #view
star

Thu Oct 06 2022 14:58:50 GMT+0000 (Coordinated Universal Time)

#dart #flutter #bloc #page #view
star

Thu Oct 06 2022 14:19:52 GMT+0000 (Coordinated Universal Time)

#dart #flutter #bloc #page #view
star

Thu Oct 06 2022 14:18:34 GMT+0000 (Coordinated Universal Time)

#dart #flutter #bloc #page #view
star

Thu Oct 06 2022 11:22:44 GMT+0000 (Coordinated Universal Time)

#dart #flutter #bloc #page #view
star

Sat Aug 27 2022 13:04:41 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Thu Jul 21 2022 09:37:04 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Thu Jul 14 2022 04:59:44 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Fri May 27 2022 06:04:14 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/53577962/better-way-to-load-images-from-network-flutter

#dart #flutter
star

Tue May 24 2022 20:56:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/54437448/charts-flutter-labels-text-on-x-axis-overlapping-each-other

#dart #flutter
star

Fri May 20 2022 14:41:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/49713189/how-to-use-conditional-statement-within-child-attribute-of-a-flutter-widget-cen

#flutter
star

Tue Apr 05 2022 11:46:23 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Sat Feb 19 2022 05:43:45 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Sun Feb 13 2022 20:38:55 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Fri Feb 11 2022 08:09:17 GMT+0000 (Coordinated Universal Time) https://imgur.com/a/gMhKD7B

#flutter #dart
star

Wed Feb 09 2022 18:54:34 GMT+0000 (Coordinated Universal Time) https://imgur.com/a/TrU40gV

#flutter #dart
star

Wed Feb 09 2022 08:26:10 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Mon Jan 31 2022 16:47:09 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Sun Jan 30 2022 11:39:22 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Sun Jan 30 2022 09:21:01 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Sun Jan 30 2022 08:43:08 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Fri Jan 28 2022 16:49:28 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/63873338/what-does-widgetsflutterbinding-ensureinitialized-do

#dart #flutter
star

Tue Jan 25 2022 14:02:13 GMT+0000 (Coordinated Universal Time)

#flutter #dart
star

Sun Jan 23 2022 19:33:41 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Sun Jan 23 2022 10:05:33 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Sun Jan 23 2022 08:57:24 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=EgtPleVwxBQ&t=64s

#dart #flutter
star

Fri Jan 21 2022 20:22:34 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Fri Jan 14 2022 15:10:07 GMT+0000 (Coordinated Universal Time) https://gist.github.com/rahulbagal/4a06a997497e6f921663b69e5286d859

#flutter
star

Sat Sep 18 2021 00:29:49 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/58819979/is-there-a-way-to-create-a-text-field-with-a-prefix-that-is-always-visible-in-fl

#dart #flutter
star

Tue Sep 14 2021 15:43:06 GMT+0000 (Coordinated Universal Time) https://api.flutter.dev/flutter/widgets/RichText-class.html

#dart #flutter
star

Tue Sep 14 2021 12:54:07 GMT+0000 (Coordinated Universal Time) https://rrtutors.com/tutorials/how-to-rotate-flutter-widget

#flutter #android
star

Tue Sep 14 2021 04:23:19 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/54135078/how-to-solve-error-running-pod-install-in-flutter-on-mac

#dart #flutter
star

Sat Sep 11 2021 03:44:46 GMT+0000 (Coordinated Universal Time) https://pub.dev/packages/shared_preferences

#flutter
star

Fri Aug 27 2021 05:58:23 GMT+0000 (Coordinated Universal Time) https://medium.com/flutter-community/flutter-threading-5c3a7b0c065f

#flutter #dart
star

Fri Aug 27 2021 05:28:55 GMT+0000 (Coordinated Universal Time) https://medium.com/flutterdevs/threading-in-flutter-e5b84c7d8d31

#flutter #dart #threading
star

Sun Jul 04 2021 12:02:09 GMT+0000 (Coordinated Universal Time) https://gist.github.com/matteocrippa/3a8b84c7b49c10bc070e58a66860e83f#file-flutter-md

#flutter #dart
star

Sun Jul 04 2021 12:00:39 GMT+0000 (Coordinated Universal Time) https://github.com/Temidtech/Flutter-Cheat-Sheet/blob/master/README.md

#dart #flutter
star

Mon Jun 28 2021 14:12:38 GMT+0000 (Coordinated Universal Time) https://www.advancedinstaller.com/install-test-certificate-from-msix.html

#flutter
star

Wed Jun 09 2021 11:44:26 GMT+0000 (Coordinated Universal Time) https://pub.dev/packages/table_calendar

#flutter
star

Fri Apr 23 2021 17:34:56 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/50122394/not-able-to-change-textfield-border-color

#dart #flutter
star

Fri Apr 23 2021 02:25:58 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Sat Apr 10 2021 06:33:52 GMT+0000 (Coordinated Universal Time)

#dart #flutter
star

Thu Mar 25 2021 15:10:11 GMT+0000 (Coordinated Universal Time) https://fluttercentral.com/Articles/Post/1056/How_to_add_a_border_to_only_one_part_of_the_container_in_Flutter

#dart #flutter
star

Mon Mar 22 2021 10:50:27 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/29628989/how-to-capitalize-the-first-letter-of-a-string-in-dart

#dart #flutter
star

Wed Mar 17 2021 13:56:41 GMT+0000 (Coordinated Universal Time) https://github.com/flutter/flutter/issues/67277

#dart #flutter
star

Tue Mar 16 2021 16:29:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/52211283/inserting-image-into-a-container-flutter-app

#dart #flutter
star

Mon Mar 15 2021 10:38:42 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/50081213/how-do-i-use-hexadecimal-color-strings-in-flutter

#dart #flutter
star

Thu Mar 11 2021 14:20:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/50614661/how-to-underline-text-in-flutter

#dart #flutter
star

Mon Mar 08 2021 13:00:55 GMT+0000 (Coordinated Universal Time) https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e

#dart #flutter
star

Wed Sep 30 2020 06:33:59 GMT+0000 (Coordinated Universal Time)

#flutter
star

Wed Sep 30 2020 06:33:59 GMT+0000 (Coordinated Universal Time)

#flutter
star

Wed Sep 30 2020 06:33:59 GMT+0000 (Coordinated Universal Time)

#flutter
star

Fri Aug 07 2020 16:15:21 GMT+0000 (Coordinated Universal Time) https://api.flutter.dev/flutter/widgets/ListView-class.html

#flutter
star

Tue May 12 2020 11:03:36 GMT+0000 (Coordinated Universal Time) https://gist.github.com/basselch/51b8a047c5c86355c5859a2e5f198fd0

#dart #flutter
star

Tue May 12 2020 11:02:17 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/48893935/how-to-remove-debug-banner-in-flutter-on-android-emulator

#dart #flutter
star

Wed Jan 22 2020 18:43:41 GMT+0000 (Coordinated Universal Time) https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e

#dart #flutter #layouts
star

Wed Jan 22 2020 18:35:33 GMT+0000 (Coordinated Universal Time) https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e

#dart #flutter #layout
star

Sun Dec 29 2019 19:42:22 GMT+0000 (Coordinated Universal Time) https://kodestat.gitbook.io/flutter/flutter-hello-world

#android #dart #flutter #ios #helloworld
star

Thu Dec 26 2019 18:27:15 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/52146269/how-to-decorate-text-stroke-in-flutter

#dart #flutter #howto

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension