Snippets Collections
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome  to Android Studio"
        android:textSize="35dp"
        android:textColor="@color/design_default_color_secondary"
        android:textStyle="bold"
        
        
        />
    <TextView
        
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:text="My Name is write ur name"
        android:textColor="@color/purple_200"
        android:textSize="35dp"
        android:textStyle="italic"
        
        />
    <EditText
        android:id="@+id/firstnum"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:hint="Enter the First Number"
        
        
        />
    <EditText
        android:id="@+id/secondnum"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:hint="Enter the Second Number"


        />

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/Title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="Welcome to Android studioo"
        android:textSize="35dp"
        android:textColor="@color/purple_700"
        android:textStyle="italic"
        />
    <TextView
        android:id="@+id/Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="My name is Shankar"
        android:textColor="@color/black"
        android:textSize="35dp"
        android:textStyle="bold"/>
    <EditText
        android:id="@+id/firstname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enetr the first name"/>
    <EditText
        android:id="@+id/Second"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter second numb"/>

</LinearLayout>
function customRatingScoreHTML($productID)
{
  $product = wc_get_product($productID);
  $average      = $product->get_average_rating();
  $rating_whole = floor($average);
  $rating_fraction = $average - $rating_whole;
  $flug = 0;
  for ($i = 1; $i <= 5; $i++) {
    if ($i <= $rating_whole) {
      echo '<i class="fas fa-star"></i>';
    } else {
      if ($rating_fraction > 0 && $flug == 0) {
        echo '<i class="fas fa-star-half-alt"></i>';
        $flug = 1;
      } else {
        echo '<i class="far fa-star empty"></i>';
      }
    }
  }
}
<?php
//Team Post Type;
add_action('init', 'our_team_post_type_init');
function our_team_post_type_init()
{

    $labels = array(

        'name' => __('Team', 'post type general name', ''),
        'singular_name' => __('Our Team', 'post type singular name', ''),
        'add_new' => __('Add New', 'Our Team', ''),
        'add_new_item' => __('Add New Our Team', ''),
        'edit_item' => __('Edit Our Team', ''),
        'new_item' => __('New Our Team', ''),
        'view_item' => __('View Our Team', ''),
        'search_items' => __('Search Our Team', ''),
        'not_found' =>  __('No Our Team found', ''),
        'not_found_in_trash' => __('No Our Team found in Trash', ''),
        'parent_item_colon' => ''
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'rewrite' => true,
        'query_var' => true,
        'capability_type' => 'post',
        'hierarchical' => true,
        'public' => true,
        'has_archive' => true,
        'show_in_nav_menus' => true,
        'menu_position' => null,
        'rewrite' => array(
            'slug' => 'teams',
            'with_front' => true
        ),
        'supports' => array(
            'title',
            'editor',
            'thumbnail'
        )
    );

    register_post_type('team', $args);
}

// Add Shortcode [our_team];
add_shortcode('our_team', 'codex_our_team');
function codex_our_team()
{
    ob_start();
    wp_reset_postdata();
    ?>
    <div class="section__body">
  <div class="team-members">
    <ul>
			<?php
			$arg = array(
				'post_type' => 'team',
				'posts_per_page' => -1,
				'order' => 'ASC',
			);
			$po = new WP_Query($arg);
			?>
			<?php if ($po->have_posts()) : ?>
				<?php while ($po->have_posts()) : ?>
					<?php $po->the_post(); ?>
            <li>
              <div class="team-member">
                <a href="<?php the_permalink(); ?>">
                  <div class="team__image image-fit js-image-fit">
                      <?php echo get_the_post_thumbnail( get_the_ID(), 'full' );?>
                  </div>
                  <!-- /.team__image -->
                  <div class="team__content">
                    <h5><?php the_title(); ?>   </h5>
                    <!-- <p>Principal</p> -->
                  </div>
                  <!-- /.team__content -->
                </a>
              </div>
              <!-- /.team-member -->
            </li>
					
				<?php endwhile; ?>
			<?php endif; ?>
				</ul>
  </div>
  <!-- /.team-members -->
</div>
<?php
    wp_reset_postdata();
    return '' . ob_get_clean();
}



/*********************** SINGLE PAGE TEAM SECTION ***********************/
<?php get_header(); ?>

<div class="section-blog-member">
  <div class="shell">
    <div class="section__inner">
      <div class="section__head">
        <figure class="section__image">
          <img src="<?php the_field('featured_member_banner'); ?>" alt="<?php the_permalink(); ?>">                 
        </figure>
        <!-- /.section__image -->
        <div class="section__content">
          <div class="section__name">
            <h1><?php the_title(); ?></h1>
          </div>
          <!-- /.section__name -->
          <div class="section__job">
            <!-- <h2 class="h1">Principal</h2> -->
          </div>
          <!-- /.section__job -->
        </div>
        <!-- /.section__content -->
      </div>
      <!-- /.section__head -->
      <div class="section__body">
        <div class="section__entry">
          <?php the_content(); ?>
        </div>
        <!-- /.section__entry -->
      </div>
      <!-- /.section__body -->
    </div>
    <!-- /.section__inner -->
  </div>
  <!-- /.shell -->
</div>
<!-- /.section-blog-member -->
<?php get_footer(); ?>



/*********************** CSS FOR TEAM SECTION ***********************/
/*OUR TEAM*/
.team-members > ul { display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; margin: 0 0; list-style: none; padding: 0; }
.team-members > ul > li { width: 50%; padding: 0; }
.team-member { text-align: center; text-transform: uppercase; }
.team-member > a { display: block; text-decoration: none; }
.team-member .team__image { margin-bottom: 44px; }
.team-member .team__image { -webkit-transition: opacity .4s; -o-transition: opacity .4s; transition: opacity .4s; }
.image-fit { overflow: hidden; position: relative; background-size: cover; background-position: 50%; }
.team-member > a:hover .team__image { opacity: .3; -webkit-transition: opacity .4s; -o-transition: opacity .4s; transition: opacity .4s; }
.team-member .team__image img { height: 600px; object-fit: cover; }
.team-member h5 { font-size: 24px; line-height: 30px; font-family: 'Questrial', sans-serif; }

/*TEAM SINGLE*/
.section-blog-member { font-size: 20px; line-height: 30px; color: #000; font-weight: 400; font-family: "Questrial", sans-serif; }
.section-blog-member .section__image { margin: 0; position: relative; margin-left: calc(-50vw + 50%); width: 100vw }
.section-blog-member .section__image img { width: 100%; display: block }
.section-blog-member .section__content { position: absolute; left: 51.6%; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); z-index: 1 }
.section-blog-member .section__job { font-style: italic }
.section-blog-member .section__head { position: relative }
.section-blog-member .section__head:not(:last-child) { margin-bottom: 80px; }
.section-blog-member .section__body { max-width: 750px; margin-inline: auto }
.section-blog-member .section__name h1 { font-size: 64px; font-family: 'Questrial', sans-serif; line-height: 40px; }
.section-blog-member .section__entry p { margin-bottom: 1.5em; }
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate]
"ProductVersion"="Windows 10"
"TargetReleaseVersion"=dword:00000001
"TargetReleaseVersionInfo"="22H2"
@extends('new_layouts.app')
@section('styles')
    <style>
        .custom-table {
            border-collapse: collapse;
            border-radius: 1rem;
            border-style: hidden;
            box-shadow: 0 0 0 1px #e6ebef;
            overflow: hidden;
            text-align: left;
            width: 100%;
        }

        .badge-file-extension {
            background-color: #f25961;
            color: white;
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.375rem;
            margin-left: 0.5rem;
        }

        .bookmark-active svg {
            fill: #FF9800;
        }

        .description-text {
            font-size: 1.1rem;
            color: #555;
            margin-top: 0.5rem;
        }

        .comment {
            margin-top: 1rem;
            margin-bottom: 1rem;
        }

        .comment-section {
            border: 1px solid #e9ebee;
            border-radius: 1rem;
            padding: 1.5rem;
            background-color: #ffffff;
            /* box-shadow: 0 0 1rem rgba(0, 0, 0, 0.1); */
        }

        .comment-header {
            border-bottom: 1px solid #e9ebee;
            padding-bottom: 0.75rem;
            margin-bottom: 1rem;
        }

        .comment-avatar {
            height: 48px;
            width: 48px;
            border-radius: 50%;
            margin-right: 1rem;
        }

        .comment-author {
            font-size: 1rem;
            font-weight: 600;
        }

        .comment-time {
            font-size: 0.875rem;
            color: #90949c;
        }

        .comment-body {
            margin: 0.75rem 0;
            font-size: 1rem;
        }

        .comment-actions a {
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-right: 1rem;
        }

        .comment-actions i {
            margin-right: 0.5rem;
        }

        .reply-list {
            margin-top: 1rem;
            padding-left: 2rem;
        }

        .reply-list .comment {
            border-left: 1px dotted #d3d6db;
            padding-left: 1rem;
            margin-top: 1rem;
        }

        .reply-toggle {
            cursor: pointer;
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-top: 1rem;
            display: block;
        }

        .reply-form {
            display: none;
            position: relative;
            z-index: 10;
        }

        .comment-input {
            border-radius: 0.5rem;
        }

        .like-button.active i {
            color: #4caf50;
        }

        .dislike-button.active i {
            color: #dc3545;
        }


        /* Dropdown Styles */
        .dropdown-toggle::after {
            display: none;
            /* Remove the default arrow */
        }

        .dropdown-menu {
            right: 0;
            left: auto;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="mt-4 comment-section">
            <h3>Comments ( {{ $comments->count() }} )</h3>
            <div class="comment-header d-flex justify-content-between align-items-center">
            </div>
            <div class="comment-body">
                <div class="d-flex mb-3">
                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                        class="comment-avatar">
                    <div class="w-100">
                        <form id="comment-form" action="{{ route('comments.store', $material) }}" method="POST">
                            @csrf
                            <div class="d-flex flex-column">
                                <textarea name="content" class="form-control comment-input" placeholder="Write a comment..." rows="3"></textarea>
                                <div class="d-flex justify-content-between mt-2">
                                    <div id="comment-form-error" class="text-danger"></div>
                                    <button type="submit" class="btn btn-primary">Post Comment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div id="comment-list" class="comment-list">
                    @foreach ($comments as $comment)
                        <div class="comment" data-comment-id="{{ $comment->id }}">
                            <div class="d-flex">
                                <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                                    class="comment-avatar">
                                <div class="w-100">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <div class="comment-author">{{ $comment->user->name }}</div>
                                            <div class="comment-time">{{ $comment->created_at->diffForHumans() }}</div>
                                        </div>
                                        @if ($comment->user_id === auth()->id())
                                            <div class="dropdown">
                                                <button class="btn btn-link dropdown-toggle" type="button"
                                                    id="dropdownMenuButton{{ $comment->id }}" data-bs-toggle="dropdown"
                                                    aria-expanded="false">
                                                    <i class="fa-solid fa-ellipsis-vertical"></i>
                                                </button>
                                                <ul class="dropdown-menu"
                                                    aria-labelledby="dropdownMenuButton{{ $comment->id }}">
                                                    <li><a class="dropdown-item" href="#" data-action="edit"
                                                            data-comment-id="{{ $comment->id }}">Edit</a></li>
                                                    <li><a class="dropdown-item text-danger" href="#"
                                                            data-action="delete"
                                                            data-comment-id="{{ $comment->id }}">Delete</a></li>
                                                </ul>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="comment-body">{{ $comment->content }}</div>
                                    <div class="comment-actions">
                                        <a href="#"
                                            class="like-button {{ $comment->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="like" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-up"></i>
                                            <span class="like-dislike-count">{{ $comment->likes }}</span>
                                        </a>
                                        <a href="#"
                                            class="dislike-button {{ $comment->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="dislike" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-down"></i>
                                            <span class="like-dislike-count">{{ $comment->dislikes }}</span>
                                        </a>
                                        <a href="#" class="reply-link" data-comment-id="{{ $comment->id }}"
                                            data-author="{{ $comment->user->name }}">
                                            <i class="fa-solid fa-reply"></i> Reply
                                        </a>
                                    </div>
                                    <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>

                                    <form class="reply-form" action="{{ route('replies.store', $comment) }}"
                                        method="POST">
                                        @csrf
                                        <div class="d-flex flex-column">
                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                            <div class="d-flex justify-content-between mt-2">
                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                    Error: Reply cannot be empty
                                                </div>
                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                            </div>
                                        </div>

                                    </form>
                                    <div class="reply-list" style="display: none;">
                                        @foreach ($comment->replies as $reply)
                                            <div class="comment reply" data-comment-id="{{ $reply->id }}">
                                                <div class="d-flex">
                                                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg"
                                                        alt="avatar" class="comment-avatar">
                                                    <div class="w-100">
                                                        <div class="d-flex justify-content-between align-items-start">
                                                            <div>
                                                                <div class="comment-author">{{ $reply->user->name }}</div>
                                                                <div class="comment-time">
                                                                    {{ $reply->created_at->diffForHumans() }}</div>
                                                            </div>
                                                            @if ($reply->user_id === auth()->id())
                                                                <div class="dropdown">
                                                                    <button class="btn btn-link dropdown-toggle"
                                                                        type="button"
                                                                        id="dropdownMenuButton{{ $reply->id }}"
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu"
                                                                        aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                                                        <li><a class="dropdown-item" href="#"
                                                                                data-action="edit"
                                                                                data-comment-id="{{ $reply->id }}">Edit</a>
                                                                        </li>
                                                                        <li><a class="dropdown-item text-danger"
                                                                                href="#" data-action="delete"
                                                                                data-comment-id="{{ $reply->id }}">Delete</a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            @endif
                                                        </div>
                                                        <div class="comment-body">
                                                            @if ($reply->parent)
                                                                <a href="#"
                                                                    class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                                                            @endif
                                                            <span class="reply-content">{{ $reply->content }}</span>
                                                        </div>
                                                        <div class="comment-actions">
                                                            <a href="#"
                                                                class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="like" data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-up"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->likes }}</span>
                                                            </a>
                                                            <a href="#"
                                                                class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="dislike"
                                                                data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-down"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->dislikes }}</span>
                                                            </a>
                                                            <a href="#" class="reply-link"
                                                                data-comment-id="{{ $reply->id }}"
                                                                data-author="{{ $reply->user->name }}">
                                                                <i class="fa-solid fa-reply"></i> Reply
                                                            </a>
                                                        </div>
                                                        <form class="reply-form"
                                                            action="{{ route('replies.store', $reply) }}" method="POST">
                                                            @csrf
                                                            <div class="d-flex flex-column">
                                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                                <div class="d-flex justify-content-between mt-2">
                                                                    <div id="comment-form-error" class="text-danger"
                                                                        style="display: none;">
                                                                        Error: Reply cannot be empty
                                                                    </div>
                                                                    <button type="submit"
                                                                        class="btn btn-primary ms-auto">Post Reply</button>
                                                                </div>
                                                            </div>

                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            @include('materials.comment', ['replies' => $reply->replies])
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('[data-action="edit"]').forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    const commentId = this.getAttribute('data-comment-id');
                    const commentBodyElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"] .comment-body`);
                    const mentionElement = commentBodyElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const content = commentBodyElement.querySelector('.reply-content').innerText
                        .trim();

                    // Store original content for cancel action
                    commentBodyElement.dataset.originalContent = commentBodyElement.innerHTML;

                    const editForm = `
                    <form class="edit-comment-form" data-comment-id="${commentId}">
                        ${mention ? `<span class="reply-mention">${mention}</span>` : ''}
                        <textarea class="form-control">${content}</textarea>
                        <button type="submit" class="btn btn-primary mt-2">Save</button>
                        <button type="button" class="btn btn-secondary mt-2 cancel-edit">Cancel</button>
                    </form>
                `;

                    commentBodyElement.innerHTML = editForm;
                    attachEditFormListeners(commentId);
                });
            });
        });

        function attachEditFormListeners(commentId) {
            document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`).addEventListener('submit',
                function(e) {
                    e.preventDefault();
                    const content = this.querySelector('textarea').value;
                    const mention = this.querySelector('.reply-mention') ? this.querySelector('.reply-mention')
                        .innerText.trim() : '';

                    fetch(`/comments/${commentId}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute(
                                    'content')
                            },
                            body: JSON.stringify({
                                content
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentBodyElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"] .comment-body`);
                                const mentionElement = mention ?
                                    `<a href="#" class="reply-mention">${mention}</a>` : '';
                                commentBodyElement.innerHTML =
                                    `${mentionElement} <span class="reply-content">${data.content}</span>`;
                            } else {
                                alert('Error updating comment.');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                });

            document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"] .cancel-edit`).addEventListener(
                'click',
                function() {
                    const originalContent = document.querySelector(
                        `.comment[data-comment-id="${commentId}"] .comment-body`).dataset.originalContent;
                    document.querySelector(`.comment[data-comment-id="${commentId}"] .comment-body`).innerHTML =
                        originalContent;
                });
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            // for delete 
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="delete"]');
                if (button) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');

                    if (confirm('Are you sure you want to delete this comment?')) {
                        fetch(`/comments/${commentId}`, {
                                method: 'DELETE',
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                        .getAttribute('content'),
                                    'Content-Type': 'application/json',
                                }
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    const commentElement = document.querySelector(
                                        `.comment[data-comment-id="${commentId}"]`);
                                    if (commentElement) {
                                        commentElement.remove();
                                    }
                                } else {
                                    alert(data.message || 'Error deleting comment');
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                alert('Something went wrong');
                            });
                    }
                }
            });

            // for like and dislike
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a');
                if (button && (button.classList.contains('like-button') || button.classList.contains(
                        'dislike-button'))) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');
                    const action = button.getAttribute('data-action');

                    fetch(`/comments/${commentId}/${action}`, {
                            method: 'POST',
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                _method: 'POST'
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"]`);
                                const likeCount = commentElement.querySelector(
                                    '.like-button .like-dislike-count');
                                const dislikeCount = commentElement.querySelector(
                                    '.dislike-button .like-dislike-count');

                                likeCount.textContent = data.comment.likes;
                                dislikeCount.textContent = data.comment.dislikes;

                                if (action === 'like') {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.dislike-button').classList.remove(
                                        'active');
                                } else {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.like-button').classList.remove(
                                        'active');
                                }
                            } else {
                                alert(data.message || 'Error updating like/dislike');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Something went wrong');
                        });
                }
            });

            // for submission of the main comment form
            document.getElementById('comment-form')?.addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(this);
                const errorDiv = document.getElementById('comment-form-error');
                errorDiv.textContent = ''; // Clear previous errors

                fetch(this.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                .getAttribute('content')
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const commentList = document.getElementById('comment-list');
                            if (commentList) {
                                const newCommentHtml = `
                                <div class="comment" data-comment-id="${data.comment.id}">
                                    <div class="d-flex">
                                        <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                        <div class="w-100">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <div class="comment-author">${data.comment.user_name}</div>
                                                    <div class="comment-time">${data.comment.created_at}</div>
                                                </div>
                                                <div class="dropdown">
                                                    <button class="btn btn-link dropdown-toggle" type="button"
                                                        id="dropdownMenuButton${data.comment.id}" data-bs-toggle="dropdown"
                                                        aria-expanded="false">
                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                    </button>
                                                    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.comment.id}">
                                                        <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.comment.id}">Edit</a></li>
                                                        <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.comment.id}">Delete</a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                            <div class="comment-body">${data.comment.content}</div>
                                            <div class="comment-actions">
                                                <a href="#" class="like-button" data-action="like" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-up"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-down"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="reply-link" data-comment-id="${data.comment.id}" data-author="${data.comment.user_name}">
                                                    <i class="fa-solid fa-reply"></i> Reply
                                                </a>
                                            </div>
                                            <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>
                                            <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                @csrf
                                            <div class="d-flex flex-column">
                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                <div class="d-flex justify-content-between  mt-2">
                                                    <div id="comment-form-error" class="text-danger" style="display: none;">
                                                        Error: Reply cannot be empty
                                                    </div>
                                                    <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                </div>
                                            </div>
                                            </form>
                                            <div class="reply-list" style="display: none;"></div>
                                        </div>
                                    </div>
                                </div>
                            `.replace(':commentId', data.comment.id);

                                commentList.insertAdjacentHTML('afterbegin', newCommentHtml);
                                this.reset();
                                initializeDropdowns();
                            }
                        } else {
                            // Display error messages
                            errorDiv.textContent = data.error || 'Your comment is empty';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        errorDiv.textContent = 'Something went wrong';
                    });
            });


            // for submission of reply forms
            document.getElementById('comment-list')?.addEventListener('submit', function(event) {
                if (event.target.closest('.reply-form')) {
                    event.preventDefault();
                    const form = event.target;
                    const formData = new FormData(form);
                    const parentId = form.closest('.comment').dataset.commentId;
                    const errorDiv = form.querySelector('#comment-form-error');

                    // Reset error display
                    errorDiv.style.display = 'none';
                    errorDiv.textContent = '';

                    fetch(form.action.replace(':commentId', parentId), {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const replyList = form.closest('.reply-list') || form.closest(
                                    '.comment').querySelector('.reply-list');
                                if (replyList) {
                                    const newReplyHtml = `
                                    <div class="comment reply" data-comment-id="${data.reply.id}">
                                        <div class="d-flex">
                                            <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                            <div class="w-100">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <div class="comment-author">${data.reply.user_name}</div>
                                                        <div class="comment-time">${data.reply.created_at}</div>
                                                    </div>
                                                    <div class="dropdown">
                                                        <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton${data.reply.id}" data-bs-toggle="dropdown" aria-expanded="false">
                                                            <i class="fa-solid fa-ellipsis-vertical"></i>
                                                        </button>
                                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.reply.id}">
                                                            <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.reply.id}">Edit</a></li>
                                                            <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.reply.id}">Delete</a></li>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div class="comment-body">${data.reply.parent_name ? '<a href="#">' + '@' + data.reply.parent_name + '</a> ' : ''}${data.reply.content}</div>
                                                <div class="comment-actions">
                                                    <a href="#" class="like-button" data-action="like" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-up"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-down"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="reply-link" data-comment-id="${data.reply.id}" data-author="${data.reply.user_name}">
                                                        <i class="fa-solid fa-reply"></i> Reply
                                                    </a>
                                                </div>
                                                <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                    @csrf
                                                        <div class="d-flex flex-column">
                                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                            <div class="d-flex justify-content-between  mt-2">
                                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                                    Error: Reply cannot be empty
                                                                </div>
                                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                            </div>
                                                        </div>
                                                </form>
                                                <div class="reply-list" style="display: none;"></div>
                                            </div>
                                        </div>
                                    </div>
                                    `.replace(':commentId', data.reply.id);

                                    replyList.insertAdjacentHTML('beforeend', newReplyHtml);
                                    form.reset();
                                    initializeDropdowns();
                                }
                            } else {
                                // Display error message
                                errorDiv.textContent = data.message || 'Error posting reply';
                                errorDiv.style.display = 'block';
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            // Display error message
                            errorDiv.textContent = 'Something went wrong';
                            errorDiv.style.display = 'block';
                        });
                }
            });




            // for reply link click to show reply form
            document.getElementById('comment-list')?.addEventListener('click', function(event) {
                if (event.target.closest('.reply-link')) {
                    event.preventDefault();
                    const replyForm = event.target.closest('.comment').querySelector('.reply-form');
                    if (replyForm) {
                        replyForm.style.display = replyForm.style.display === 'block' ? 'none' : 'block';
                    }
                }
            });
        });

        function initializeDropdowns() {
            const dropdowns = document.querySelectorAll('.dropdown-toggle:not(.initialized)');
            dropdowns.forEach(dropdown => {
                new bootstrap.Dropdown(dropdown);
                dropdown.classList.add('initialized');
            });
        }

        function toggleReplies(element) {
            const replyList = element.nextElementSibling.nextElementSibling;
            const isVisible = replyList.style.display === 'block';
            replyList.style.display = isVisible ? 'none' : 'block';
            element.textContent = isVisible ? 'View replies' : 'Hide replies';
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.bookmark-toggle').forEach(function(button) {
                button.addEventListener('click', function() {
                    const fileId = this.getAttribute('data-file-id');
                    const button = this;

                    fetch("{{ route('bookmark.toggle') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                file_id: fileId
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'added') {
                                button.classList.add('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks-fill" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5z"/>
                                        <path d="M4.268 1A2 2 0 0 1 6 0h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L13 13.768V2a1 1 0 0 0-1-1z"/>
                                    </svg>`;
                            } else if (data.status === 'removed') {
                                button.classList.remove('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5zm2-1a1 1 0 0 0-1 1v10.566l3.723-2.482a.5.5 0 0 1 .554 0L11 14.566V4a1 1 0 0 0-1-1z"/>
                                        <path d="M4.268 1H12a1 1 0 0 1 1 1v11.768l.223.148A.5.5 0 0 0 14 13.5V2a2 2 0 0 0-2-2H6a2 2 0 0 0-1.732 1"/>
                                    </svg>`;
                            }
                        })
                        .catch(error => console.error('Error:', error));
                });
            });
        });
    </script>
@endsection


@foreach ($replies as $reply)
    <div class="comment reply" data-comment-id="{{ $reply->id }}">
        <div class="d-flex">
            <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
            <div class="w-100">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="comment-author">{{ $reply->user->name }}</div>
                        <div class="comment-time">{{ $reply->created_at->diffForHumans() }}</div>
                    </div>
                    @if ($reply->user_id === auth()->id())
                        <div class="dropdown">
                            <button class="btn btn-link dropdown-toggle" type="button"
                                id="dropdownMenuButton{{ $reply->id }}" data-bs-toggle="dropdown"
                                aria-expanded="false">
                                <i class="fa-solid fa-ellipsis-vertical"></i>
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                <li><a class="dropdown-item" href="#" data-action="edit"
                                        data-comment-id="{{ $reply->id }}">Edit</a>
                                </li>
                                <li><a class="dropdown-item text-danger" href="#" data-action="delete"
                                        data-comment-id="{{ $reply->id }}">Delete</a>
                                </li>
                            </ul>
                        </div>
                    @endif
                </div>
                <div class="comment-body">
                    @if ($reply->parent)
                        <a href="#" class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                    @endif
                    <span class="reply-content">{{ $reply->content }}</span>
                </div>
                <div class="comment-actions">
                    <a href="#"
                        class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                        data-action="like" data-comment-id="{{ $reply->id }}">
                        <i class="fa-solid fa-thumbs-up"></i>
                        <span class="like-dislike-count">{{ $reply->likes }}</span>
                    </a>
                    <a href="#"
                        class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                        data-action="dislike" data-comment-id="{{ $reply->id }}">
                        <i class="fa-solid fa-thumbs-down"></i>
                        <span class="like-dislike-count">{{ $reply->dislikes }}</span>
                    </a>
                    <a href="#" class="reply-link" data-comment-id="{{ $reply->id }}"
                        data-author="{{ $reply->user->name }}">
                        <i class="fa-solid fa-reply"></i> Reply
                    </a>
                </div>
                <form class="reply-form" action="{{ route('replies.store', $reply) }}" method="POST">
                    @csrf
                    <div class="d-flex flex-column">
                        <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                        <div class="d-flex justify-content-between  mt-2">
                            <div id="comment-form-error" class="text-danger" style="display: none;">
                                Error: Reply cannot be empty
                            </div>
                            <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                        </div>
                    </div>

                </form>
                <div id="edit-comment-template" style="display: none;">
                    <div class="edit-comment-form">
                        <textarea class="form-control edit-comment-input" rows="3"></textarea>
                        <div class="text-end mt-2">
                            <button type="button" class="btn btn-primary save-edit-button">Save</button>
                            <button type="button" class="btn btn-secondary cancel-edit-button">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @include('materials.comment', ['replies' => $reply->replies])
@endforeach
Harness the power of next-gen asset tokenization platform development with Maticz. A trusted asset tokenization platform development company like Maticz helps business convert their illiquid asset into a tradable digital token. Tokenization of high-value assets through blockchain offers a secured transaction with transparency. This also offers a fragmented property ownership of a large asset. Fuel your business growth by digitalizing your high-value asset with Maticz.
function woo_checkout_custom_coupon_form(){
	if ( ! wc_coupons_enabled() ) { // @codingStandardsIgnoreLine.
		return;
	}
?>
<div class="mini-cart-nm-coupon">
	<div class="mini-cart-nm-coupon-heading">Enter your discount code</div>
    <div class="nm-coupon" style="display: flex;">
       <input type="text" id="nm-coupon-code" class="input-text nm-coupon-code" name="nm_coupon_code" value="" placeholder="">
       <button type="button" id="nm-apply-coupon-btn" class="button" name="nm_apply_coupon" value="" onclick="applyCoupon(this)" style="white-space: nowrap;"><?php esc_html_e( 'ACTIVATE', 'woocommerce' ); ?></button>
    </div>
    <div class="nm-coupon-notify" style="display: none; color: #FF0000;"></div>
</div>
<script type="text/javascript">
function applyCoupon(button) {
    let form = button.closest('.nm-coupon');
	button.innerText = 'ACTIVATE...';
    let couponCode = form.querySelector(".nm-coupon-code").value;
    let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    
    jQuery.ajax({
        type: "GET",
        url: ajaxurl,
        dataType: 'json',
        data: 'coupon_code=' + couponCode + '&action=custom_apply_coupon',
        success: function (data) {
            if (data.status === 'success') {
                jQuery(document.body).trigger('wc_fragment_refresh');
                
            } else if (data.status === 'already_used') {
                jQuery('.nm-coupon-notify').html('Coupon already used!');
                jQuery('.nm-coupon-notify').show();
            } else {
                jQuery('.nm-coupon-notify').html('Coupon is not valid!');
                jQuery('.nm-coupon-notify').show();
            }
			if (jQuery('body').hasClass('woocommerce-checkout'))
                    jQuery(document.body).trigger('update_checkout');
        },
    });
}
// Remove coupon script
(function($) {
    $('body').on('click', '.woocommerce-remove-coupon', function(e) {
        e.preventDefault();
        let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        var coupon = $(this).data('coupon');
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'remove_coupon',
                coupon: coupon,
            },
            success: function(response) {
                jQuery(document.body).trigger('wc_fragment_refresh');
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    });
})(jQuery);	
</script>
<?php    
}
add_action( 'woo_custom_checkout_coupon_form', 'woo_checkout_custom_coupon_form',10 );

add_action('wp_ajax_custom_apply_coupon', 'custom_apply_coupon');
add_action('wp_ajax_nopriv_custom_apply_coupon', 'custom_apply_coupon');

function custom_apply_coupon() {
    $coupon_code = isset($_GET['coupon_code']) ? $_GET['coupon_code'] : '';
    $coupon_code = sanitize_text_field($coupon_code);

    // Check if the coupon is already applied
    if (WC()->cart->has_discount($coupon_code)) {
        echo json_encode(array('status' => 'already_used'));
    } else {
        // Apply coupon
        $applied = WC()->cart->apply_coupon($coupon_code);
        if ($applied) {
            echo json_encode(array('status' => 'success'));
        } else {
            echo json_encode(array('status' => 'invalid'));
        }
    }
    wp_die();
}

add_action('wp_ajax_remove_coupon', 'remove_coupon_from_cart');
add_action('wp_ajax_nopriv_remove_coupon', 'remove_coupon_from_cart');

function remove_coupon_from_cart() {
    if (isset($_POST['coupon'])) {
        $coupon_code = sanitize_text_field($_POST['coupon']);
        WC()->cart->remove_coupon($coupon_code);
        wc_clear_notices(); 
        
        wp_send_json_success();
    } else {
        wp_send_json_error('Coupon code not provided.');
    }
}
.parent-container{
  //defining a grid container
  display: grid;
  //defining rows and columns
  grid-template: 50px 50px / 50px 50px;
  //defining a row and column gap
  gap: 20px 50px;
  
  
}

When we use the grid-template propertie, we are explicitly defining grid tracks to lay out our grid items. But when the grid needs more tracks for extra content, it will implicitly define new grid tracks. Additionally, the size values established from our grid-template propertie are not carried over into these implicit grid tracks. But we can define values for the implicit grid tracks.

Let’s say we want any new rows to stay the same value as our explicit row track sizes:

.parent-container {
  display: grid;
  grid-template: 50px 50px;
  grid-auto-rows: 50px;
}
// Driver function
        for(int i = 0; i < V; i++){
            if(!vis[i]) {
                if(cycleBFS(i, vis, adj)) return true;
            }
        }



// cycle check fun by BFS
    bool cycleBFS(int src, vector<int> &vis, vector<int> adj[]){
        queue<pair<int,int>> q;
        vis[src] = 1;
        q.push({src,-1});
        
        while(!q.empty()){
            int node = q.front().first;
            int parent = q.front().second;
            q.pop();
            
            for(auto it: adj[node]){
                if(!vis[it]){
                    vis[it] = 1;
                    q.push({it, node});
                }
                else if(parent != it){
                    return true;
                }
            }
        }
        return false;
    }




add_action('init', 'aovup_register_awaiting_dispatch_order_status');
function aovup_register_awaiting_dispatch_order_status() {
    register_post_status('wc-awaiting-dispatch', array(
        'label'                     => 'Awaiting Dispatch',
        'public'                    => true,
        'exclude_from_search'       => false,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        'label_count'               => _n_noop('Awaiting Dispatch <span class="count">(%s)</span>', 'Awaiting Dispatch <span class="count">(%s)</span>')
    ));
}

add_filter('wc_order_statuses', 'aovup_add_awaiting_dispatch_to_order_statuses');
function aovup_add_awaiting_dispatch_to_order_statuses($order_statuses) {
    $order_statuses['wc-awaiting-dispatch'] = 'Awaiting Dispatch';
    return $order_statuses;
}

add_filter('bulk_actions-edit-shop_order', 'aovup_add_awaiting_dispatch_bulk_action');
function aovup_add_awaiting_dispatch_bulk_action($bulk_actions) {
    // Add a new bulk action named "Mark Awaiting Dispatch"
    $bulk_actions['mark_awaiting-dispatch'] = 'Mark Awaiting Dispatch';
    return $bulk_actions;
}

add_filter('handle_bulk_actions-edit-shop_order', 'aovup_handle_mark_awaiting_dispatch_bulk_action', 10, 3);
function aovup_handle_mark_awaiting_dispatch_bulk_action($redirect_to, $doaction, $post_ids) {
    if ($doaction !== 'mark_awaiting-dispatch') {
        return $redirect_to;
    }

    foreach ($post_ids as $post_id) {
        $order = wc_get_order($post_id);
        $order->update_status('awaiting-dispatch');
    }

    $redirect_to = add_query_arg('bulk_awaiting_dispatch_orders', count($post_ids), $redirect_to);
    return $redirect_to;
}
add_filter( 'wc_order_statuses', 'wc_renaming_order_status' );
function wc_renaming_order_status( $order_statuses ) {
    foreach ( $order_statuses as $key => $status ) {
        if ( 'wc-completed' === $key ) 
            $order_statuses['wc-completed'] = _x( 'Order Received', 'Order status', 'woocommerce' );
    }
    return $order_statuses;
}

/**configure your WordPress site to send emails via the Brevo API**/

function send_email_via_brevo($to, $subject, $message, $headers = '', $attachments = []) {
    $api_url = 'https://api.brevo.com/v3/smtp/email';
    $api_key = '123'; // Your Brevo API key

    // Email data structure
    $email_data = [
        'sender' => [
            'email' => 'contact@example.com', // Your email address
            'name' => 'Your Name' // Your name
        ],
        'to' => [
            [
                'email' => $to, // Recipient's email
                'name' => '' // Recipient's name (optional)
            ]
        ],
        'subject' => $subject,
        'htmlContent' => $message
    ];

    // Headers for the API request
    $request_headers = [
        'Content-Type: application/json',
        'api-key: ' . $api_key
    ];

    // Arguments for the API request
    $args = [
        'body' => json_encode($email_data),
        'headers' => $request_headers,
        'method' => 'POST',
        'data_format' => 'body'
    ];

    // Send the API request
    $response = wp_remote_post($api_url, $args);

    // Handle any errors
    if (is_wp_error($response)) {
        error_log('Email sending failed: ' . $response->get_error_message());
        return false;
    }

    // Log the response
    $response_body = wp_remote_retrieve_body($response);
    error_log('Email sent response: ' . $response_body);

    return true;
}

function override_wp_mail($args) {
    return send_email_via_brevo($args['to'], $args['subject'], $args['message'], $args['headers'], $args['attachments']);
}

add_filter('wp_mail', 'override_wp_mail', 10, 1);

MID({!$Flow.FaultMessage}, FIND('FIELD_CUSTOM_VALIDATION_EXCEPTION: ', {!$Flow.FaultMessage}) + LEN('FIELD_CUSTOM_VALIDATION_EXCEPTION: '), FIND('. Você pode consultar valores de ExceptionCode', {!$Flow.FaultMessage}) - FIND('FIELD_CUSTOM_VALIDATION_EXCEPTION: ', {!$Flow.FaultMessage}) - LEN('FIELD_CUSTOM_VALIDATION_EXCEPTION: '))
git clone https://github.com/yourusername/route-optimization.git
cd route-optimization
pip install -r requirements.txt
#include <bits/stdc++.h>
#include <iostream>
using namespace std;

#define MOD 1000000007
#define ll long long int
#define fr(i, a, b) for (int i = a; i < b; i++)

inline int binaryExponentiation(ll base, int exp, int mod = MOD) {
    ll result = 1;
    while (exp) {
        if (exp & 1) result = (result * base) % mod;
        base = (base * base) % mod;
        exp >>= 1;
    }
    return (int)result;
}

void solve() {
    int n;
    cin >> n;
    ll answer = 0;
    fr(i, 1, n) {
        ll current = binaryExponentiation(2, n - i - 1);
        current = (2 * current * (n - i)) % MOD;
        current = (current * i) % MOD;
        current = (current * i) % MOD;
        answer = (answer + current) % MOD;
    }
    cout << answer << endl;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int t;
    cin >> t;
    while (t--) solve();
    return 0;
}
#include<bits/stdc++.h>
#define ll long long
using namespace std;


bool is_valid(int x,int y,int r,int c,vector<vector<char>>&v){
    if(x<1 || x>r || y<1 || y>c || v[x][y]=='#') return false;
    return true;
}


void dfs(int &x,int &y,vector<vector<char>>&v,string &s,int r,int c,int &idx,int l){
    if(idx<l && s[idx]=='U' && is_valid(x,y,r,c,v)){
       dfs(x-1,y,v,s,r,c,idx+1);
    }
    if(idx<l && s[idx]=='L' && is_valid(x,y,r,c,v)){
       dfs(x,y-1,v,s,r,c,idx+1);
    }
    
    if(idx<l && s[idx]=='R' && is_valid(x,y,r,c,v)){
       dfs(x,y+1,v,s,r,c,idx+1);
    }
    
    if(idx<l && s[idx]=='D' && is_valid(x,y,r,c,v)){
       dfs(x+1,y,v,s,r,c,idx+1);
    }
    return;
}


int main(){
    int r,c,x,y;
    cin>>r>>c>>x>>y;
    vector<vector<char>>v(r,vector<char>(c));
    for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            cin>>a[i][j];
        }
    }
    string s;
    cin>>s;
    int l=s.length();
    
    dfs(x,y,v,s,r,c,0,l);
    cout<<x<<" "<<y;
    return 0;
    
}
@media (max-width: 600px) {
    nav ul {
        text-align: center;
    }

    nav ul li {
        display: block;
        margin: 0.5rem 0;
    }
}
<tts service="android" speed="1.0" voice="en-US" style="display: none">{{En}}</tts>
// Add a checkbox to the terms and conditions section
add_action('woocommerce_checkout_terms_and_conditions', 'add_custom_checkout_checkbox', 20);
function add_custom_checkout_checkbox() {
    woocommerce_form_field('factor_need', array(
        'type'  => 'checkbox',
        'class' => array('woocommerce-form__input woocommerce-form__input-checkbox'),
        'label' => ('آیا مایل به دریافت فاکتور هستید؟', 'woocommerce'),
    ));
}

// Save the checkbox value in the order meta
add_action('woocommerce_checkout_update_order_meta', 'save_custom_checkout_checkbox');
function save_custom_checkout_checkbox($order_id) {
    if (isset($_POST['factor_need'])) {
        update_post_meta($order_id, 'factor_need', 'yes');
    } else {
        update_post_meta($order_id, 'factor_need', 'no');
    }
}

// Display the checkbox value in the admin order details
add_action('woocommerce_admin_order_data_after_billing_address', 'display_custom_checkout_checkbox_in_admin', 10, 1);
function display_custom_checkout_checkbox_in_admin($order) {
    $factor_need = get_post_meta($order->get_id(), 'factor_need', true);
    if ($factor_need === 'yes') {
        echo '<p><strong>' . ('نیاز به فاکتور:', 'woocommerce') . '</strong> ' . __('هست', 'woocommerce') . '</p>';
    } 
}
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
}

header {
    background-color: #333;
    color: white;
    padding: 1rem;
    text-align: center;
}

nav ul {
    list-style-type: none;
    padding: 0;
}

nav ul li {
    display: inline;
    margin: 0 1rem;
}

nav ul li a {
    color: white;
    text-decoration: none;
}

section {
    padding: 2rem;
    margin: 1rem;
}

footer {
    background-color: #333;
    color: white;
    text-align: center;
    padding: 1rem;
    position: fixed;
    width: 100%;
    bottom: 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Portfolio</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>Welcome to My Portfolio</h1>
        <nav>
            <ul>
                <li><a href="#about">About</a></li>
                <li><a href="#projects">Projects</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
        </nav>
    </header>
    <section id="about">
        <h2>About Me</h2>
        <p>This is the about section.</p>
    </section>
    <section id="projects">
        <h2>Projects</h2>
        <p>This is the projects section.</p>
    </section>
    <section id="contact">
        <h2>Contact</h2>
        <p>This is the contact section.</p>
    </section>
    <footer>
        <p>&copy; 2024 My Portfolio</p>
    </footer>
</body>
</html>
import React, { useState } from 'react';

const App = () => {
  // Initialize with one set of input boxes
  const [inputSets, setInputSets] = useState([{ id: Date.now() }]);

  const handleAddClick = () => {
    // Add a new set of input boxes
    setInputSets([...inputSets, { id: Date.now() }]);
  };

  const handleDeleteClick = (id) => {
    // Ensure at least one set of input boxes remains
    if (inputSets.length > 1) {
      setInputSets(inputSets.filter(set => set.id !== id));
    }
  };

  return (
    <div>
      <button onClick={handleAddClick}>
        Add Input Boxes
      </button>

      {inputSets.map(set => (
        <div key={set.id} style={{ marginBottom: '10px' }}>
          <input type="text" placeholder="Input 1" />
          <input type="text" placeholder="Input 2" />
          {/* Conditionally render the delete button */}
          {inputSets.length > 1 && (
            <button 
              onClick={() => handleDeleteClick(set.id)} 
              style={{ marginLeft: '10px' }}
            >
              Delete
            </button>
          )}
        </div>
      ))}
    </div>
  );
};

export default App;
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { Md5 } from 'ts-md5';
import { environment } from '../../environments/environment';
import { OrderService } from '../Services/order.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { UserService } from '../Services/userprofile.service';
import { CartItemViewModel, OrderViewModel } from '../shared/order';
import { PaymentViewModel } from '../shared/payment';
import { PaymentService } from '../Services/payment.service';

declare global {
  interface Window {
    payfast_do_onsite_payment: (param1: any, callback: any) => any;
  }
}

@Component({
  selector: 'app-payfast',
  standalone: true,
  imports: [],
  templateUrl: './payfast.component.html',
  styleUrl: './payfast.component.css'
})
export class PayfastComponent implements OnInit {
  memberId!: number;

  constructor(private router : Router, private orderService : OrderService, private paymentService : PaymentService , private userService: UserService, private formBuilder: FormBuilder, private snackBar: MatSnackBar) {
    
  }

  ngOnInit(): void {
    this.fetchMemberId();
  }

  getSignature(data : Map<string, string>) : string {
    let tmp = new URLSearchParams();
    data.forEach((v, k)=> {
      tmp.append(k, v)
    });
    let queryString = tmp.toString();
    let sig = Md5.hashStr(queryString);
    return sig;
  }

  async doOnSitePayment() {
    await this.fetchMemberId();

    let onSiteUserData = new Map<string, string>();
    onSiteUserData.set("merchant_id", "10033427")
    onSiteUserData.set("merchant_key", "mu83ipbgas9p7")

    onSiteUserData.set('return_url', window.location.origin + '/payment-success')
    onSiteUserData.set('cancel_url', window.location.origin + '/payment-cancel')

    // Gather required user data from orderService or other sources
    const userData = this.orderService.getUserData();
    onSiteUserData.set("email_address", userData.email);
    
    // Set amount and item_name
    this.orderService.getTotalAmount().subscribe(amount => {
      onSiteUserData.set('amount', amount.toString());
      onSiteUserData.set('item_name', 'Cart Purchase');

      // Optional passphrase for added security
      onSiteUserData.set('passphrase', 'HelloWorldHello'); // Use if you have a passphrase

      let signature = this.getSignature(onSiteUserData);
      onSiteUserData.set('signature', signature);

      let formData = new FormData();
      onSiteUserData.forEach((val, key) => {
        formData.append(key, val);
      });

      fetch(environment.payfastOnsiteEndpoint, {
        method: 'POST',
        body: formData,
        redirect: 'follow'
      })
      .then(response => response.json())
      .then(respJson => {
          let uuid = respJson['uuid'];
          window.payfast_do_onsite_payment({ 'uuid': uuid }, (res: any) => {
            if (res == true) {
              this.createOrder().then((orderResponse) => {
                this.createPayment(orderResponse);
                this.snackBar.open('Payment Successful', 'Close', { duration: 5000 });
              });         
            } else {
              this.snackBar.open('Payment Failed', 'Close', { duration: 5000 });              
            }
          });
        })
        .catch(error => {
          console.error('Error processing payment:', error);
          this.router.navigate(['/cancel']);
        });
      });
    }

    //order
    private fetchMemberId() {
      const user = localStorage.getItem('User');
      if (user) {
        const userData = JSON.parse(user);
        this.memberId = userData.userId;
    
        // Optional: Fetch and validate member details if needed
        this.userService.getMemberByUserId(this.memberId).subscribe({
          next: (member) => {
            if (member && member.member_ID) {
              this.memberId = member.member_ID;
              console.log('Member ID:', this.memberId); // Check if this logs the correct ID
            } else {
              console.error('Member ID is undefined in the response');
              this.snackBar.open('Failed to retrieve member information', 'Close', { duration: 5000 });
            }
          },
          error: (error) => {
            console.error('Error fetching member:', error);
            this.snackBar.open('Failed to retrieve member information', 'Close', { duration: 5000 });
          }
        });
      } else {
        this.snackBar.open('User not logged in', 'Close', { duration: 5000 });
        this.router.navigate(['/login']);
      }
    }

    private createOrder(): Promise<OrderViewModel> {
      return new Promise((resolve, reject) => {
        if (this.memberId === undefined) {
          this.snackBar.open('Member ID is not available', 'Close', { duration: 5000 });
          reject('Member ID is not available');
        } else {
          this.orderService.getCartItems().subscribe({
            next: (cartItems) => {
              const order = this.prepareOrderDetails(cartItems);
              this.orderService.createOrder(order).subscribe({
                next: (orderResponse) => {
                  this.snackBar.open('Order Created Successfully', 'Close', { duration: 5000 });
                  resolve(orderResponse);
                },
                error: (error) => {
                  console.error('Error creating order:', error);
                  this.snackBar.open('Failed to create order', 'Close', { duration: 5000 });
                  reject(error);
                }
              });
            },
            error: (error) => {
              console.error('Error fetching cart items:', error);
              this.snackBar.open('Failed to fetch cart items', 'Close', { duration: 5000 });
              reject(error);
            }
          });
        }
      });
    }
    
  private prepareOrderDetails(cartItems: CartItemViewModel[]): OrderViewModel {
    const order: OrderViewModel = {
      order_ID: 0, // ID will be generated by backend
      member_ID: this.memberId,
      order_Date: new Date().toISOString(),
      total_Price: this.calculateTotalPrice(cartItems),
      order_Status_ID: 1, // Ready for Collection
      isCollected: false,
      orderLines: cartItems.map(item => ({
        order_Line_ID: 0, // ID will be generated by backend
        product_ID: item.product_ID,
        product_Name: item.product_Name,
        quantity: item.quantity,
        unit_Price: item.unit_Price
      }))
    };
  
    console.log('Prepared order details:', order);
    return order;
  }

  // Helper method to calculate the total price
  private calculateTotalPrice(cartItems: CartItemViewModel[]): number {
    return cartItems.reduce((total, item) => total + (item.unit_Price * item.quantity), 0);
  }

  private createPayment(order: OrderViewModel) {
    const paymentData: PaymentViewModel = {
      payment_ID: 0,
      amount: order.total_Price,
      payment_Date: new Date().toISOString(),
      order_ID: order.order_ID,
      payment_Type_ID: 1 // Default to 1
    };

    this.paymentService.createPayment(paymentData).subscribe({
      next: (response) => {
        console.log('Payment record created successfully:', response);
        this.router.navigate(['/orders']);
      },
      error: (error) => {
        console.error('Error creating payment record:', error);
      }
    });
  }  
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: Xero Boost Days What's on! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Hey London! \n\n We're excited to kickstart another great week in the office with our new Boost Day Program! :zap: \n\nPlease see below for what's on this week! "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-6: Tuesday, 6th August",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Café-style beverages with Vinyl Coffee, located 6a Tileyard Rd, London N79AH (Please bring your Xero ID to claim your free coffee)\n:breakfast: *Breakfast*: Provided by *Sands Catering* from *9:00AM - 10:00AM* in the Kitchen."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-8: Thursday, 8th August",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Café-style beverages with Vinyl Coffee, located 6a Tileyard Rd, London N79AH (Please bring your Xero ID to claim your free coffee)\n:Lunch: *Lunch*: Provided by *Sands Catering* from *12:00PM - 1:00PM* in the Kitchen."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Comms will be via this slack channel, get ready to Boost your workdays!\n\nLove,\nWX Team :party-wx:"
			}
		}
	]
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  </head>
  <body>
    <h1 style="background-color: rgb(247, 215, 74);color: rgb(0, 0, 0);text-align: center;font-size: 50px;">

    Vasavi mart
     
        
     
    </h1>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
  </body>
  <nav class="navbar navbar-expand-lg bg-body-tertiary">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">Products</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="#">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">daily use</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
              which you need
            </a>
            <ul class="dropdown-menu">
              <li><a class="dropdown-item" href="#">snacks</a></li>
              <li><a class="dropdown-item" href="#">organic items</a></li>
              <li><hr class="dropdown-divider"></li>

            </ul>
          </li>
          <li class="nav-item">
            <a class="nav" aria-disabled="true">Disabled</a>
          </li>
        </ul>
        <form class="d-flex" role="search">
          <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success" type="submit">Search</button>
        </form>
      </div>
    </div>
  </nav>
  <marquee class="slide" style="background-color: aqua;font-size: large;">
    this website is used only by owners
  </marquee>

  <div id="carouselExample" class="carousel slide">
    <div class="carousel-inner">
      <div class="carousel-item active">
        <img src="fresh-healthy-vegetable-market-online-facebook-cover-banner-premium-vector_640223-41.avif" class="d-block w-100" alt="...">
      </div>
      <div class="carousel-item">
        <img src="mart 5.jpg" class="d-block w-100" alt="...">
      </div>
      <div class="carousel-item">
        <img src="mart 6.jpg" class="d-block w-100" alt="...">
      </div>
    </div>
    <button class="carousel-control-prev" type="button" data-bs-target="#carouselExample" data-bs-slide="prev">
      <span class="carousel-control-prev-icon" aria-hidden="true"></span>
      <span class="visually-hidden">Previous</span>
    </button>
    <button class="carousel-control-next" type="button" data-bs-target="#carouselExample" data-bs-slide="next">
      <span class="carousel-control-next-icon" aria-hidden="true"></span>
      <span class="visually-hidden">Next</span>
    </button>
    <div >
        <h2 style="text-align: center;background-color: rgb(236, 255, 255);font-size: 50px;">ORGANIC FARM</h2>
        <div class="container">
    
            <div class="box" style="background-color: rgb(159, 175, 159);text-align: center;margin: 20px;padding: 10px;">
                <h5>Vegetables</h5>
                <img src="vege.jpg" alt="" width="300" height="100px">
                <br>
                <br>
                <button>Buy Now</button>
             </div>
             <div class="box" style="background-color: rgb(133, 150, 144);text-align: center;margin: 20px;padding: 10px;">
                <h5>Milk and curd</h5>
                <img src="milk.jpg" alt="" width="300" height="100px"><br><br>
                <button>Buy Now</button>
             </div>

             <div class="box" style="background-color: rgb(70, 75, 73);text-align: center;margin: 20px;padding: 10px;">
                <h5>Fruits</h5>
                <img src="fruits.jpg" alt="" width="300px" height="100px"><br><br>
                <button>Buy Now</button>
                <br>
                <br>
             
             </div>
                  
        
<style>
    .container{
        border: 5px  solid black;
        display:flex;
        width: auto;
    }
    .box{
        border: 5px  solid black;
    }
</style>
        </div>
  </div>
</html>
$(document).ready(function() {
    // Select the div with the class 'radiobuttonlist'
    $('.radiobuttonlist').each(function() {
        // Find each input within the radiobuttonlist div
        $(this).find('input[type="radio"]').each(function() {
            // Get the current input
            var $input = $(this);
            // Get the corresponding label for the current input
            var $label = $('label[for="' + $input.attr('id') + '"]');
            // Create a new div with class 'radiowp'
            var $wrapper = $('<div class="radiowp"></div>');
            // Wrap the input and label with the new div
            $input.add($label).wrapAll($wrapper);
        });
    });
});
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: What's on in Melbourne this week! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n Hey Melbourne, happy Monday! Please see below for what's on this week! "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Xero Café :coffee:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n :new-thing: This week we are offering Brownie Slice (GF), White Chocolate & Macadamia Cookies and Melting Moments Biscuits!\n *Weekly Café Special*: _Salted Caramel Hot Cocoa_"
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Wednesday, 14th August :calendar-date-14:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n:late-cake: *Afternoon Tea*: Provided by *Brisk Catering* from *2pm* in the *L1, L2 and L3* kitchens!\n:massage:*Wellbeing - Massage*: Book a session <https://bookings.corporatebodies.com/|*here*> to relax and unwind. \n *Username:* xero \n *Password:* 1234"
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Thursday, 15th August :calendar-date-15:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":breakfast: *Breakfast*: Provided by *Kartel Catering* from *8:30am - 10:30am* in the Wominjeka Breakout Space.\n "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*LATER THIS MONTH:*"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*Thursday, 22nd August*\n :blob-party: *Social + (Nashville Theme)*: Drinks, food, and engaging activities bringing everyone together. Make sure you put on your cowboy/cowgirl hats and join us for the party! :cowboy-twins:"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Stay tuned to this channel for more details, check out the <https://calendar.google.com/calendar/u/0?cid=Y19xczkyMjk5ZGlsODJzMjA4aGt1b3RnM2t1MEBncm91cC5jYWxlbmRhci5nb29nbGUuY29t|*Melbourne Social Calendar*>, and get ready to Boost your workdays!\n\nLove,\nWX Team :party-wx:"
			}
		}
	]
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Furniture Store</title>
    <style>

        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
            color: #333;
        }
        header {
            background-color: #333;
            color: #fff;
            padding: 10px;
            text-align: center;
        }
        .container {
            max-width: 1200px;
            margin: auto;
            padding: 20px;
        }
        .product {
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            padding: 20px;
            border-radius: 5px;
        }
        .product img {
            max-width: 100%;
            height: auto;
            border-radius: 5px;
            margin-bottom: 10px;
        }
        .product h2 {
            font-size: 1.4rem;
            margin-bottom: 10px;
        }
        .product p {
            font-size: 1rem;
            line-height: 1.6;
        }
        footer {
            background-color: #333;
            color: #fff;
            text-align: center;
            padding: 10px;
            position: absolute;
            bottom: 0;
            width: 100%;
        }
        @media (min-width: 768px) {
            .container {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
                grid-gap: 20px;
            }
        } 
    </style>
</head>
<body>
    <header>
        <h1>Furniture Store</h1>
        <p>Discover our latest collection of stylish furniture.</p>
    </header>
    <div class="container">
        <div class="product">
            <img src="https://via.placeholder.com/400x300" alt="Product 1">
            <h2>Modern Sofa Set</h2>
            <p>A stylish sofa set for your living room. Comes with matching cushions and coffee table.</p>
            <p>$799.99</p>
            <button>Add to Cart</button>
        </div>
        <div class="product">
            <img src="https://via.placeholder.com/400x300" alt="Product 2">
            <h2>Wooden Dining Table</h2>
            <p>Handcrafted dining table made from solid wood. Comfortably seats six people.</p>
            <p>$499.99</p>
            <button>Add to Cart</button>
        </div>
        <div class="product">
            <img src="https://via.placeholder.com/400x300" alt="Product 3">
            <h2>Leather Recliner Chair</h2>
            <p>Luxurious leather recliner chair with ergonomic design. Perfect for relaxation.</p>
            <p>$299.99</p>
            <button>Add to Cart</button>
        </div>
        <div class="product">
            <img src="https://via.placeholder.com/400x300" alt="Product 4">
            <h2>Minimalist Desk</h2>
            <p>Simple and elegant desk for your home office. Features spacious drawers and a smooth finish.</p>
            <p>$199.99</p>
            <button>Add to Cart</button>
        </div>
    </div>
    <footer>
        <p>&copy; 2024 Furniture Store. All rights reserved.</p>
    </footer>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Time Table Pattern</title>
    <style>
        body {
             font-family: arial;  
        }
        header{
            text-align: center;
            background-color: #333;
            color: white;
            padding:20px;
            margin-left:500px;
            margin-right: 500px;

        }
        nav{
            text-decoration: none;
            text-align: right;
            color:rgb(204, 10, 117);
            font-size:20px;
            padding:20px
        }
        a:hover{
            color: yellow;
            background-color: #333;
        }
        a{
            text-decoration: none;
            color:aqua;
        }

    </style>
    <body>
        <header>
            <h1>Time Table Pattern</h1>
            <h3>For Future</h3>
        </header>
        <nav>
            <a href="pgm1.html">PATTERN FOR GAMES</a>
            <a href="pgm2.html">MARKETING</a>
            <a href="pgm3.html">PURCHASING</a>
            <a href="pgm4.html">FURNITURE</a>
        </nav>
</head>

</html>
.your-component .react-colorful {
  height: 240px;
}
.your-component .react-colorful__saturation {
  border-radius: 4px 4px 0 0;
}
.your-component .react-colorful__hue {
  height: 40px;
  border-radius: 0 0 4px 4px;
}
.your-component .react-colorful__hue-pointer {
  width: 12px;
  height: inherit;
  border-radius: 0;
}
git remote add origin https://github.com/shookthacr3ator777/examples.git
git branch -M main
git push -u origin main
echo "# examples" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/shookthacr3ator777/examples.git
git push -u origin main
@import "compass/css";

​
3
// toggle the cube dimensions here.

$cubeWidth: px;
5
$cubeHeight: 0px;

$cubeDepth: $cubeHeight;

​

body {

  color: #3;

  padding: 20px;

  text-align: center;

  font-family: Arial;

}

​

.separator {

  margin-top: px;

}

  

.twitter {
20
  color: #FFF;

  text-decoration: none;

  border-radius: 4px;

  background: #00ACED;

  display: inline-block;
25
  padding: 10px 8px;

  margin-bottom: 15px;

  font-weight: bold;

}

​

/* 3D Cube */

.space3d {

  perspective: 1000px;
33
  width: $cubeWidth;

  height: $cubeHeight;

  text-align: center;

  display: inline-block;

}

​

._3dbox {
40
  display: inline-block;

  transition: all 0.85s cubic-bezier(0.175,0.885,0.320,1.275);

​

  text-align: center;

  position: relative;

  width: 100%;

  height: 100%;

  transform-style: preserve-3d;

  transform: rotateX(-15deg) rotateY(15deg);

}

​

._3dface {

  overflow: hidden;

  position: absolute;

  

  border: 1px solid #888;

  background: #FFF;

  box-shadow: inset 0 0 60px rgba(0, 0, 0, 0.1),
/* Add your CSS code here.

​

For example:

.example {

    color: red;

}

​

For brushing up on your CSS knowledge, check out http://www.w3schools.com/css/css_syntax.asp

​

End of comment */ 

​

​
import React, { useState, useRef } from 'react';
import { Dialog, DialogActions, DialogContent, Typography, styled, Button, Slider, withStyles } from '@material-ui/core';
import Cropper from 'react-cropper';
import 'cropperjs/dist/cropper.css';

const Input = () => {
  const [open, setOpen] = useState(true);
  const cropperRef = useRef(null);
  const [croppedImage, setCroppedImage] = useState(null);
  const [cropBoxSize, setCropBoxSize] = useState(200); 
  const [zoomLevel, setZoomLevel] = useState(1); 

  const handleCrop = () => {
    const cropper = cropperRef.current.cropper;
    setCroppedImage(cropper.getCroppedCanvas({
      width: cropBoxSize,
      height: cropBoxSize,
    }).toDataURL());
  };

  const handleApply = () => {
    handleCrop();
    setOpen(false);
  };

  const handleCancel = () => {
    setOpen(false);
  };

  const handleZoomChange = (event, newValue) => {
    const cropper = cropperRef.current.cropper;
    setZoomLevel(newValue);
    cropper.zoomTo(newValue);
  };

  return (
    <div>
      <ProfileDialog open={open}>
        <ProfileTitle>Adjust position of photo</ProfileTitle>
        <DialogContent style={{ padding: '0px',background:'#eeeeee' }}>
          <CropperWrapper>
            <Cropper
              src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSzP-Y9jQiwYJRI8DqrnqxdI9UzLtkcYC9SRw&s"
              initialAspectRatio={1} // Set aspect ratio to 1 for a square crop box
              guides={true}
              ref={cropperRef}
              viewMode={1}
              dragMode="move"
              movable={true}
              zoomable={true}
              style={{ height: '100%', width: '100%'}}
              cropBoxResizable={false}
              cropBoxMovable={false}
              background={false}
              ready={() => {
                const cropper = cropperRef.current.cropper;
                const initialZoomLevel = cropper.getData().scaleX;
                setZoomLevel(initialZoomLevel);
                cropper.setCropBoxData({
                  width: cropBoxSize,
                  height: cropBoxSize,
                  left: (cropper.getContainerData().width - cropBoxSize) / 2,
                  top: (cropper.getContainerData().height - cropBoxSize) / 2,
                });
              }}
              cropend={() => {
                const cropper = cropperRef.current.cropper;
                cropper.cropBoxData = {
                  ...cropper.cropBoxData,
                  width: cropBoxSize,
                  height: cropBoxSize,
                };
                cropper.setCropBoxData(cropper.cropBoxData);
              }}
            />
            <div style={{ display: 'flex', justifyContent: "center", alignItems: 'center',background:'#eeeeee' }}>
              <div style={{ width: '40%' }}>
                <div style={{display:'flex',flexDirection:'row',justifyContent:'space-between'}}>
                  <p>Zoom</p>
                  <p>{zoomLevel}</p>
                </div>
                <PrettoSlider
                  style={{ zIndex: '999', marginTop: '-20px' }}
                  value={zoomLevel}
                  min={1}
                  max={3}
                  step={0.01}
                  onChange={handleZoomChange}
                  aria-labelledby="zoom-slider"
                  // valueLabelDisplay="auto"
                />
              </div>
            </div>
          </CropperWrapper>

        </DialogContent>
        <DialogActions style={{ justifyContent: 'center', alignItems: 'center' }}>
          <Button variant='outlined' onClick={handleApply}>Apply</Button>
          <Button variant='outlined' onClick={handleCancel}>Cancel</Button>
        </DialogActions>

      </ProfileDialog>
      {croppedImage && (
        <div>
          <Typography variant="h6">Cropped Image:</Typography>
          <img src={croppedImage} alt="Cropped" style={{ maxWidth: '100%' }} />
        </div>
      )}
    </div>
  );
};

export default Input;

const ProfileDialog = styled(Dialog)({
  '& .MuiPaper-rounded': {
    borderRadius: '10px',
    width: 'calc(45% - 100px)'
  }
});

const ProfileTitle = styled(Typography)({
  padding: '20px',
  fontWeight: 'bold',
  fontFamily: 'sans-serif'
});

const CropperWrapper = styled('div')({
  backgroundColor: '#ddd',
  position: 'relative',
  marginTop:'40px',
  // '& .cropper-view-box': {
  //   borderRadius: '50%', // Make crop box a circle
  // },
  // '& .cropper-face': {
  //   borderRadius: '50%', // Make crop box a circle
  //   clipPath: 'circle(50% at 50% 50%)', // Use clipPath to clip the content to a circle
  // },
  '& .cropper-modal': {
    backgroundColor: 'white'
  }
});
const PrettoSlider = withStyles({
  root: {
    color: '#374f81',
    height: 4,
  },
  thumb: {
    height: 12,
    width: 12,
    backgroundColor: '#fff',
    border: '4px solid currentColor',
    marginTop: -4,
    marginLeft: -6,
    '&:focus, &:hover, &$active': {
      boxShadow: 'inherit',
    },
  },
  active: {},
  valueLabel: {
    left: '-30px',
    '& *': {
      background: 'white',
      color: '#000',
      transform: 'none',
      width: '80px',
      borderRadius: '4px',
      textAlign: 'center'
    },
  },
  track: {
    height: 4,
    borderRadius: 2,
  },
  rail: {
    height: 4,
    borderRadius: 2,
    opacity: 1,
    backgroundColor: 'white',
  },
})(Slider);
import React, { useState } from "react";
import { Cropper } from "react-advanced-cropper";
import "react-advanced-cropper/dist/style.css";

const Example = () => {
  let image = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTV_NaGTKWnAwn8j_yuPFVSDBtV4xfBbo7uPw&s"

  return (
    <div className="example">
      <div className="example__cropper-wrapper">
        <Cropper className="example__cropper" src={image} />
      </div>
    </div>
  );
};
export default Example;
jonas schedman suggesions----
For checking good websites designs suggested by jonas schedman
1)https://land-book.com/
2)https://onepagelove.com/
3) https://www.awwwards.com/
4) https://www.appsignal.com/


Useful websites 
1) Base64decode.org 
2) caniuse.com to check browser features compatibility 
3) visualgo.net for learning DSA 
4) cs.usfca.edu for DSA 
5) https://latentflip.com/ - checking nodejs
6) https://explainshell.com/ -for CLI commands explanation 
7) latentflip.com - for js code execution visualization 
8) jsv9000.app - JS code execution visualization 
9) regexr.com regex practice and visualize
10) algomap.io learn algorithms 

Other websites
Bbox.com for getting lat long
Geojson.io for checking geojson
https://100dayscss.com 
React
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome against localhost",
      "url": "http://localhost:3000",
      "webRoot": "${workspaceFolder}",
      "skipFiles": [
        "${workspaceFolder}/node_modules/**/*.js",
        "${workspaceFolder}/node_modules/**/*.ts",
        "${workspaceFolder}/node_modules/**/*.jsx",
        "${workspaceFolder}/node_modules/**/*.tsx",
        "**/bundler.js"
      ]
    }
  ]
}
-------------------------------------------------
Node
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "skipFiles": [
        "<node_internals>/**",
        "${workspaceFolder}/node_modules/**/*.js",
        "${workspaceFolder}/node_modules/**/*.ts"
      ],
      "program": "${workspaceFolder}\\app.js",
      "restart": true,
      "runtimeExecutable": "nodemon",
      "console": "integratedTerminal",
      "sourceMaps": true, // I dunno what this does, 
      "smartStep": true  // can remove both of these
    }
  ]
}

Sub CreateCalendar()
   'Define your variables
   Dim wks As Worksheet
   Dim var As Variant
   Dim datDay As Date
   Dim iMonth As Integer, iCol As Integer, iCounter As Integer, iYear As Integer
   Dim sMonth As String
   Dim bln As Boolean
   
   'In the current application, turn off screen updating, save the current state of the status bar,
   'and then turn on the status bar.
   With Application
      .ScreenUpdating = False
      bln = .DisplayStatusBar
      .DisplayStatusBar = True
   End With
   
   'Initialize iYear with the value entered in the first spin button on the worksheet.
   iYear = Cover.SpinButton1.Value
   
   'Create a new workbook to hold your new calendar.
   Workbooks.Add
   
   'In this new workbook, clear out all the worksheets except for one.
   Application.DisplayAlerts = False
   For iCounter = 1 To Worksheets.Count - 1
      Worksheets(2).Delete
   Next iCounter
   Application.DisplayAlerts = True
   
   
   Set wks = ThisWorkbook.Worksheets("Employee")
   
   'For each month of the year
   For iMonth = 1 To 12
      'Create a new worksheet and label the worksheet tab with the name of the new month
      sMonth = Format(DateSerial(1, iMonth, 1), "mmmm")
      Application.StatusBar = "Place month " & sMonth & " on..."
      Worksheets.Add after:=Worksheets(Worksheets.Count)
      ActiveSheet.Name = sMonth
      
      'Copy the employee names to the first column, and add the dates across the remaining columns.
      wks.Range(wks.Cells(3, 1), wks.Cells( _
         WorksheetFunction.CountA(wks.Columns(1)) + 1, 1)).Copy Range("A2")
      Range("A1").Value = "'" & ActiveSheet.Name & " " & iYear
      
      'Call the private subs, depending on what options are chosen for the calendar.
      
      'With weekends and holidays
      If Cover.OptionButton1.Value And Cover.OptionButton3.Value Then
         Call WithHW(iMonth)
      'With weekends, but without holidays
      ElseIf Cover.OptionButton1.Value And Cover.OptionButton3.Value = False Then
         Call WithWsansH(iMonth)
      'With holidays, but without weekends
      ElseIf Cover.OptionButton1.Value = False And Cover.OptionButton3.Value Then
         Call WithHsansW(iMonth)
      'Without weekends or holidays.
      Else
         Call SansWH(iMonth)
      End If
      
      'Apply some formatting.
      Rows(2).Value = Rows(1).Value
      Rows(2).NumberFormat = "ddd"
      Range("A2").Value = "Weekdays"
      Rows("1:2").Font.Bold = True
      Columns.AutoFit
   Next iMonth
   
   'Delete the first worksheet, because there was not anything in it.
   Application.DisplayAlerts = False
   Worksheets(1).Delete
   Application.DisplayAlerts = True
   
   'Label the window.
   Worksheets(1).Select
   ActiveWindow.Caption = "Yearly calendar " & iYear
   
   'Do some final cleanup, and then close out the sub.
   With Application
      .ScreenUpdating = True
      .DisplayStatusBar = bln
      .StatusBar = False
   End With
End Sub


'Name: WithWH (with weekends and holidays)
'Description: Creates a calendar for the specified month, including both weekends and holidays.
Private Sub WithHW(ByVal iMonth As Integer)
   'Define your variables.
   Dim cmt As Comment
   Dim rng As Range
   Dim var As Variant
   Dim datDay As Date
   Dim iYear As Integer, iCol As Integer
   iCol = 1
   iYear = Cover.SpinButton1.Value
   
   'Go through every day of the month and put the date on the calendar in the first row.
   For datDay = DateSerial(iYear, iMonth, 1) To DateSerial(iYear, iMonth + 1, 0)
      iCol = iCol + 1
      Set rng = Range(Cells(1, iCol), Cells(WorksheetFunction.CountA(Columns(1)), iCol))
      
      'Determine if the day is a holiday.
      var = Application.Match(CDbl(datDay), ThisWorkbook.Worksheets("Holidays").Columns(1), 0)
      Cells(1, iCol).Value = datDay
      
      'Add the appropriate formatting that indicates a holiday or weekend.
      With rng.Interior
         Select Case Weekday(datDay)
            Case 1
               .ColorIndex = 35
            Case 7
               .ColorIndex = 36
         End Select
         If Not IsError(var) Then
            .ColorIndex = 34
            Set cmt = Cells(1, iCol).AddComment( _
               ThisWorkbook.Worksheets("Holidays").Cells(var, 2).Value)
            cmt.Shape.TextFrame.AutoSize = True
         End If
      End With
   Next datDay
End Sub


'Name: WithHsansW (with holidays, without weekends)
'Description: Creates a calendar for the specified month, including holidays, but not weekends.
Private Sub WithHsansW(ByVal iMonth As Integer)
   'Declare your variables.
   Dim datDay As Date
   Dim iYear As Integer, iCol As Integer
   iCol = 1
   iYear = Cover.SpinButton1.Value
   
   'For every day in the month, determine if the day is a weekend.
   For datDay = DateSerial(iYear, iMonth, 1) To DateSerial(iYear, iMonth + 1, 0)
      
      'If the day is not a weekend, put it on the calendar.
      If WorksheetFunction.Weekday(datDay, 2) < 6 Then
         iCol = iCol + 1
         Cells(1, iCol).Value = datDay
      End If
   Next datDay
End Sub


'Name: WithWsansH (with weekends, without holidays)
'Description: Creates a calendar for the specified month, including weekends, but not holidays.
Private Sub WithWsansH(ByVal iMonth As Integer)
   'Declare your variables.
   Dim var As Variant
   Dim datDay As Date
   Dim iYear As Integer, iCol As Integer
   iCol = 1
   iYear = Cover.SpinButton1.Value
   
   'For every day in the month, determine if the day is a holiday.
   For datDay = DateSerial(iYear, iMonth, 1) To DateSerial(iYear, iMonth + 1, 0)
      var = Application.Match(CDbl(datDay), ThisWorkbook.Worksheets("Holidays").Columns(1), 0)
      
      'If the day is not a holiday, put it on the calendar.
      If IsError(var) Then
         iCol = iCol + 1
         Cells(1, iCol).Value = datDay
      End If
   Next datDay
End Sub


'Name: SansWH (without weekends or holidays)
'Description: Creates a calendar for the specified month, not including weekends or holidays.
Private Sub SansWH(ByVal iMonth As Integer)
   'Set up your variables
   Dim var As Variant
   Dim datDay As Date
   Dim iYear As Integer, iCol As Integer
   iCol = 1
   iYear = Cover.SpinButton1.Value
   
   'For every day in the month, determine if the day is a weekend or a holiday.
   For datDay = DateSerial(iYear, iMonth, 1) To DateSerial(iYear, iMonth + 1, 0)
      If WorksheetFunction.Weekday(datDay, 2) < 6 Then
         var = Application.Match(CDbl(datDay), ThisWorkbook.Worksheets("Holidays").Columns(1), 0)
         
         'If the day is not a weekend or a holiday, put it on the calendar.
         If IsError(var) Then
            iCol = iCol + 1
            Cells(1, iCol).Value = datDay
         End If
      End If
   Next datDay
End Sub
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;
    }
  }
}
//controller
using av_motion_api.Data;
using av_motion_api.Models;
using av_motion_api.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace av_motion_api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RewardController : ControllerBase
    {
        private readonly AppDbContext _appDbContext;

        public RewardController(AppDbContext appDbContext)
        {
            _appDbContext = appDbContext;
        }

        [HttpGet]
        [Route("getAllRewardTypes")]
        public async Task<IActionResult> GetAllRewardTypes()
        {
            try
            {
                var rewardTypes = await _appDbContext.Reward_Types.ToListAsync();
                return Ok(rewardTypes);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        [HttpGet]
        [Route("getRewardTypeById/{id}")]
        public async Task<IActionResult> GetRewardTypeById(int id)
        {
            try
            {
                var rewardType = await _appDbContext.Reward_Types.FindAsync(id);

                if (rewardType == null)
                {
                    return NotFound();
                }

                return Ok(rewardType);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        [HttpPost]
        [Route("createRewardType")]
        public async Task<IActionResult> CreateRewardType(RewardTypeViewModel rt)
        {
            try
            {
                var existingRewardType = await _appDbContext.Reward_Types
                    .FirstOrDefaultAsync(r => r.Reward_Type_Name == rt.Reward_Type_Name);

                if (existingRewardType != null)
                {
                    return Conflict(new { message = "Reward type already exists." });
                }


                var rewardType = new Reward_Type
                {
                    Reward_Type_Name = rt.Reward_Type_Name,
                    Reward_Criteria = rt.Reward_Criteria
                    
                };
                _appDbContext.Reward_Types.Add(rewardType);
                await _appDbContext.SaveChangesAsync();

                return CreatedAtAction(nameof(GetRewardTypeById), new { id = rewardType.Reward_Type_ID }, rewardType);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        [HttpPut]
        [Route("updateRewardType/{id}")]
        public async Task<IActionResult> UpdateRewardType(int id, [FromBody] RewardTypeViewModel rt)
        {
            try
            {
                var rewardType = await _appDbContext.Reward_Types.FindAsync(id);

                if(rewardType == null)
                {
                    return NotFound();
                }

                var existingRewardType = await _appDbContext.Reward_Types
                    .FirstOrDefaultAsync(r => r.Reward_Type_Name == rt.Reward_Type_Name && r.Reward_Type_ID != id);

                if (existingRewardType != null)
                {
                    return Conflict(new { message = "Reward type already exists." });
                }

                rewardType.Reward_Type_Name = rt.Reward_Type_Name;
                rewardType.Reward_Criteria = rt.Reward_Criteria;

                _appDbContext.Entry(rewardType).State = EntityState.Modified;
                await _appDbContext.SaveChangesAsync();

                return NoContent();
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        [HttpDelete]
        [Route("deleteRewardType/{id}")]
        public async Task<IActionResult> DeleteRewardType(int id)
        {
            try
            {
                var rewardType = await _appDbContext.Reward_Types.FindAsync(id);

                if(rewardType == null)
                {
                    return NotFound();
                }

                _appDbContext.Reward_Types.Remove(rewardType);
                await _appDbContext.SaveChangesAsync();

                return NoContent();
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }



        [HttpGet]
        [Route("getRewardById/{id}")]
        public async Task<IActionResult> GetRewardById(int id)
        {
            try
            {
                var reward = await _appDbContext.Rewards.FindAsync(id);

                if (reward == null)
                {
                    return NotFound();
                }

                return Ok(reward);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        [HttpGet]
        [Route("getAllRewards")]
        public async Task<IActionResult> GetAllRewards()
        {
            try
            {
                var rewards = await _appDbContext.Rewards
                                         .Join(_appDbContext.Reward_Types,
                                               reward => reward.Reward_Type_ID,
                                               rewardType => rewardType.Reward_Type_ID,
                                               (reward, rewardType) => new RewardViewModel
                                               {
                                                   Reward_ID = reward.Reward_ID,
                                                   Reward_Issue_Date = reward.Reward_Issue_Date,
                                                   Reward_Type_Name = rewardType.Reward_Type_Name,
                                                   IsPosted = reward.IsPosted
                                               })
                                         .ToListAsync();
                return Ok(rewards);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

        [HttpGet]
        [Route("UnredeemedRewards/{memberId}")]
        public async Task<IActionResult> UnredeemedRewards(int memberId)
        {
            try
            {
                var rewards = await _appDbContext.Reward_Members
                    .Where(r => r.Member_ID == memberId && !r.IsRedeemed)
                    .Select(rm => new
                    {
                        rm.Reward_ID,
                        rm.IsRedeemed,
                        RewardTypeName = rm.Reward.Reward_Type.Reward_Type_Name,
                        RewardCriteria = rm.Reward.Reward_Type.Reward_Criteria,
                        RewardIssueDate = rm.Reward.Reward_Issue_Date
                    })
                    .ToListAsync();

                return Ok(rewards);
            }
            catch (Exception ex)
            {
                return BadRequest($"An error occurred: {ex.Message}");
            }
        }

        [HttpPost]
        [Route("redeemReward")]
        public async Task<IActionResult> RedeemReward([FromBody] RewardRedeemViewModel request)
        {
            try
            {
                // Fetch the reward by ID
                var reward = await _appDbContext.Reward_Members
                                                .FirstOrDefaultAsync(r => r.Reward_ID == request.RewardId && r.Member_ID == request.MemberId);

                if (reward == null)
                {
                    return NotFound("Reward not found or not eligible for the member.");
                }

                // Check if the reward is already redeemed
                if (reward.IsRedeemed)
                {
                    return BadRequest("Reward is already redeemed.");
                }

                // Mark the reward as redeemed
                reward.IsRedeemed = true;
                _appDbContext.Entry(reward).State = EntityState.Modified;
                await _appDbContext.SaveChangesAsync();

                return Ok(new { Status = "Success", Message = "Reward redeemed successfully!" });
            }
            catch (Exception)
            {
                return BadRequest("An error occurred while redeeming the reward.");
            }
        }

        [HttpPost]
        [Route("setReward")]
        public async Task<IActionResult> SetReward(RewardSetViewModel r)
        {
            try
            {
                var reward = new Reward
                {
                    Reward_Issue_Date = r.Reward_Issue_Date,
                    Reward_Type_ID = r.Reward_Type_ID,
                    IsPosted = r.IsPosted
                };
                _appDbContext.Rewards.Add(reward);
                await _appDbContext.SaveChangesAsync();

                return CreatedAtAction(nameof(GetRewardById), new { id = reward.Reward_ID }, reward);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }


        [HttpPost]
        [Route("postReward")]
        public async Task<IActionResult> PostReward([FromBody] RewardPostViewModel request)
        {
            try
            {
                // Fetch the reward by ID
                var reward = await _appDbContext.Rewards
                                                .FirstOrDefaultAsync(r => r.Reward_ID == request.RewardId);

                if (reward == null)
                {
                    return NotFound("Reward not found.");
                }

                // Check if the reward is already posted
                if (reward.IsPosted)
                {
                    return BadRequest("Reward is already posted.");
                }

                // Mark the reward as posted
                reward.IsPosted = true;
                _appDbContext.Entry(reward).State = EntityState.Modified;
                await _appDbContext.SaveChangesAsync();

                // Fetch members who qualify for this reward based on the criteria
                var rewardType = await _appDbContext.Reward_Types.FindAsync(reward.Reward_Type_ID);
                var qualifyingMembers = await GetQualifyingMembers(rewardType.Reward_Criteria);

                // Add qualifying members to the Reward_Member table
                foreach (var member in qualifyingMembers)
                {
                    var rewardMember = new Reward_Member
                    {
                        Member_ID = member.Member_ID,
                        Reward_ID = reward.Reward_ID,
                        IsRedeemed = false
                    };
                    _appDbContext.Reward_Members.Add(rewardMember);
                }
                await _appDbContext.SaveChangesAsync();

                return Ok(new { Status = "Success", Message = "Reward posted successfully!" });
            }
            catch (Exception)
            {
                return BadRequest("An error occurred while posting the reward.");
            }
        }

        //Predined Reward Types Methods
        private async Task<List<Member>> GetQualifyingMembers(string criteria)
        {
            var qualifyingMembers = new List<Member>();

            if (criteria == "Placed a Booking")
            {
                qualifyingMembers = await GetMembersWithAtLeastOneBooking();
            }
            else if (criteria == "Completed 10 Bookings in a Month")
            {
                qualifyingMembers = await GetMembersWithBookingsInMonth(10);
            }
            else if (criteria == "Made 20 Bookings in Last 3 Months")
            {
                qualifyingMembers = await GetFrequentBookers(20, 3);
            }
            else if (criteria == "Member for Over a Year")
            {
                qualifyingMembers = await GetLoyalMembers();
            }

            return qualifyingMembers;
        }

        private async Task<List<Member>> GetMembersWithAtLeastOneBooking()
        {
            var qualifyingMembers = await _appDbContext.Members
                .Where(m => _appDbContext.Bookings
                    .Any(b => b.Member_ID == m.Member_ID))
                .ToListAsync();

            return qualifyingMembers;
        }


        private async Task<List<Member>> GetMembersWithBookingsInMonth(int bookingCount)
        {
            var oneMonthAgo = DateTime.Now.AddMonths(-1);
            var qualifyingMembers = await _appDbContext.Members
                .Where(m => _appDbContext.Bookings
                    .Where(b => b.Member_ID == m.Member_ID)
                    .Join(_appDbContext.Booking_Time_Slots,
                          b => b.Booking_ID,
                          bts => bts.Booking_ID,
                          (b, bts) => bts.Time_Slot_ID)
                    .Join(_appDbContext.Time_Slots,
                          btsId => btsId,
                          ts => ts.Time_Slot_ID,
                          (btsId, ts) => ts)
                    .Count(ts => ts.Slot_Date >= oneMonthAgo) >= bookingCount)
                .ToListAsync();

            return qualifyingMembers;
        }

        private async Task<List<Member>> GetLoyalMembers()
        {
            var oneYearAgo = DateTime.Now.AddYears(-1);
            var qualifyingMembers = await _appDbContext.Members
                .Join(_appDbContext.Contracts,
                      m => m.Contract_ID,
                      c => c.Contract_ID,
                      (m, c) => new { Member = m, Contract = c })
                .Where(mc => mc.Contract.Subscription_Date <= oneYearAgo)
                .Select(mc => mc.Member)
                .ToListAsync();

            return qualifyingMembers;
        }


        private async Task<List<Member>> GetFrequentBookers(int bookingCount, int months)
        {
            var dateLimit = DateTime.Now.AddMonths(-months);
            var qualifyingMembers = await _appDbContext.Members
                .Where(m => _appDbContext.Bookings
                    .Where(b => b.Member_ID == m.Member_ID)
                    .Join(_appDbContext.Booking_Time_Slots,
                          b => b.Booking_ID,
                          bts => bts.Booking_ID,
                          (b, bts) => bts.Time_Slot_ID)
                    .Join(_appDbContext.Time_Slots,
                          btsId => btsId,
                          ts => ts.Time_Slot_ID,
                          (btsId, ts) => ts)
                    .Count(ts => ts.Slot_Date >= dateLimit) >= bookingCount)
                .ToListAsync();

            return qualifyingMembers;
        }
    }
}

//RewardPostViewModel
namespace av_motion_api.ViewModels
{
    public class RewardPostViewModel
    {
        public int RewardId { get; set; }
    }
}
Dim mainWorkBook As Workbook
Dim arrMatrix(1 To 9, 1 To 3, 1 To 3)
Dim arrOptions(9)
Dim arrAlreadyUpdated()
Dim blnHaveSomethingToFill

Sub Sumit()
Set mainWorkBook = ActiveWorkbook
Call FnGetValues

blnHaveSomethingToFill = False
For i = 1 To 9
StrA = ""
'intAUCounter = 0
'ReDim Preserve arrAlreadyUpdated(0)
For j = 1 To 3
For k = 1 To 3
'MsgBox i & " " & j & "      " & arrMatrix(i, j)
If arrMatrix(i, j, k) = "" Then

Call FnFillOptionsArray
Call FnCalculate(i, j, k)
intCounterO = 0
'StrA = ""
For p = 0 To 8
StrA = StrA & "  " & arrOptions(p)
If arrOptions(p) = 0 Then
intCounterO = intCounterO + 1
End If
Next
If i = 4 Then
'MsgBox i & j & k & "     " & StrA
End If

'intAUCounter = intAUCounter + 1
'ReDim Preserve arrAlreadyUpdated(intAUCounter)
'arrAlreadyUpdated(intAUCounter - 1) = i & " " & j & " " & k
'MsgBox arrAlreadyUpdated(intAUCounter - 1) & " Entered"

If intCounterO = 8 Then
'intAUCounter = 0
For p = 0 To 8
If arrOptions(p) <> 0 Then
arrMatrix(i, j, k) = arrOptions(p)
'MsgBox "have"
blnHaveSomethingToFill = True
End If
Next
End If
End If
Next
Next
If blnHaveSomethingToFill = False Then
For a = 1 To 9
StrA = Replace(StrA, " ", "")
strTemp = StrA
If Len(strTemp) - Len(Replace(strTemp, CStr(a), "")) = 1 Then
' MsgBox StrA
intLocation = InStr(1, StrA, CStr(a), 1)
' MsgBox intLocation
intCell = 0
If Int(intLocation / 9) <> (intLocation / 9) Then
intCell = Int(intLocation / 9) + 1
Else
intCell = Int(intLocation / 9)
End If
' MsgBox intCell & " Location"
'arrTemp = Split(arrAlreadyUpdated(intCell - 1), " ")
'intI = CInt(arrTemp(0))
'intJ = CInt(arrTemp(1))
'intK = CInt(arrTemp(2))
' MsgBox intI & intJ & intK
intC = 0
blnFound = False
For j = 1 To 3
For k = 1 To 3
'MsgBox i & " " & j & "      " & arrMatrix(i, j)
If arrMatrix(i, j, k) = "" Then
''MsgBox "411" & arrMatrix(4, 1, 1)
intC = intC + 1
'MsgBox "intC" & intC
'MsgBox i & j & k
If intC = intCell Then
arrMatrix(i, j, k) = a
'Call FnFillValues
' MsgBox i & j & k & "Matched" & "   " & a
blnFound = True
Exit For
End If
End If
Next
If blnFound Then
Exit For
End If
Next
Exit For
StrA = ""
strTemp = ""
End If
Next

End If
Next

ReDim Preserve arrAlreadyUpdated(0)

Call FnFillValues

End Sub

Function FnFillOptionsArray()

arrOptions(0) = 1
arrOptions(1) = 2
arrOptions(2) = 3
arrOptions(3) = 4
arrOptions(4) = 5
arrOptions(5) = 6
arrOptions(6) = 7
arrOptions(7) = 8
arrOptions(8) = 9

End Function

Function FnCalculate(a, b, c)

For j = 1 To 3
For k = 1 To 3
If arrMatrix(a, j, k) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(a, j, k) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next

If a = 1 Then
For j = 1 To 3
For k = 1 To 3
If arrMatrix(j, k, c) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, k, c) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
For j = 1 To 7 Step 3
For k = 1 To 3
If arrMatrix(j, b, k) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, b, k) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
End If

If a = 2 Then
For j = 1 To 3
For k = 1 To 3
If arrMatrix(j, k, c) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, k, c) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
For j = 2 To 8 Step 3
For k = 1 To 3
If arrMatrix(j, b, k) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, b, k) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
End If

If a = 3 Then
For j = 1 To 3
For k = 1 To 3
If arrMatrix(j, k, c) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, k, c) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
For j = 3 To 9 Step 3
For k = 1 To 3
If arrMatrix(j, b, k) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, b, k) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
End If

If a = 4 Then
For j = 4 To 6
For k = 1 To 3
If arrMatrix(j, k, c) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, k, c) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
For j = 1 To 7 Step 3
For k = 1 To 3
If arrMatrix(j, b, k) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, b, k) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
End If

If a = 5 Then
For j = 4 To 6
For k = 1 To 3
If arrMatrix(j, k, c) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, k, c) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
For j = 2 To 8 Step 3
For k = 1 To 3
If arrMatrix(j, b, k) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, b, k) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
End If

If a = 6 Then
For j = 4 To 6
For k = 1 To 3
If arrMatrix(j, k, c) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, k, c) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
For j = 3 To 9 Step 3
For k = 1 To 3
If arrMatrix(j, b, k) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, b, k) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
End If

If a = 7 Then
For j = 7 To 9
For k = 1 To 3
If arrMatrix(j, k, c) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, k, c) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
For j = 1 To 7 Step 3
For k = 1 To 3
If arrMatrix(j, b, k) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, b, k) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
End If

If a = 8 Then
For j = 7 To 9
For k = 1 To 3
If arrMatrix(j, k, c) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, k, c) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
For j = 2 To 8 Step 3
For k = 1 To 3
If arrMatrix(j, b, k) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, b, k) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
End If

If a = 9 Then
For j = 7 To 9
For k = 1 To 3
If arrMatrix(j, k, c) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, k, c) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
For j = 3 To 9 Step 3
For k = 1 To 3
If arrMatrix(j, b, k) <> "" Then
For m = 0 To 8
If arrOptions(m) = arrMatrix(j, b, k) Then
arrOptions(m) = 0
End If
Next
End If
Next
Next
End If

End Function

Function FnGetValues()
'intChar = 69
'j = 1
'Set mainWorkBook = ActiveWorkbook
'For k = 1 To 9
'   For m = 69 To 77
'      For k = 1 To 3
'          For i = 1 To 3
'             arrMatrix(k, i, j) = mainWorkBook.Sheets("Sheet1").Range(Chr(m) & i + 4).Value
'        Next
'       j = j + 1
'  Next
'Next
'Next

arrMatrix(1, 1, 1) = mainWorkBook.Sheets("Sheet1").Range("E5").Value
arrMatrix(1, 2, 1) = mainWorkBook.Sheets("Sheet1").Range("E6").Value
arrMatrix(1, 3, 1) = mainWorkBook.Sheets("Sheet1").Range("E7").Value
arrMatrix(2, 1, 1) = mainWorkBook.Sheets("Sheet1").Range("E8").Value
arrMatrix(2, 2, 1) = mainWorkBook.Sheets("Sheet1").Range("E9").Value
arrMatrix(2, 3, 1) = mainWorkBook.Sheets("Sheet1").Range("E10").Value
arrMatrix(3, 1, 1) = mainWorkBook.Sheets("Sheet1").Range("E11").Value
arrMatrix(3, 2, 1) = mainWorkBook.Sheets("Sheet1").Range("E12").Value
arrMatrix(3, 3, 1) = mainWorkBook.Sheets("Sheet1").Range("E13").Value

arrMatrix(1, 1, 2) = mainWorkBook.Sheets("Sheet1").Range("F5").Value
arrMatrix(1, 2, 2) = mainWorkBook.Sheets("Sheet1").Range("F6").Value
arrMatrix(1, 3, 2) = mainWorkBook.Sheets("Sheet1").Range("F7").Value
arrMatrix(2, 1, 2) = mainWorkBook.Sheets("Sheet1").Range("F8").Value
arrMatrix(2, 2, 2) = mainWorkBook.Sheets("Sheet1").Range("F9").Value
arrMatrix(2, 3, 2) = mainWorkBook.Sheets("Sheet1").Range("F10").Value
arrMatrix(3, 1, 2) = mainWorkBook.Sheets("Sheet1").Range("F11").Value
arrMatrix(3, 2, 2) = mainWorkBook.Sheets("Sheet1").Range("F12").Value
arrMatrix(3, 3, 2) = mainWorkBook.Sheets("Sheet1").Range("F13").Value

arrMatrix(1, 1, 3) = mainWorkBook.Sheets("Sheet1").Range("G5").Value
arrMatrix(1, 2, 3) = mainWorkBook.Sheets("Sheet1").Range("G6").Value
arrMatrix(1, 3, 3) = mainWorkBook.Sheets("Sheet1").Range("G7").Value
arrMatrix(2, 1, 3) = mainWorkBook.Sheets("Sheet1").Range("G8").Value
arrMatrix(2, 2, 3) = mainWorkBook.Sheets("Sheet1").Range("G9").Value
arrMatrix(2, 3, 3) = mainWorkBook.Sheets("Sheet1").Range("G10").Value
arrMatrix(3, 1, 3) = mainWorkBook.Sheets("Sheet1").Range("G11").Value
arrMatrix(3, 2, 3) = mainWorkBook.Sheets("Sheet1").Range("G12").Value
arrMatrix(3, 3, 3) = mainWorkBook.Sheets("Sheet1").Range("G13").Value

arrMatrix(4, 1, 1) = mainWorkBook.Sheets("Sheet1").Range("H5").Value
arrMatrix(4, 2, 1) = mainWorkBook.Sheets("Sheet1").Range("H6").Value
arrMatrix(4, 3, 1) = mainWorkBook.Sheets("Sheet1").Range("H7").Value
arrMatrix(5, 1, 1) = mainWorkBook.Sheets("Sheet1").Range("H8").Value
arrMatrix(5, 2, 1) = mainWorkBook.Sheets("Sheet1").Range("H9").Value
arrMatrix(5, 3, 1) = mainWorkBook.Sheets("Sheet1").Range("H10").Value
arrMatrix(6, 1, 1) = mainWorkBook.Sheets("Sheet1").Range("H11").Value
arrMatrix(6, 2, 1) = mainWorkBook.Sheets("Sheet1").Range("H12").Value
arrMatrix(6, 3, 1) = mainWorkBook.Sheets("Sheet1").Range("H13").Value

arrMatrix(4, 1, 2) = mainWorkBook.Sheets("Sheet1").Range("I5").Value
arrMatrix(4, 2, 2) = mainWorkBook.Sheets("Sheet1").Range("I6").Value
arrMatrix(4, 3, 2) = mainWorkBook.Sheets("Sheet1").Range("I7").Value
arrMatrix(5, 1, 2) = mainWorkBook.Sheets("Sheet1").Range("I8").Value
arrMatrix(5, 2, 2) = mainWorkBook.Sheets("Sheet1").Range("I9").Value
arrMatrix(5, 3, 2) = mainWorkBook.Sheets("Sheet1").Range("I10").Value
arrMatrix(6, 1, 2) = mainWorkBook.Sheets("Sheet1").Range("I11").Value
arrMatrix(6, 2, 2) = mainWorkBook.Sheets("Sheet1").Range("I12").Value
arrMatrix(6, 3, 2) = mainWorkBook.Sheets("Sheet1").Range("I13").Value

arrMatrix(4, 1, 3) = mainWorkBook.Sheets("Sheet1").Range("J5").Value
arrMatrix(4, 2, 3) = mainWorkBook.Sheets("Sheet1").Range("J6").Value
arrMatrix(4, 3, 3) = mainWorkBook.Sheets("Sheet1").Range("J7").Value
arrMatrix(5, 1, 3) = mainWorkBook.Sheets("Sheet1").Range("J8").Value
arrMatrix(5, 2, 3) = mainWorkBook.Sheets("Sheet1").Range("J9").Value
arrMatrix(5, 3, 3) = mainWorkBook.Sheets("Sheet1").Range("J10").Value
arrMatrix(6, 1, 3) = mainWorkBook.Sheets("Sheet1").Range("J11").Value
arrMatrix(6, 2, 3) = mainWorkBook.Sheets("Sheet1").Range("J12").Value
arrMatrix(6, 3, 3) = mainWorkBook.Sheets("Sheet1").Range("J13").Value

arrMatrix(7, 1, 1) = mainWorkBook.Sheets("Sheet1").Range("K5").Value
arrMatrix(7, 2, 1) = mainWorkBook.Sheets("Sheet1").Range("K6").Value
arrMatrix(7, 3, 1) = mainWorkBook.Sheets("Sheet1").Range("K7").Value
arrMatrix(8, 1, 1) = mainWorkBook.Sheets("Sheet1").Range("K8").Value
arrMatrix(8, 2, 1) = mainWorkBook.Sheets("Sheet1").Range("K9").Value
arrMatrix(8, 3, 1) = mainWorkBook.Sheets("Sheet1").Range("K10").Value
arrMatrix(9, 1, 1) = mainWorkBook.Sheets("Sheet1").Range("K11").Value
arrMatrix(9, 2, 1) = mainWorkBook.Sheets("Sheet1").Range("K12").Value
arrMatrix(9, 3, 1) = mainWorkBook.Sheets("Sheet1").Range("K13").Value

arrMatrix(7, 1, 2) = mainWorkBook.Sheets("Sheet1").Range("L5").Value
arrMatrix(7, 2, 2) = mainWorkBook.Sheets("Sheet1").Range("L6").Value
arrMatrix(7, 3, 2) = mainWorkBook.Sheets("Sheet1").Range("L7").Value
arrMatrix(8, 1, 2) = mainWorkBook.Sheets("Sheet1").Range("L8").Value
arrMatrix(8, 2, 2) = mainWorkBook.Sheets("Sheet1").Range("L9").Value
arrMatrix(8, 3, 2) = mainWorkBook.Sheets("Sheet1").Range("L10").Value
arrMatrix(9, 1, 2) = mainWorkBook.Sheets("Sheet1").Range("L11").Value
arrMatrix(9, 2, 2) = mainWorkBook.Sheets("Sheet1").Range("L12").Value
arrMatrix(9, 3, 2) = mainWorkBook.Sheets("Sheet1").Range("L13").Value

arrMatrix(7, 1, 3) = mainWorkBook.Sheets("Sheet1").Range("M5").Value
arrMatrix(7, 2, 3) = mainWorkBook.Sheets("Sheet1").Range("M6").Value
arrMatrix(7, 3, 3) = mainWorkBook.Sheets("Sheet1").Range("M7").Value
arrMatrix(8, 1, 3) = mainWorkBook.Sheets("Sheet1").Range("M8").Value
arrMatrix(8, 2, 3) = mainWorkBook.Sheets("Sheet1").Range("M9").Value
arrMatrix(8, 3, 3) = mainWorkBook.Sheets("Sheet1").Range("M10").Value
arrMatrix(9, 1, 3) = mainWorkBook.Sheets("Sheet1").Range("M11").Value
arrMatrix(9, 2, 3) = mainWorkBook.Sheets("Sheet1").Range("M12").Value
arrMatrix(9, 3, 3) = mainWorkBook.Sheets("Sheet1").Range("M13").Value

End Function

Function FnFillValues()
'intChar = 69
'j = 1
'Set mainWorkBook = ActiveWorkbook
'For k = 1 To 9
'   For m = 69 To 77
'      For k = 1 To 3
'          For i = 1 To 3
'             arrMatrix(k, i, j) = mainWorkBook.Sheets("Sheet1").Range(Chr(m) & i + 4).Value
'        Next
'       j = j + 1
'  Next
'Next
'Next

mainWorkBook.Sheets("Sheet1").Range("E5").Value = arrMatrix(1, 1, 1)
mainWorkBook.Sheets("Sheet1").Range("E6").Value = arrMatrix(1, 2, 1)
mainWorkBook.Sheets("Sheet1").Range("E7").Value = arrMatrix(1, 3, 1)
mainWorkBook.Sheets("Sheet1").Range("E8").Value = arrMatrix(2, 1, 1)
mainWorkBook.Sheets("Sheet1").Range("E9").Value = arrMatrix(2, 2, 1)
mainWorkBook.Sheets("Sheet1").Range("E10").Value = arrMatrix(2, 3, 1)
mainWorkBook.Sheets("Sheet1").Range("E11").Value = arrMatrix(3, 1, 1)
mainWorkBook.Sheets("Sheet1").Range("E12").Value = arrMatrix(3, 2, 1)
mainWorkBook.Sheets("Sheet1").Range("E13").Value = arrMatrix(3, 3, 1)

mainWorkBook.Sheets("Sheet1").Range("F5").Value = arrMatrix(1, 1, 2)
mainWorkBook.Sheets("Sheet1").Range("F6").Value = arrMatrix(1, 2, 2)
mainWorkBook.Sheets("Sheet1").Range("F7").Value = arrMatrix(1, 3, 2)
mainWorkBook.Sheets("Sheet1").Range("F8").Value = arrMatrix(2, 1, 2)
mainWorkBook.Sheets("Sheet1").Range("F9").Value = arrMatrix(2, 2, 2)
mainWorkBook.Sheets("Sheet1").Range("F10").Value = arrMatrix(2, 3, 2)
mainWorkBook.Sheets("Sheet1").Range("F11").Value = arrMatrix(3, 1, 2)
mainWorkBook.Sheets("Sheet1").Range("F12").Value = arrMatrix(3, 2, 2)
mainWorkBook.Sheets("Sheet1").Range("F13").Value = arrMatrix(3, 3, 2)

mainWorkBook.Sheets("Sheet1").Range("G5").Value = arrMatrix(1, 1, 3)
mainWorkBook.Sheets("Sheet1").Range("G6").Value = arrMatrix(1, 2, 3)
mainWorkBook.Sheets("Sheet1").Range("G7").Value = arrMatrix(1, 3, 3)
mainWorkBook.Sheets("Sheet1").Range("G8").Value = arrMatrix(2, 1, 3)
mainWorkBook.Sheets("Sheet1").Range("G9").Value = arrMatrix(2, 2, 3)
mainWorkBook.Sheets("Sheet1").Range("G10").Value = arrMatrix(2, 3, 3)
mainWorkBook.Sheets("Sheet1").Range("G11").Value = arrMatrix(3, 1, 3)
mainWorkBook.Sheets("Sheet1").Range("G12").Value = arrMatrix(3, 2, 3)
mainWorkBook.Sheets("Sheet1").Range("G13").Value = arrMatrix(3, 3, 3)

mainWorkBook.Sheets("Sheet1").Range("H5").Value = arrMatrix(4, 1, 1)
mainWorkBook.Sheets("Sheet1").Range("H6").Value = arrMatrix(4, 2, 1)
mainWorkBook.Sheets("Sheet1").Range("H7").Value = arrMatrix(4, 3, 1)
mainWorkBook.Sheets("Sheet1").Range("H8").Value = arrMatrix(5, 1, 1)
mainWorkBook.Sheets("Sheet1").Range("H9").Value = arrMatrix(5, 2, 1)
mainWorkBook.Sheets("Sheet1").Range("H10").Value = arrMatrix(5, 3, 1)
mainWorkBook.Sheets("Sheet1").Range("H11").Value = arrMatrix(6, 1, 1)
mainWorkBook.Sheets("Sheet1").Range("H12").Value = arrMatrix(6, 2, 1)
mainWorkBook.Sheets("Sheet1").Range("H13").Value = arrMatrix(6, 3, 1)

mainWorkBook.Sheets("Sheet1").Range("I5").Value = arrMatrix(4, 1, 2)
mainWorkBook.Sheets("Sheet1").Range("I6").Value = arrMatrix(4, 2, 2)
mainWorkBook.Sheets("Sheet1").Range("I7").Value = arrMatrix(4, 3, 2)
mainWorkBook.Sheets("Sheet1").Range("I8").Value = arrMatrix(5, 1, 2)
mainWorkBook.Sheets("Sheet1").Range("I9").Value = arrMatrix(5, 2, 2)
mainWorkBook.Sheets("Sheet1").Range("I10").Value = arrMatrix(5, 3, 2)
mainWorkBook.Sheets("Sheet1").Range("I11").Value = arrMatrix(6, 1, 2)
mainWorkBook.Sheets("Sheet1").Range("I12").Value = arrMatrix(6, 2, 2)
mainWorkBook.Sheets("Sheet1").Range("I13").Value = arrMatrix(6, 3, 2)

mainWorkBook.Sheets("Sheet1").Range("J5").Value = arrMatrix(4, 1, 3)
mainWorkBook.Sheets("Sheet1").Range("J6").Value = arrMatrix(4, 2, 3)
mainWorkBook.Sheets("Sheet1").Range("J7").Value = arrMatrix(4, 3, 3)
mainWorkBook.Sheets("Sheet1").Range("J8").Value = arrMatrix(5, 1, 3)
mainWorkBook.Sheets("Sheet1").Range("J9").Value = arrMatrix(5, 2, 3)
mainWorkBook.Sheets("Sheet1").Range("J10").Value = arrMatrix(5, 3, 3)
mainWorkBook.Sheets("Sheet1").Range("J11").Value = arrMatrix(6, 1, 3)
mainWorkBook.Sheets("Sheet1").Range("J12").Value = arrMatrix(6, 2, 3)
mainWorkBook.Sheets("Sheet1").Range("J13").Value = arrMatrix(6, 3, 3)

mainWorkBook.Sheets("Sheet1").Range("K5").Value = arrMatrix(7, 1, 1)
mainWorkBook.Sheets("Sheet1").Range("K6").Value = arrMatrix(7, 2, 1)
mainWorkBook.Sheets("Sheet1").Range("K7").Value = arrMatrix(7, 3, 1)
mainWorkBook.Sheets("Sheet1").Range("K8").Value = arrMatrix(8, 1, 1)
mainWorkBook.Sheets("Sheet1").Range("K9").Value = arrMatrix(8, 2, 1)
mainWorkBook.Sheets("Sheet1").Range("K10").Value = arrMatrix(8, 3, 1)
mainWorkBook.Sheets("Sheet1").Range("K11").Value = arrMatrix(9, 1, 1)
mainWorkBook.Sheets("Sheet1").Range("K12").Value = arrMatrix(9, 2, 1)
mainWorkBook.Sheets("Sheet1").Range("K13").Value = arrMatrix(9, 3, 1)

mainWorkBook.Sheets("Sheet1").Range("L5").Value = arrMatrix(7, 1, 2)
mainWorkBook.Sheets("Sheet1").Range("L6").Value = arrMatrix(7, 2, 2)
mainWorkBook.Sheets("Sheet1").Range("L7").Value = arrMatrix(7, 3, 2)
mainWorkBook.Sheets("Sheet1").Range("L8").Value = arrMatrix(8, 1, 2)
mainWorkBook.Sheets("Sheet1").Range("L9").Value = arrMatrix(8, 2, 2)
mainWorkBook.Sheets("Sheet1").Range("L10").Value = arrMatrix(8, 3, 2)
mainWorkBook.Sheets("Sheet1").Range("L11").Value = arrMatrix(9, 1, 2)
mainWorkBook.Sheets("Sheet1").Range("L12").Value = arrMatrix(9, 2, 2)
mainWorkBook.Sheets("Sheet1").Range("L13").Value = arrMatrix(9, 3, 2)

mainWorkBook.Sheets("Sheet1").Range("M5").Value = arrMatrix(7, 1, 3)
mainWorkBook.Sheets("Sheet1").Range("M6").Value = arrMatrix(7, 2, 3)
mainWorkBook.Sheets("Sheet1").Range("M7").Value = arrMatrix(7, 3, 3)
mainWorkBook.Sheets("Sheet1").Range("M8").Value = arrMatrix(8, 1, 3)
mainWorkBook.Sheets("Sheet1").Range("M9").Value = arrMatrix(8, 2, 3)
mainWorkBook.Sheets("Sheet1").Range("M10").Value = arrMatrix(8, 3, 3)
mainWorkBook.Sheets("Sheet1").Range("M11").Value = arrMatrix(9, 1, 3)
mainWorkBook.Sheets("Sheet1").Range("M12").Value = arrMatrix(9, 2, 3)
mainWorkBook.Sheets("Sheet1").Range("M13").Value = arrMatrix(9, 3, 3)

End Function

'// Replacing #N/A with 0 in Excel using Formula.
'   =IFERROR (expression, value-if-error)

=IFERROR(VLOOKUP(2,2,1,FALSE),"0") 
' - Display value if no error 
' - Display 0 if error

'//Replace #N/A with blank
=IFERROR(VLOOKUP(2,2,1,FALSE),"")
//Installations
npm install xlsx file-saver
npm install xlsx file-saver

//payment component
//ts
import { Component } from '@angular/core';
import { PaymentService } from '../Services/payment.service';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import * as XLSX from 'xlsx';
import * as FileSaver from 'file-saver';
declare var $: any;

@Component({
  selector: 'app-payment',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule],
  templateUrl: './payment.component.html',
  styleUrl: './payment.component.css'
})
export class PaymentComponent {
  payments: any[] = [];
  selectedPayment: any | null = null;
  filterPayment: any[] = [];
  searchTerm: string = '';

  constructor(private paymentService: PaymentService, private router: Router, private location: Location, private snackBar: MatSnackBar) {}

  ngOnInit(): void {
    this.loadPayments();
  }

  loadPayments(): void {
    this.paymentService.getPayments().subscribe({
      next: (data) => {
        this.payments = data;
        this.filterPayment = data;
        console.log(data)
      },
      error: (err) => {
        console.error('Error fetching payments:', err);
      }
    });
  }  

  filteredPayments(): void {
    if (!this.searchTerm) {
      this.filterPayment = this.payments;
    } else {
      const term = this.searchTerm.toLowerCase();
      this.filterPayment = this.payments.filter(payment =>
        payment.payment_ID.toString().includes(term) ||
        payment.memberName.toLowerCase().includes(term) ||
        payment.amount.toString().includes(term) ||
        payment.payment_Date.toString().includes(term) ||
        payment.paymentTypeName.toLowerCase().includes(term)
      );
    }
  }
 
  openModal(payment: any): void {
    this.selectedPayment = payment;
    $('#userModal').modal('show');
  }
 
  closeModal(): void {
    $('#userModal').modal('hide');
  }
 
  goBack(): void {
    this.location.back();
  }

  exportToExcel(): void {
    const customHeaders = [
      { header: 'Payment ID', key: 'payment_ID' },
      { header: 'Member Name', key: 'memberName' },
      { header: 'Amount', key: 'amount' },
      { header: 'Payment Date', key: 'payment_Date' },
      { header: 'Payment Type', key: 'paymentTypeName' }
    ];

    const worksheetData = this.filterPayment.map(payment => ({
      payment_ID: payment.payment_ID,
      memberName: payment.memberName,
      amount: payment.amount,
      payment_Date: this.formatDate(payment.payment_Date), // Format the date
      paymentTypeName: payment.paymentTypeName
    }));

    const worksheet = XLSX.utils.json_to_sheet(worksheetData, { header: customHeaders.map(h => h.key) });
    const workbook = { Sheets: { 'Payments': worksheet }, SheetNames: ['Payments'] };

    // Modify column headers
    customHeaders.forEach((header, index) => {
      const col = XLSX.utils.encode_col(index); // Convert 0 -> 'A', 1 -> 'B', etc.
      worksheet[`${col}1`] = { t: 's', v: header.header };
    });

    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    this.saveAsExcelFile(excelBuffer, 'payments');
  }

  private formatDate(date: string): string {
    return new Date(date).toISOString().split('T')[0];
  }

  private saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], { type: EXCEL_TYPE });
    FileSaver.saveAs(data, `${fileName}_${new Date().getTime()}.xlsx`);
  }
}

const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';

//html
<br>
<div class="header-search-container">
    <i class="bi bi-arrow-left-circle header-icon" (click)="goBack()"></i>
    <h2 class="header-title">Payment Manager</h2>
    <div class="search-bar-container">
        <input type="text" class="form-control search-bar" placeholder="Search payments" [(ngModel)]="searchTerm" (input)="filteredPayments()">
    </div>
</div>
<br>
<br>
<div class="container">
    <div *ngIf="payments.length === 0">
        <p>No payments have been made.</p>
    </div>
    <div *ngIf="payments.length > 0" class="row">
        <table class="table">
            <thead class="table-dark">
                <tr>
                <th>Payment ID</th>
                <th>Member Name</th>
                <th>Amount</th>
                <th>Payment Date</th>
                <th>Payment Type</th>
                <th>Action</th>
                </tr>
            </thead>
            <tbody class>
                <tr *ngFor="let payment of filterPayment">
                <td>{{ payment.payment_ID }}</td>
                <td>{{ payment.memberName }}</td>
                <td>{{ payment.amount | currency: 'R ' }}</td>
                <td>{{ payment.payment_Date | date: 'short' }}</td>
                <td>{{ payment.paymentTypeName }}</td>
                <td>
                    <button class="btn btn-primary" (click)="openModal(payment)">View</button>
                </td>
                </tr>
            </tbody>
    </table>
    
    <button class="btn btn-success" (click)="exportToExcel()">Export to Excel</button>
    
    <div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
          <div class="modal-content" style="text-align: center;">
            <div class="modal-header">
              <h5 class="modal-title" id="userModalLabel"><strong>Payment Details</strong></h5>
            </div>
            <div class="modal-body">
              <p><strong>Payment ID:</strong> {{ selectedPayment?.payment_ID }}</p>
              <p><strong>Member Name:</strong> {{ selectedPayment?.memberName }}</p>
              <p><strong>Amount:</strong> {{ selectedPayment?.amount | currency: 'R ' }}</p>
              <p><strong>Payment Date:</strong> {{ selectedPayment?.payment_Date | date: 'short' }}</p>
              <p><strong>Payment Type:</strong> {{ selectedPayment?.paymentTypeName }}</p>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" (click)="closeModal()">Close</button>
            </div>
          </div>
        </div>
      </div>
</div> 

//shared
//file-saver.d.ts
declare module 'file-saver';
//SQL QUERY
CREATE PROCEDURE UpdateUserDeletionSettings
    @DeletionTimeValue INT,
    @DeletionTimeUnit NVARCHAR(20)
AS
BEGIN
    SET NOCOUNT ON;
    
    -- Define the deletion threshold
    DECLARE @DeletionThreshold DATETIME;
    SET @DeletionThreshold = CASE
        WHEN @DeletionTimeUnit = 'Minutes' THEN DATEADD(MINUTE, -@DeletionTimeValue, GETUTCDATE())
        WHEN @DeletionTimeUnit = 'Hours' THEN DATEADD(HOUR, -@DeletionTimeValue, GETUTCDATE())
        WHEN @DeletionTimeUnit = 'Days' THEN DATEADD(DAY, -@DeletionTimeValue, GETUTCDATE())
        WHEN @DeletionTimeUnit = 'Weeks' THEN DATEADD(WEEK, -@DeletionTimeValue, GETUTCDATE())
        WHEN @DeletionTimeUnit = 'Months' THEN DATEADD(MONTH, -@DeletionTimeValue, GETUTCDATE())
        WHEN @DeletionTimeUnit = 'Years' THEN DATEADD(YEAR, -@DeletionTimeValue, GETUTCDATE())
        ELSE GETUTCDATE()
    END;

    -- Delete users based on the threshold
    DELETE FROM dbo.AspNetUsers
    WHERE User_Status_ID = 2 AND DeactivatedAt < @DeletionThreshold;
END

//UserDeletionService
using av_motion_api.Data; 
using av_motion_api.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;

namespace av_motion_api.Services
{
    public class UserDeletionService : IHostedService, IDisposable
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly IOptionsMonitor<DeletionSettings> _settings;
        private Timer _timer;
        private long _remainingIntervals;
        private const long MaxInterval = Int32.MaxValue - 2;

        public UserDeletionService(IServiceProvider serviceProvider, IOptionsMonitor<DeletionSettings> settings)
        {
            _serviceProvider = serviceProvider;
            _settings = settings;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            ScheduleDeletionTask();
            _settings.OnChange(settings => ScheduleDeletionTask());
            return Task.CompletedTask;
        }

        private void ScheduleDeletionTask()
        {
            var interval = GetTimeSpan(_settings.CurrentValue.DeletionTimeValue, _settings.CurrentValue.DeletionTimeUnit);
            _remainingIntervals = (long)Math.Ceiling(interval.TotalMilliseconds / MaxInterval);

            _timer?.Dispose();
            _timer = new Timer(OnTimerElapsed, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(MaxInterval));
        }



        private void OnTimerElapsed(object state)
        {
            if (--_remainingIntervals <= 0)
            {
                DeleteDeactivatedUsers(state);
                ScheduleDeletionTask(); // Reschedule for the next interval
            }
        }

        private void DeleteDeactivatedUsers(object state)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();

                var deletionThreshold = DateTime.UtcNow.Subtract(GetTimeSpan(_settings.CurrentValue.DeletionTimeValue, _settings.CurrentValue.DeletionTimeUnit));

                var connection = context.Database.GetDbConnection();
                if (connection.State != System.Data.ConnectionState.Open)
                {
                    connection.Open();
                }

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "UpdateUserDeletionSettings";
                    command.CommandType = System.Data.CommandType.StoredProcedure;
                    command.Parameters.Add(new SqlParameter("@DeletionTimeValue", _settings.CurrentValue.DeletionTimeValue));
                    command.Parameters.Add(new SqlParameter("@DeletionTimeUnit", _settings.CurrentValue.DeletionTimeUnit));

                    command.ExecuteNonQuery();
                }
            }
        }


        private TimeSpan GetTimeSpan(int value, string unit)
        {
            return unit.ToLower() switch
            {
                "minutes" => TimeSpan.FromMinutes(value),
                "hours" => TimeSpan.FromHours(value),
                "days" => TimeSpan.FromDays(value),
                "weeks" => TimeSpan.FromDays(value * 7),
                "months" => TimeSpan.FromDays(value * 30), // Approximation
                "years" => TimeSpan.FromDays(value * 365), // Approximation
                _ => TimeSpan.FromMinutes(value),
            };
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
}

//Program.cs --unchanged
using av_motion_api.Data;
using av_motion_api.Factory;
using av_motion_api.Models;
using av_motion_api.Interfaces;
using av_motion_api.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Configuration; // Ensure this is here
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

// Configure the app environment
var configuration = builder.Configuration;

builder.Configuration.SetBasePath(Directory.GetCurrentDirectory())
    //.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: false);
    .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true); // Add reloadOnChange

builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
    //config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    config.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true); // Add reloadOnChange
    config.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true);
});

// Configure logging
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();

// CORS
if (builder.Environment.IsDevelopment())
{
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", policy =>
        {
            policy.AllowAnyOrigin()
                  .AllowAnyHeader()
                  .AllowAnyMethod();
        });
    });
}

// Add services to the container
builder.Services.AddControllers()
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
                    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
                });

// SQL
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IRepository, Repository>();

builder.Services.AddIdentity<User, Role>(options =>
                {
                    options.Password.RequireUppercase = false;
                    options.Password.RequireLowercase = false;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireDigit = true;
                    options.User.RequireUniqueEmail = true;
                })
                .AddRoles<Role>()
                .AddEntityFrameworkStores<AppDbContext>()
                .AddDefaultTokenProviders();

builder.Services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddCookie()
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = builder.Configuration["Tokens:Issuer"],
                        ValidAudience = builder.Configuration["Tokens:Audience"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Tokens:Key"]))
                    };
                });

// Configure FormOptions for file uploads
builder.Services.Configure<FormOptions>(o =>
{
    o.ValueLengthLimit = int.MaxValue;
    o.MultipartBodyLengthLimit = int.MaxValue;
    o.MemoryBufferThreshold = int.MaxValue;
});

builder.Services.AddScoped<IUserClaimsPrincipalFactory<User>, AppUserClaimsPrincipalFactory>();

builder.Services.Configure<DataProtectionTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromHours(3));


// Register the OrderStatusUpdater hosted service
builder.Services.AddHostedService<OrderStatusUpdater>();

// Register the DeletionSettings configuration section
builder.Services.Configure<DeletionSettings>(configuration.GetSection("DeletionSettings"));

// Register the UserDeletionService hosted service
builder.Services.AddHostedService<UserDeletionService>();

// Register ContractLinkingService
//builder.Services.AddHostedService<ContractLinkingService>();


// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// Use CORS
app.UseCors("AllowAll");

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Use(async (context, next) =>
{
    var logger = app.Services.GetRequiredService<ILogger<Program>>();
    logger.LogInformation("Handling request: " + context.Request.Path);
    await next.Invoke();
    logger.LogInformation("Finished handling request.");
});

app.Run();

//appsettings.Development.json --unchanged
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-9QI4G7U\\SQLEXPRESS;Database=AV_Motion;Trusted_Connection=True;TrustServerCertificate=True"
  },
  "Tokens": {
    "Key": "hLKjZkF5q2wX3rQ$@1hy+VRv[&)0XhxJ<sk=yUpW{yE5CH@xh",
    "Issuer": "https://localhost:7185",
    "Audience": "http://localhost:4200"
  },
  "SendGrid": {
    "ApiKey": "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",
    "SenderEmail": "datalungeteam43@gmail.com",
    "SenderName": "AVSFitnessAdmin@AVMotion.com",
    "ContractsDirectory": "C:\\Contracts\\AVS_Fitness"
  },
  "DeletionSettings": {
    "DeletionTimeValue": 1,
    "DeletionTimeUnit": "Minutes"
  }
}
  
//AppDbContext --Add & run migration
  public DbSet<DeletionSettings> DeletionSettings { get; set; }

  // Configure the DeletionSettings entity
  builder.Entity<DeletionSettings>()
    .HasKey(ds => new { ds.DeletionTimeValue, ds.DeletionTimeUnit });

  builder.Entity<DeletionSettings>()
    .Property(ds => ds.DeletionTimeValue)
    .IsRequired();

  builder.Entity<DeletionSettings>()
    .Property(ds => ds.DeletionTimeUnit)
    .IsRequired()
    .HasMaxLength(50);
Link: <https://one.example.com>; rel="preconnect", <https://two.example.com>; rel="preconnect", <https://three.example.com>; rel="preconnect"
star

Wed Aug 07 2024 09:00:03 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Aug 07 2024 08:50:14 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Aug 07 2024 02:12:07 GMT+0000 (Coordinated Universal Time)

@quanganh141220 #php #single #product

star

Tue Aug 06 2024 17:42:28 GMT+0000 (Coordinated Universal Time)

@wasim_mm1

star

Tue Aug 06 2024 14:05:29 GMT+0000 (Coordinated Universal Time) https://www.ntlite.com/community/index.php?threads/content-delivery-manager-vs-automatic-installation-of-sponsored-apps.4684/#post-45667

@Curable1600 #windows #ntlite

star

Tue Aug 06 2024 13:32:00 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Tue Aug 06 2024 11:44:03 GMT+0000 (Coordinated Universal Time) https://maticz.com/asset-tokenization-platform-development

@carolinemax ##maticz ##usa #assettokenization platform development

star

Tue Aug 06 2024 11:00:28 GMT+0000 (Coordinated Universal Time)

@ngoctran #php

star

Tue Aug 06 2024 09:40:50 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Tue Aug 06 2024 06:35:19 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/problems/detect-cycle-in-an-undirected-graph/1

@w3yogesh #c++

star

Tue Aug 06 2024 05:45:33 GMT+0000 (Coordinated Universal Time) https://aovup.com/woocommerce/custom-order-status/

@mediasolutions

star

Tue Aug 06 2024 01:50:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/37790855/renaming-woocommerce-order-status

@mediasolutions

star

Mon Aug 05 2024 19:53:31 GMT+0000 (Coordinated Universal Time)

@peron97 #html

star

Mon Aug 05 2024 17:57:38 GMT+0000 (Coordinated Universal Time)

@tanushahaha

star

Mon Aug 05 2024 17:05:19 GMT+0000 (Coordinated Universal Time) https://www.codechef.com/problems/SQING

@utp #c++

star

Mon Aug 05 2024 16:57:34 GMT+0000 (Coordinated Universal Time)

@rohan_112d

star

Mon Aug 05 2024 16:16:34 GMT+0000 (Coordinated Universal Time)

@ibn_shakeerah

star

Mon Aug 05 2024 15:32:50 GMT+0000 (Coordinated Universal Time)

@trvndng #javascript

star

Mon Aug 05 2024 15:07:42 GMT+0000 (Coordinated Universal Time)

@tokoyami_ds #php #wordpress #checkout #factor #checkbox

star

Mon Aug 05 2024 12:50:16 GMT+0000 (Coordinated Universal Time)

@ibn_shakeerah

star

Mon Aug 05 2024 12:33:51 GMT+0000 (Coordinated Universal Time)

@ibn_shakeerah

star

Mon Aug 05 2024 12:00:16 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/c/34f4ea11-88de-45af-9d0f-2d9c829daef6

@Zslayer97

star

Mon Aug 05 2024 11:33:23 GMT+0000 (Coordinated Universal Time)

@codeing #javascript #react.js

star

Mon Aug 05 2024 08:36:34 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/8946325/chrome-extension-id-how-to-find-it

@Curable1600 #edgebrowser #chromebrowser

star

Mon Aug 05 2024 07:47:51 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Aug 05 2024 06:28:35 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Mon Aug 05 2024 06:05:11 GMT+0000 (Coordinated Universal Time)

@signup

star

Mon Aug 05 2024 05:53:12 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/c/0bed8330-b7d0-4d76-9f9b-94e81c012d36

star

Mon Aug 05 2024 05:50:59 GMT+0000 (Coordinated Universal Time)

@WXAPAC

star

Mon Aug 05 2024 05:10:42 GMT+0000 (Coordinated Universal Time)

@signup

star

Mon Aug 05 2024 04:14:00 GMT+0000 (Coordinated Universal Time)

@signup

star

Sun Aug 04 2024 20:41:41 GMT+0000 (Coordinated Universal Time) https://www.npmjs.com/package/react-colorful

@Shook87

star

Sun Aug 04 2024 18:18:05 GMT+0000 (Coordinated Universal Time) https://gunsbuyerusa.com/product-category/arsenal-ak47-sale/

@ak74uforsale

star

Sun Aug 04 2024 17:08:37 GMT+0000 (Coordinated Universal Time) https://github.com/shookthacr3ator777/examples

@Shook87

star

Sun Aug 04 2024 17:08:28 GMT+0000 (Coordinated Universal Time) https://github.com/shookthacr3ator777/examples

@Shook87

star

Sun Aug 04 2024 14:37:43 GMT+0000 (Coordinated Universal Time) https://codepen.io/dangol-heart/pen/QWXvrOe

@dongolheart #undefined

star

Sun Aug 04 2024 13:27:12 GMT+0000 (Coordinated Universal Time) https://findlokal.co.za/wp-admin/post-new.php?post_type

@danieros #undefined

star

Sun Aug 04 2024 10:02:43 GMT+0000 (Coordinated Universal Time)

@DoctorDoom

star

Sun Aug 04 2024 09:57:43 GMT+0000 (Coordinated Universal Time)

@DoctorDoom

star

Sun Aug 04 2024 09:54:33 GMT+0000 (Coordinated Universal Time)

@StephenThevar

star

Sun Aug 04 2024 08:55:50 GMT+0000 (Coordinated Universal Time)

@StephenThevar

star

Sun Aug 04 2024 07:19:18 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/ru-ru/office/vba/excel/concepts/workbooks-and-worksheets/create-a-scheduling-calendar-workbook

@Swietoslawa #vba

star

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

@Samuel1347 #flutter #dart

star

Sat Aug 03 2024 23:50:30 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sat Aug 03 2024 14:31:33 GMT+0000 (Coordinated Universal Time) https://tutorialhorizon.com/excel/vba-excel-sudoku-solver/

@Swietoslawa #vba

star

Sat Aug 03 2024 14:13:25 GMT+0000 (Coordinated Universal Time) https://officetricks.com/replace-na-excel-with-0-or-blank-formula/

@Swietoslawa

star

Sat Aug 03 2024 14:10:17 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sat Aug 03 2024 13:43:46 GMT+0000 (Coordinated Universal Time) https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link

@Shook87

Save snippets that work with our extensions

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