Snippets Collections
SWITCH(LOOKUP(USEREMAIL(), "Accounts", "Email", "Position"), 
  "dev", "ALL_CHANGES", 
  "accountant", "ALL_CHANGES", 
  "READ_ONLY")
const BasicComponent = () => {
  return (
    <div>
      <h1>This is basic component!</h1>
    </div>
  );
};

export default BasicComponent;
//controller
using av_motion_api.Data;
using av_motion_api.Models;
using av_motion_api.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace av_motion_api.Controllers
{
    [Route("api/supplier/[controller]")]
    [ApiController]
    public class SupplierController : ControllerBase
    {
        private readonly AppDbContext _appContext;
        private readonly ILogger<SupplierController> _logger;

        public SupplierController(AppDbContext context, ILogger<SupplierController> logger)
        {
            _appContext = context;
            _logger = logger;
        }

        // GET: api/supplier/GetSuppliers
        [HttpGet]
        [Route("GetSuppliers")]
        //[Authorize(Roles = "Administrator")]
        public async Task<ActionResult<IEnumerable<Supplier>>> GetSuppliers()
        {
            var suppliers = await _appContext.Suppliers.ToListAsync();
            return suppliers;
        }

        // GET: api/supplier/GetSupplier/{id}
        [HttpGet]
        [Route("GetSupplier/{id}")]
        //[Authorize(Roles = "Administrator")]
        public async Task<ActionResult<Supplier>> GetSupplier(int id)
        {
            if (_appContext.Suppliers == null)
            {
                return NotFound();
            }
            var supplier = await _appContext.Suppliers.FindAsync(id);
            if (supplier == null)
            {
                return NotFound();
            }
            return supplier;
        }

        // POST: api/supplier/PostSupplier
        [HttpPost]
        [Route("PostSupplier")]
        //[Authorize(Roles = "Administrator")]
        public async Task<ActionResult<Supplier>> PostSupplier([FromBody] Supplier supplier)
        {
            if (_appContext.Suppliers == null)
            {
                return Problem("Entity set 'AppDbContext.Suppliers' is null.");
            }

            var supplierEntity = new Supplier
            {
                Name = supplier.Name,
                Contact_Number = supplier.Contact_Number,
                Email_Address = supplier.Email_Address,
                Physical_Address = supplier.Physical_Address,
            };

            _appContext.Suppliers.Add(supplierEntity);
            await _appContext.SaveChangesAsync();
            return Ok(supplier);
        }

        // PUT: api/supplier/PutSupplier/{id}
        [HttpPut]
        [Route("PutSupplier/{id}")]
        //[Authorize(Roles = "Administrator")]
        public async Task<IActionResult> PutSupplier(int id, [FromBody] SupplierViewModel supplier)
        {
            var supplierEntity = await _appContext.Suppliers.FindAsync(id);

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

            supplierEntity.Name = supplier.Name;
            supplierEntity.Contact_Number = supplier.Contact_Number;
            supplierEntity.Email_Address = supplier.Email_Address;
            supplierEntity.Physical_Address = supplier.Physical_Address;

            try
            {
                _appContext.Suppliers.Update(supplierEntity);
                await _appContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SupplierExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // DELETE: api/supplier/DeleteSupplier/{id}
        [HttpDelete]
        [Route("DeleteSupplier/{id}")]
        //[Authorize(Roles = "Administrator")]
        public async Task<IActionResult> DeleteSupplier(int id)
        {
            if (_appContext.Suppliers == null)
            {
                return NotFound();
            }
            var supplier = await _appContext.Suppliers.FindAsync(id);
            if (supplier == null)
            {
                return NotFound();
            }

            _appContext.Suppliers.Remove(supplier);
            await _appContext.SaveChangesAsync();
            return NoContent();
        }

        private bool SupplierExists(int id)
        {
            return (_appContext.Suppliers?.Any(e => e.Supplier_ID == id)).GetValueOrDefault();
        }

        // GET: api/supplier/GetAllSupplierOrders
        [HttpGet]
        [Route("GetAllSupplierOrders")]
        //[Authorize(Roles = "Administrator")]
        public async Task<IActionResult> GetAllSupplierOrders()
        {
            var orders = await _appContext.Supplier_Orders
                    .Include(o => o.Supplier)
                    .Include(o => o.Owner)
                    .Include(o => o.Supplier_Order_Lines)
                    .ThenInclude(sol => sol.Product)
                    .ToListAsync();

            var supplierOrderViewModels = orders.Select(order => new SupplierOrderViewModel
            {
                Supplier_Order_ID = order.Supplier_Order_ID,
                Date = order.Date,
                Supplier_ID = order.Supplier_ID,
                Supplier_Name = order.Supplier.Name,
                Owner_ID = order.Owner_ID,
                Status = order.Status,
                Supplier_Order_Details = order.Supplier_Order_Details,
                OrderLines = order.Supplier_Order_Lines.Select(sol => new SupplierOrderLineViewModel
                {
                    Supplier_Order_Line_ID = sol.Supplier_Order_Line_ID,
                    Product_ID = sol.Product_ID,
                    Product_Name = sol.Product.Product_Name,
                    Supplier_Quantity = sol.Supplier_Quantity,
                    Purchase_Price = sol.Purchase_Price
                }).ToList(),
                Total_Price = (decimal)order.Supplier_Order_Lines.Sum(sol => sol.Supplier_Quantity * sol.Purchase_Price)
            }).ToList();

            return Ok(supplierOrderViewModels);
        }

        // GET: api/supplier/GetSupplierOrderById/{id}
        [HttpGet]
        [Route("GetSupplierOrderById/{id}")]
        //[Authorize(Roles = "Administrator")]
        public async Task<IActionResult> GetSupplierOrderById(int id)
        {
            try
            {
                var order = await _appContext.Supplier_Orders
                    .Include(o => o.Supplier)
                    .Include(o => o.Owner)
                    .Include(o => o.Supplier_Order_Lines)
                    .ThenInclude(sol => sol.Product)
                    .FirstOrDefaultAsync(o => o.Supplier_Order_ID == id);

                if (order == null)
                {
                    return NotFound("Supplier order not found.");
                }

                return Ok(order);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error fetching supplier order by ID.");
                return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request.");
            }
        }

        // GET: api/supplier/GetSupplierOrderDetails/{orderId}
        [HttpGet]
        [Route("GetSupplierOrderDetails/{orderId}")]
        public async Task<IActionResult> GetSupplierOrderDetails(int orderId)
        {
            try
            {
                var orderDetails = await (from sol in _appContext.Supplier_Order_Lines
                                          join p in _appContext.Products on sol.Product_ID equals p.Product_ID
                                          where sol.Supplier_Order_ID == orderId
                                          select new SupplierOrderDetailsViewModel
                                          {
                                              Supplier_Order_Line_ID = sol.Supplier_Order_Line_ID,
                                              Supplier_Order_ID = sol.Supplier_Order_ID,
                                              Product_ID = sol.Product_ID,
                                              Supplier_Quantity = sol.Supplier_Quantity,
                                              Purchase_Price = p.Purchase_Price ?? 0, // Handle nullable Purchase_Price
                                              Total_Price = (sol.Supplier_Quantity * (p.Purchase_Price ?? 0)), // Calculate Total_Price
                                              Product_Name = p.Product_Name
                                          }).ToListAsync();

                if (orderDetails == null || orderDetails.Count == 0)
                {
                    return NotFound("No order details found for the given order ID.");
                }

                return Ok(orderDetails);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error retrieving supplier order details.");
                return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request.");
            }
        }

        [HttpGet]
        [Route("GetProductCategories")]
        public async Task<IActionResult> GetProductCategories()
        {
            var categories = await _appContext.Product_Categories.ToListAsync();
            return Ok(categories);
        }

        // Controller to fetch products by category ID
        [HttpGet]
        [Route("GetProductsByCategory/{categoryId}")]
        public async Task<IActionResult> GetProductsByCategory(int categoryId)
        {
            var products = await _appContext.Products.Where(p => p.Product_Category_ID == categoryId).ToListAsync();
            return Ok(products);
        }
        
        [HttpPost]
        [Route("PlaceSupplierOrder")]
        public async Task<IActionResult> PlaceSupplierOrder([FromBody] SupplierOrderViewModel orderVm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // Create a new supplier order
            var supplierOrder = new Supplier_Order
            {
                Date = DateTime.UtcNow,
                Supplier_Order_Details = orderVm.Supplier_Order_Details,
                Supplier_ID = orderVm.Supplier_ID,
                Owner_ID = orderVm.Owner_ID,
                Status = orderVm.Status,
                Supplier_Order_Lines = new List<Supplier_Order_Line>()
            };

            decimal totalOrderPrice = 0;

            Console.WriteLine($"Creating Supplier_Order with ID {supplierOrder.Supplier_Order_ID}");
            Console.WriteLine($"OrderLines count: {orderVm.OrderLines?.Count ?? 0}");

            // Process each order line
            foreach (var orderLine in orderVm.OrderLines)
            {

                // Fetch the product details
                var product = await _appContext.Products.FindAsync(orderLine.Product_ID);
                if (product == null)
                {
                    return BadRequest($"Product with ID {orderLine.Product_ID} not found.");
                }

                if (product != null)
                {
                    var purchasePrice = product.Purchase_Price;
                    if (purchasePrice == null)
                    {
                        return BadRequest($"Purchase price for product ID {orderLine.Product_ID} is not set.");
                    }

                    // Create a new supplier order line
                    var supplierOrderLine = new Supplier_Order_Line
                    {
                        Product_ID = orderLine.Product_ID,
                        Supplier_Quantity = orderLine.Supplier_Quantity,
                        Purchase_Price = purchasePrice // Set the purchase price from product
                    };

                    // Add the order line to the supplier order
                    supplierOrder.Supplier_Order_Lines.Add(supplierOrderLine);

                    // Calculate total price
                    totalOrderPrice += orderLine.Supplier_Quantity * (decimal)purchasePrice;
                }

                Console.WriteLine($"Processing OrderLine: Product_ID = {orderLine.Product_ID}, Quantity = {orderLine.Supplier_Quantity}");
            }

            // Set total price on supplier order
            supplierOrder.Total_Price = totalOrderPrice;

            // Save the supplier order to the database
            _appContext.Supplier_Orders.Add(supplierOrder);
            await _appContext.SaveChangesAsync();

            return Ok(supplierOrder);
        }

        // PUT: api/supplier/updateinventory
        [HttpPut]
        [Route("updateinventory")]
        //[Authorize(Roles = "Administrator")]
        public async Task<IActionResult> UpdateInventory([FromBody] UpdateInventoryViewModel updateInventoryVm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var receivedSupplierOrder = new Received_Supplier_Order
                {
                    Supplies_Received_Date = updateInventoryVm.Supplies_Received_Date
                };

                _appContext.Received_Supplier_Orders.Add(receivedSupplierOrder);
                await _appContext.SaveChangesAsync();

                foreach (var line in updateInventoryVm.ReceivedOrderLines)
                {
                    var receivedOrderLine = new Received_Supplier_Order_Line
                    {
                        Received_Supplier_Order_ID = receivedSupplierOrder.Received_Supplier_Order_ID,
                        Received_Supplies_Quantity = line.Received_Supplies_Quantity,
                        Supplier_Order_Line_ID = line.Supplier_Order_Line_ID,
                    };

                    var product = await _appContext.Products.FindAsync(line.Product_ID);
                    if (product != null)
                    {
                        product.Quantity += line.Received_Supplies_Quantity;
                        _appContext.Products.Update(product);
                    }

                    _appContext.Received_Supplier_Order_Lines.Add(receivedOrderLine);
                }

                await _appContext.SaveChangesAsync();

                return Ok("Inventory updated successfully.");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating inventory.");
                return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request.");
            }
        }

        // POST: api/supplier/receivesupplierorder
        [HttpPost]
        [Route("receivesupplierorder")]

        public async Task<IActionResult> ReceiveSupplierOrder([FromBody] ReceivedSupplierOrderViewModel receiveOrderVm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var receivedSupplierOrder = new Received_Supplier_Order
            {
                Supplies_Received_Date = receiveOrderVm.Supplies_Received_Date,
                Discrepancies = receiveOrderVm.Discrepancies,
                Accepted = receiveOrderVm.Accepted ?? false,
                Received_Supplier_Order_Lines = new List<Received_Supplier_Order_Line>()
            };

            _appContext.Received_Supplier_Orders.Add(receivedSupplierOrder);
            await _appContext.SaveChangesAsync();

            if (receivedSupplierOrder.Accepted)
            {
                foreach (var line in receiveOrderVm.Received_Supplier_Order_Lines)
                {
                    var product = await _appContext.Products.FindAsync(line.Product_ID);

                    // Debugging and Logging
                    Console.WriteLine($"Processing Product ID: {line.Product_ID}");

                    if (product == null)
                    {
                        Console.WriteLine($"Product ID {line.Product_ID} not found.");
                        return BadRequest($"Product ID {line.Product_ID} not found.");
                    }

                    product.Quantity += line.Received_Supplies_Quantity;
                    _appContext.Products.Update(product);

                    var receivedOrderLine = new Received_Supplier_Order_Line
                    {
                        Received_Supplier_Order_ID = receivedSupplierOrder.Received_Supplier_Order_ID,
                        Received_Supplies_Quantity = line.Received_Supplies_Quantity,
                        Supplier_Order_Line_ID = line.Supplier_Order_Line_ID,
                        Product_ID = line.Product_ID // Ensure this is set
                    };

                    _appContext.Received_Supplier_Order_Lines.Add(receivedOrderLine);
                }

                await _appContext.SaveChangesAsync();
            }

            return Ok(receivedSupplierOrder);
        }

        [HttpPost]
        [Route("UpdateSupplierOrderStatus")]
        public async Task<IActionResult> UpdateSupplierOrderStatus([FromBody] UpdateSupplierOrderStatusViewModel statusUpdateVm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // Fetch the specific supplier order entry
            var supplierOrder = await _appContext.Supplier_Orders
                .FirstOrDefaultAsync(o => o.Supplier_Order_ID == statusUpdateVm.Supplier_Order_ID);

            if (supplierOrder == null)
            {
                return BadRequest($"Supplier order with ID {statusUpdateVm.Supplier_Order_ID} not found.");
            }

            // Update the status based on the Accepted boolean
            supplierOrder.Status = statusUpdateVm.Status; // Ensure this is directly assigned

            // Save changes to the database
            await _appContext.SaveChangesAsync();

            return Ok(supplierOrder);
        }
    }
}
//models
public class Supplier_Order
{
    [Key]
    public int Supplier_Order_ID { get; set; }

    //[Required]
    public DateTime Date { get; set; }

    //[Required]
    public string? Supplier_Order_Details { get; set; }

    //[Required]
    public decimal Total_Price { get; set; }

    public int Status { get; set; }

    public int Supplier_ID { get; set; }

    [ForeignKey(nameof(Supplier_ID))]
    public Supplier Supplier { get; set; }

    public int Owner_ID { get; set; }

    [ForeignKey(nameof(Owner_ID))]
    public Owner Owner { get; set; }

    public ICollection<Supplier_Order_Line> Supplier_Order_Lines { get; set; }
}
public class Supplier_Order_Line
{
    [Key]
    public int Supplier_Order_Line_ID { get; set; }

    public int Supplier_Quantity { get; set; }


    public int Product_ID { get; set; }

    [ForeignKey(nameof(Product_ID))]

    public Product Product { get; set; }

    public decimal? Purchase_Price { get; set; } 

    public decimal? Unit_Price { get; set; } 

    public int Supplier_Order_ID { get; set; }

    [ForeignKey(nameof(Supplier_Order_ID))]
    public Supplier_Order Supplier_Order { get; set; } 
}
public class Received_Supplier_Order
{
    [Key]
    public int Received_Supplier_Order_ID { get; set; }

    [Required]
    public DateTime Supplies_Received_Date { get; set; }

    public bool Accepted { get; set; } // Indicates if the order was accepted

    public string? Discrepancies { get; set; }  // Nullable attribute for discrepancies

    public ICollection<Received_Supplier_Order_Line> Received_Supplier_Order_Lines { get; set; }
}
public class Received_Supplier_Order_Line
{
    [Key]
    public int Received_Supplier_Order_Line_ID { get; set; }

    public int Received_Supplier_Order_ID { get; set; }

    [ForeignKey(nameof(Received_Supplier_Order_ID))]

    public Received_Supplier_Order Received_Supplier_Order { get; set; }


    public int Supplier_Order_Line_ID { get; set; }

    [ForeignKey(nameof(Supplier_Order_Line_ID))]

    public Supplier_Order_Line Supplier_Order_Line { get; set; }
  

    public int Product_ID { get; set; }

    [ForeignKey(nameof(Product_ID))]

    public Product Product { get; set; }

    public int Received_Supplies_Quantity { get; set; }
}

//viewmodels
public class SupplierOrderViewModel
{
    public int Supplier_Order_ID { get; set; }
    public DateTime Date { get; set; }
    public string Supplier_Order_Details { get; set; }
    public decimal Total_Price { get; set; }
    public int Supplier_ID { get; set; }
    public string Supplier_Name { get; set; }
    public int Owner_ID { get; set; }
    public int Status { get; set; }
    public ICollection<SupplierOrderLineViewModel> OrderLines { get; set; }
}
public class SupplierOrderLineViewModel
{
    public int Supplier_Order_Line_ID { get; set; }
    public int Product_ID { get; set; }
    public string Product_Name { get; set; }
    public int Supplier_Quantity { get; set; }

    public decimal? Purchase_Price { get; set; }
}
public class UpdateSupplierOrderStatusViewModel
{
    public int Supplier_Order_ID { get; set; }
    public int Status { get; set; } // Boolean to indicate acceptance/rejection
}
public class ReceivedSupplierOrderViewModel
{
    public DateTime Supplies_Received_Date { get; set; }

    public bool? Accepted { get; set; } // Nullable bool to indicate acceptance/rejection

    public string? Discrepancies { get; set; }  // Nullable attribute for discrepancies

    public List<ReceivedSupplierOrderLineViewModel> Received_Supplier_Order_Lines { get; set; }
}

public class ReceivedSupplierOrderLineViewModel
{
    public int Product_ID { get; set; }
    public int Received_Supplies_Quantity { get; set; }
    public int Supplier_Order_Line_ID { get; set; }
}
from typing import List
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base
from pydantic import BaseModel, constr

Base = declarative_base()


class CompanyOrm(Base):
    __tablename__ = 'companies'
    id = Column(Integer, primary_key=True, nullable=False)
    public_key = Column(String(20), index=True, nullable=False, unique=True)
    name = Column(String(63), unique=True)
    domains = Column(ARRAY(String(255)))


class CompanyModel(BaseModel):
    id: int
    public_key: constr(max_length=20)
    name: constr(max_length=63)
    domains: List[constr(max_length=255)]

    class Config:
        orm_mode = True


co_orm = CompanyOrm(
    id=123,
    public_key='foobar',
    name='Testing',
    domains=['example.com', 'foobar.com'],
)
print(co_orm)
#> <models_orm_mode.CompanyOrm object at 0x7f23ee50a650>
co_model = CompanyModel.from_orm(co_orm)
print(co_model)
#> id=123 public_key='foobar' name='Testing' domains=['example.com',
#> 'foobar.com']
https://developer.android.com/courses/android-development-with-kotlin/course?utm_source=dac&utm_medium=website&utm_campaign=edu
Solana is a secured blockchain that allows the creation of decentralized applications(DApps). These services can benefit a business and help it grow in its respective fields. Some of the following services of Solana Dapp Development are:
*Wallet development solutions allow the user to send, receive, store, and manage digital assets like tokens and cryptocurrencies.
*NFT Marketplace Development creates a decentralized marketplace on the blockchain wherNFTs are bought, sold, and traded.
*Solana Exchange Development Services designs a custom Solana-based exchange platform that assists the business in extracting the potential of the Solana blockchain to provide a smooth trading experience.
*Minting platform development services provide custom token creation, smart contract development, and the launch of a new token. 

INSERT INTO tbl_users (user_id, username, crm_id, email, table_type, card_name) VALUES (1553,'Abhay Kumar', 'ak_531328', 'abhay.kumar1@tatamotors.com', 1, '1,2,4,5,6,13,14,15,19,16,17,21,18,29,32');
------------------------------------------
INSERT INTO tbl_users (user_id, username, crm_id, email, table_type, card_name, created_on) VALUES
(1555, 'RAMAN GUPTA', NULL, 'raman.gupta@tatamotors.com', 1, '1,2,4,5,6,13,14,15,19,16,17,21,18,29,32', CURRENT_TIMESTAMP),
----------------------------------------------
UPDATE tbl_users
SET username = 'Gaurav Yadav',
    crm_id = NULL,
    email = 'gaurav.yadav@tatamotors.com',
    table_type = 1,
    card_name = '1,2,4,5,6,13,14,15,19,16,17,21,18,29,32',
    created_on = CURRENT_TIMESTAMP
WHERE user_id = 1554;
--------------------------------------------
//controller
namespace av_motion_api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class InventoriesController : ControllerBase
    {
        private readonly AppDbContext _appContext;
        public readonly IRepository _repository;

        public InventoriesController(AppDbContext _context, IRepository repository)
        {

            _appContext = _context;
            _repository = repository;
        }
        // GET: api/<InventoriesController>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<InventoryViewModel>>> GetInventories()
        {
            var inventories = await _repository.GetInventoryDetails();

            return Ok(inventories);
        }


        // GET api/<InventoriesController>/5
        [HttpGet("{id}")]
        public async Task<ActionResult<InventoryViewModel>> GetInventoryItem(int id)
        {
            if (_appContext.Inventory == null)
            {
                return NotFound();
            }
            var inventoryItem = await _repository.GetInventoryItem(id);
            if (inventoryItem == null)
            {
                return NotFound();
            }

            return Ok(inventoryItem);
        }

        // POST api/<InventoriesController>
        [HttpPost]
        public async Task<ActionResult<Inventory>> PostInventoryItem([FromBody] InventoryViewModel inventoryItem)
        {

            var item = new Inventory
            {

                Inventory_Item_Category = inventoryItem.category,
                Inventory_Item_Name = inventoryItem.itemName,
                Inventory_Item_Quantity = inventoryItem.quantity,
                Inventory_Item_Photo = inventoryItem.photo,
                Supplier_ID = inventoryItem.supplierID,
                Received_Supplier_Order_ID = inventoryItem.received_supplier_order_id
            };




            if (_appContext.Inventory == null)
            {
                return Problem("Entity set 'AppDbContext.Inventory'  is null.");
            }
            _appContext.Inventory.Add(item);
            await _appContext.SaveChangesAsync();


            return Ok(item);
        }

        // PUT api/<InventoriesController>/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutInventoryItem(int id, [FromBody] InventoryViewModel inventoryItem)
        {
            if (id != inventoryItem.inventoryID)
            {
                return BadRequest();
            }
            var existingitem = await _appContext.Inventory.FindAsync(id);

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

            existingitem.Inventory_Item_Name = inventoryItem.itemName;
            existingitem.Inventory_Item_Category = inventoryItem.category;
            existingitem.Inventory_Item_Quantity = inventoryItem.quantity;
            existingitem.Supplier_ID = inventoryItem.supplierID;
            existingitem.Inventory_Item_Photo = inventoryItem.photo;

          //  _appContext.Entry(inventoryItem).State = EntityState.Modified;

            try
            {
                _appContext.Inventory.Update(existingitem);    
                await _appContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!InventoryStatusExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }


        // DELETE api/<InventoriesController>/5
        //[HttpDelete("{id}")]
        //public void Delete(int id)
        //{
        //}

        private bool InventoryStatusExists(int id)
        {
            return (_appContext.Inventory?.Any(e => e.Inventory_ID == id)).GetValueOrDefault();
        }
    }
}

//model
namespace av_motion_api.Models
{
    public class Inventory
    {
        [Key]
        public int Inventory_ID { get; set; }

        [Required]
        [StringLength(50)]
        public string Inventory_Item_Category { get; set;}

        [Required]
        [StringLength(50)]

        public string Inventory_Item_Name { get; set; }

        [Required]

        public int Inventory_Item_Quantity { get; set; }

        [Required]
        public string Inventory_Item_Photo { get; set; }

        public int Supplier_ID { get; set; }

        [ForeignKey(nameof(Supplier_ID))]
        public Supplier Supplier { get; set; }

        public int Received_Supplier_Order_ID { get; set; }

        [ForeignKey(nameof(Received_Supplier_Order_ID))]
        public Received_Supplier_Order Received_Supplier_Order { get; set; }


    }
}

//viewmodel
namespace av_motion_api.ViewModels
{
    public class InventoryViewModel
    {
        public int inventoryID { get; set; }
        public string category { get; set; }
        public string itemName { get; set; }
        public int quantity { get; set; }
        public string photo { get; set; }
        public int supplierID { get; set; }
        public string supplierName { get; set; }
        public int received_supplier_order_id { get; set; }
    }
}
//controller
namespace av_motion_api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class InventoriesController : ControllerBase
    {
        private readonly AppDbContext _appContext;
        public readonly IRepository _repository;

        public InventoriesController(AppDbContext _context, IRepository repository)
        {

            _appContext = _context;
            _repository = repository;
        }
        // GET: api/<InventoriesController>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<InventoryViewModel>>> GetInventories()
        {
            var inventories = await _repository.GetInventoryDetails();

            return Ok(inventories);
        }


        // GET api/<InventoriesController>/5
        [HttpGet("{id}")]
        public async Task<ActionResult<InventoryViewModel>> GetInventoryItem(int id)
        {
            if (_appContext.Inventory == null)
            {
                return NotFound();
            }
            var inventoryItem = await _repository.GetInventoryItem(id);
            if (inventoryItem == null)
            {
                return NotFound();
            }

            return Ok(inventoryItem);
        }

        // POST api/<InventoriesController>
        [HttpPost]
        public async Task<ActionResult<Inventory>> PostInventoryItem([FromBody] InventoryViewModel inventoryItem)
        {

            var item = new Inventory
            {

                Inventory_Item_Category = inventoryItem.category,
                Inventory_Item_Name = inventoryItem.itemName,
                Inventory_Item_Quantity = inventoryItem.quantity,
                Inventory_Item_Photo = inventoryItem.photo,
                Supplier_ID = inventoryItem.supplierID,
                Received_Supplier_Order_ID = inventoryItem.received_supplier_order_id
            };




            if (_appContext.Inventory == null)
            {
                return Problem("Entity set 'AppDbContext.Inventory'  is null.");
            }
            _appContext.Inventory.Add(item);
            await _appContext.SaveChangesAsync();


            return Ok(item);
        }

        // PUT api/<InventoriesController>/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutInventoryItem(int id, [FromBody] InventoryViewModel inventoryItem)
        {
            if (id != inventoryItem.inventoryID)
            {
                return BadRequest();
            }
            var existingitem = await _appContext.Inventory.FindAsync(id);

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

            existingitem.Inventory_Item_Name = inventoryItem.itemName;
            existingitem.Inventory_Item_Category = inventoryItem.category;
            existingitem.Inventory_Item_Quantity = inventoryItem.quantity;
            existingitem.Supplier_ID = inventoryItem.supplierID;
            existingitem.Inventory_Item_Photo = inventoryItem.photo;

          //  _appContext.Entry(inventoryItem).State = EntityState.Modified;

            try
            {
                _appContext.Inventory.Update(existingitem);    
                await _appContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!InventoryStatusExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }


        // DELETE api/<InventoriesController>/5
        //[HttpDelete("{id}")]
        //public void Delete(int id)
        //{
        //}

        private bool InventoryStatusExists(int id)
        {
            return (_appContext.Inventory?.Any(e => e.Inventory_ID == id)).GetValueOrDefault();
        }
    }
}

//model
namespace av_motion_api.Models
{
    public class Inventory
    {
        [Key]
        public int Inventory_ID { get; set; }

        [Required]
        [StringLength(50)]
        public string Inventory_Item_Category { get; set;}

        [Required]
        [StringLength(50)]

        public string Inventory_Item_Name { get; set; }

        [Required]

        public int Inventory_Item_Quantity { get; set; }

        [Required]
        public string Inventory_Item_Photo { get; set; }

        public int Supplier_ID { get; set; }

        [ForeignKey(nameof(Supplier_ID))]
        public Supplier Supplier { get; set; }

        public int Received_Supplier_Order_ID { get; set; }

        [ForeignKey(nameof(Received_Supplier_Order_ID))]
        public Received_Supplier_Order Received_Supplier_Order { get; set; }


    }
}

//viewmodel
namespace av_motion_api.ViewModels
{
    public class InventoryViewModel
    {
        public int inventoryID { get; set; }
        public string category { get; set; }
        public string itemName { get; set; }
        public int quantity { get; set; }
        public string photo { get; set; }
        public int supplierID { get; set; }
        public string supplierName { get; set; }
        public int received_supplier_order_id { get; set; }
    }
}
//controller
namespace av_motion_api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly AppDbContext _appContext;
        public readonly IRepository _repository;
        public ProductController(AppDbContext _context, IRepository repository)
        {

            _appContext = _context;
            _repository = repository;
        }
        // GET: api/<ProductController>
        [HttpGet]
        [Route("GetAllProducts")]
        public async Task<IActionResult> GetAllProducts()
        {
            try
            {
                var products = await _appContext.Products.ToListAsync();

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

        // GET api/<ProductController>/5
        [HttpGet]
        [Route("GetProductById/{id}")]
        public async Task<IActionResult> GetProductById(int id)
        {
            try
            {
                var product = await _appContext.Products.FindAsync(id);
                if (product == null)
                {
                    return NotFound();
                }

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

        //POST api/<ProductController>
        [HttpPost]
        [DisableRequestSizeLimit]
        [Route("PostProduct")]
        public async Task<IActionResult> PostProduct([FromForm] ProductViewModel product)
        {
            var formCollection = await Request.ReadFormAsync();
            var product_Img = formCollection.Files.FirstOrDefault();

            using (var memoryStream = new MemoryStream())
            {
                await product_Img.CopyToAsync(memoryStream);
                var fileBytes = memoryStream.ToArray();
                string base64Image = Convert.ToBase64String(fileBytes);

                var newProduct = new Product()
                {
                    Product_Name = product.Product_Name,
                    Product_Description = product.Product_Description,
                    Product_Img = base64Image,
                    Quantity = product.Quantity,
                    Unit_Price = product.Unit_Price,
                    Purchase_Price = product.Purchase_Price,
                    Size = product.Size,
                    Product_Category_ID = product.Product_Category_ID,
                };

                if (_appContext.Products == null)
                {
                    return Problem("Entity set 'AppDbContext.Products' is null.");
                }
                _appContext.Products.Add(newProduct);
                await _appContext.SaveChangesAsync();

                return Ok(newProduct);
            }
        }


        // PUT api/<ProductController>/5
        [HttpPut]
        [Route("PutProduct/{id}")]
        public async Task<IActionResult> PutProduct(int id, [FromForm] ProductViewModel updatedProduct)
        {
            var existingProduct = await _appContext.Products.FindAsync(id);
            if (existingProduct == null)
            {
                return NotFound();
            }

            // Read the form data to get the photo file
            var formCollection = await Request.ReadFormAsync();
            var product_Img = formCollection.Files.FirstOrDefault();

            existingProduct.Product_Name = updatedProduct.Product_Name;
            existingProduct.Product_Description = updatedProduct.Product_Description;
            existingProduct.Quantity = updatedProduct.Quantity;
            existingProduct.Unit_Price = updatedProduct.Unit_Price;
            existingProduct.Purchase_Price = updatedProduct.Purchase_Price;
            existingProduct.Size = updatedProduct.Size;
            existingProduct.Product_Category_ID = updatedProduct.Product_Category_ID;

            if (product_Img != null && product_Img.Length > 0)
            {
                using (var memoryStream = new MemoryStream())
                {
                    await product_Img.CopyToAsync(memoryStream);
                    var fileBytes = memoryStream.ToArray();
                    string base64Image = Convert.ToBase64String(fileBytes);

                    existingProduct.Product_Img = base64Image; // Store the base64 string of the photo
                }
            }

            _appContext.Products.Update(existingProduct);
            await _appContext.SaveChangesAsync();

            return Ok(existingProduct);
        }

        // DELETE api/<ProductController>/5
        [HttpDelete]
        [Route("DeleteProduct/{id}")]

        public async Task<IActionResult> DeleteProduct(int id)
        {
            if (_appContext.Products == null)
            {
                return NotFound();
            }
            var product = await _appContext.Products.FindAsync(id);
            if (product == null)
            {
                return NotFound();
            }
            
            _appContext.Products.Remove(product);
            await _appContext.SaveChangesAsync();

            return NoContent();
        }

    }
}

//model
  namespace av_motion_api.Models
{
    public class Product
    {
        [Key]
        public int Product_ID { get; set; }

        [Required, StringLength(100)]
        public string Product_Name { get; set; }

        [Required, StringLength(100)]
        public string Product_Description { get; set; }

        [Required]
        public string Product_Img { get; set; }

        public decimal? Purchase_Price { get; set; }

        [Required]
        public int Quantity { get; set; }

        [Required]
        public decimal Unit_Price { get; set; }

        [Required]
        public string Size { get; set; }

        public int Product_Category_ID { get; set; }

        [ForeignKey(nameof(Product_Category_ID))]
        public Product_Category Product_Category { get; set; }

    }
}

//viewmodel
namespace av_motion_api.ViewModels
{
    public class ProductViewModel
    { 
        public string Product_Name { get; set; }
        public string Product_Description { get; set; }
        public IFormFile Product_Img { get; set; }
        public int Quantity { get; set; }
        public decimal Unit_Price { get; set; }
        public decimal? Purchase_Price { get; set; }
        public string Size { get; set; }
        public int Product_Category_ID { get; set; }
    }
}
<!-- Example split danger button -->
<div class="btn-group">
  <button type="button" class="btn btn-danger">Action</button>
  <button type="button" class="btn btn-danger dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
    <span class="visually-hidden">Toggle Dropdown</span>
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">Action</a></li>
    <li><a class="dropdown-item" href="#">Another action</a></li>
    <li><a class="dropdown-item" href="#">Something else here</a></li>
    <li><hr class="dropdown-divider"></li>
    <li><a class="dropdown-item" href="#">Separated link</a></li>
  </ul>
</div>
b=int(input())
a=int(input())
for i in range(1,a+1):
    i=a+1-i
    s=""
    ls=" "*(a-i)
    for j in range(1,i+1):
        if i==a:
            s=s+str(b)+" "
        else:
            if j==1:
                s=s+str(b)+" "
            elif 1<j<i:
                s=s+"  "
            else:
                s=s+str(b)
        b+=1
    print(ls+s)
b=int(input())
a=int(input())
for i in range(1,a+1):
    b=b+i
sn=b-1
for i in range(1,a+1):
    i=a+1-i
    s=""
    ls="  "*(a-i)
    for j in range(1,i+1):
        if i==a or i==1:
            s=s+str(sn)+" "
        else:
            if j==1:
                s=s+str(sn)+" "
            elif 1<j<i:
                s=s+"  "
            else:
                s=s+str(sn)
        sn-=1
    print(ls+s)
a=input()
b=int(input())
b=int(b%7)
if a=="Monday":
    b=b
    if b>7:
        b=int(b%7)
elif a=="Tuesday":
    b=b+1
    if b>7:
        b=int(b%7)
elif a=="Wednesday":
    b=b+2
    if b>7:
        b=int(b%7)
elif a=="Thursday":
    b=b+3
    if b>7:
        b=int(b%7)
elif a=="Friday":
    b=b+4
    if b>7:
        b=int(b%7)
elif a=="Saturday":
    b=b+5
    if b>7:
        b=int(b%7)
elif a=="Sunday":
    b=b+6
    if b>7:
        b=int(b%7)
if b==1:
    print("Monday")
elif b==2:
    print("Tuesday")
elif b==3:
    print("Wednesday")
elif b==4:
    print("Thursday")
elif b==5:
    print("Friday")
elif b==6:
    print("Saturday")
elif b==7:
    print("Sunday")
using av_motion_api.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Net.NetworkInformation;
using System.Reflection.Emit;
using System.Security.Claims;
using System.Xml.Linq;

namespace av_motion_api.Data
{
    public class AppDbContext : IdentityDbContext<User, Role, int>

    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

        //set tables


        public DbSet<Attendance_List> Attendance_Lists { get; set; }
        public DbSet<Audit_Trail> Audit_Trails { get; set; }
        public DbSet<Booking> Bookings { get; set; }
        public DbSet<Booking_Time_Slot> Booking_Time_Slots { get; set; }
        public DbSet<Cart> Carts { get; set; }
        public DbSet<Cart_Item> Cart_Items { get; set; }
        public DbSet<Contract> Contracts { get; set; }
        public DbSet<Contract_History> Contract_History { get; set; }
        public DbSet<Contract_Type> Contract_Types { get; set; }
        public DbSet<DeletionSettings> DeletionSettings { get; set; }
        public DbSet<Discount> Discounts { get; set; }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<Employee_Type> Employee_Types { get; set; }
        public DbSet<Equipment> Equipment { get; set; }
        public DbSet<Inspection> Inspection { get; set; }
        public DbSet<Inspection_Status> Inspection_Status { get; set; }
        public DbSet<Inspection_Type> Inspection_Type { get; set; }
        public DbSet<Inventory> Inventory { get; set; }
        public DbSet<Lesson_Plan> Lesson_Plans { get; set; }

        public DbSet<Lesson_Plan_Workout> lesson_Plan_Workout { get; set; }

        public DbSet<Member> Members { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<Order_Line> Order_Lines { get; set; }
        public DbSet<Order_Status> Order_Status { get; set; }
        public DbSet<Outstanding_Payment> Outstanding_Payments { get; set; }
        public DbSet<Owner> Owners { get; set; }
        public DbSet<Payment> Payments { get; set; }
        public DbSet<Payment_Method> Payment_Methods { get; set; }
        public DbSet<Payment_Type> Payment_Types { get; set; }
        public DbSet<Price> Prices { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<Product_Category> Product_Categories { get; set; }
        public DbSet<Received_Supplier_Order> Received_Supplier_Orders { get; set; }
        public DbSet<Received_Supplier_Order_Line> Received_Supplier_Order_Lines { get; set; }
        public DbSet<Report> Reports { get; set; }
        public DbSet<Reward> Rewards { get; set; }

        public DbSet<Role> Roles { get; set; }
        public DbSet<Reward_Member> Reward_Members { get; set; }
        public DbSet<Reward_Type> Reward_Types { get; set; }
        public DbSet<Shift> Shifts { get; set; }
        public DbSet<Supplier> Suppliers { get; set; }
        public DbSet<Supplier_Order> Supplier_Orders { get; set; }
        public DbSet<Supplier_Order_Line> Supplier_Order_Lines { get; set; }
        public DbSet<Time_Slot> Time_Slots { get; set; }

        public DbSet<User> Users { get; set; }
        public DbSet<User_Status> Users_Status{ get; set; }

        public DbSet<User_Type> User_Types { get; set; }
        public DbSet<VAT> VAT { get; set; }

        public DbSet<Wishlist> Wishlists { get; set; }
        public DbSet<Wishlist_Item> Wishlist_Items { get; set; }

        public DbSet<Workout_Category> Workout_Category { get; set; }
        public DbSet<Workout> Workout { get; set; }
  
        public DbSet<Write_Off> Write_Offs { get; set; }



        protected override void OnModelCreating(ModelBuilder builder)
        {
            //Renaming of Default asp Tables
            builder.Entity<User>().ToTable("Users");
            builder.Entity<IdentityUserRole<int>>().ToTable("User_Roles");
            builder.Entity<IdentityUserLogin<int>>().ToTable("User_Logins");
            builder.Entity<Role>().ToTable("Roles");
            builder.Entity<IdentityRoleClaim<int>>().ToTable("Role_Claims");
            builder.Entity<IdentityUserClaim<int>>().ToTable("User_Claims");
            builder.Entity<IdentityUserToken<int>>().ToTable("Tokens");

            //Validation fix for database, specifying coulm types to be type decimal
            // builder.Entity<Contract>()
            //.Property(c => c.Initial_Fee)
            //.HasColumnType("decimal(18, 2)");

            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);

            builder.Entity<VAT>()
            .Property(v => v.VAT_Percentage)
            .HasColumnType("decimal(18, 2)");

            builder.Entity<Order>()
           .Property(o => o.Total_Price)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Outstanding_Payment>()
           .Property(op => op.Amount_Due)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Outstanding_Payment>()
           .Property(op => op.Late_Fee)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Payment>()
           .Property(pay => pay.Amount)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Price>()
           .Property(pr => pr.Unit_Price)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Product>()
            .Property(p => p.Unit_Price)
            .HasColumnType("decimal(18, 2)"); // Add this line for Unit_Price

            builder.Entity<Product>()
            .Property(p => p.Purchase_Price)
            .HasColumnType("decimal(18, 2)");

            builder.Entity<Supplier_Order>()
           .Property(so => so.Total_Price)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Supplier_Order_Line>()
            .Property(sol => sol.Purchase_Price)
            .HasColumnType("decimal(18, 2)");

            builder.Entity<Supplier_Order_Line>()
            .Property(sol => sol.Unit_Price)
            .HasColumnType("decimal(18, 2)");

            builder.Entity<Discount>()
           .Property(d => d.Discount_Percentage)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Supplier_Order_Line>()
             .HasOne(s => s.Product)
             .WithMany()
             .HasForeignKey(s => s.Product_ID)
             .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Order_Line>()
           .Property(ol => ol.Unit_Price)
           .HasColumnType("decimal(18,2)");

            //Delete cascade error fix
            //builder.Entity<Payment>()
            //.HasOne(p => p.Payment_Type)
            //.WithMany()
            //.HasForeignKey(p => p.Payment_Type_ID)
            //.OnDelete(DeleteBehavior.NoAction);

            //builder.Entity<Supplier_Order_Line>()
            //.HasOne(s => s.Supplier)
            //.WithMany()
            //.HasForeignKey(s => s.Supplier_ID)
            //.OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Received_Supplier_Order_Line>()
                .HasOne(r => r.Received_Supplier_Order)
                .WithMany(r => r.Received_Supplier_Order_Lines)  // Assuming Received_Supplier_Order has a collection of Received_Supplier_Order_Lines
                .HasForeignKey(r => r.Received_Supplier_Order_ID)
                .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Received_Supplier_Order_Line>()
                .HasOne(r => r.Supplier_Order_Line)
                .WithMany()  // Assuming Supplier_Order_Line does not need a navigation property for Received_Supplier_Order_Lines
                .HasForeignKey(r => r.Supplier_Order_Line_ID)
                .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Received_Supplier_Order_Line>()
                .HasOne(r => r.Product)
                .WithMany()  // Assuming Product does not need a navigation property for Received_Supplier_Order_Lines
                .HasForeignKey(r => r.Product_ID)
                .OnDelete(DeleteBehavior.NoAction);


            //builder.Entity<Received_Supplier_Order_Line>()
            //.HasOne(r => r.Product)
            //.WithMany()
            //.HasForeignKey(r => r.Product_ID)
            //.OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Outstanding_Payment>()
            .HasOne(op => op.Member)
            .WithMany()
            .HasForeignKey(op => op.Member_ID)
            .OnDelete(DeleteBehavior.NoAction); 

            builder.Entity<Outstanding_Payment>()
            .HasOne(op => op.Payment)
            .WithMany()
            .HasForeignKey(op => op.Payment_ID)
            .OnDelete(DeleteBehavior.NoAction);


            builder.Entity<Booking>()
            .HasOne(b => b.Member)
            .WithMany()
            .HasForeignKey(b => b.Member_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Reward_Member>()
            .HasOne(rm => rm.Member)
            .WithMany()
            .HasForeignKey(rm => rm.Member_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Reward_Member>()
            .HasOne(rm => rm.Reward)
            .WithMany()
            .HasForeignKey(rm => rm.Reward_ID)
            .OnDelete(DeleteBehavior.NoAction);

           builder.Entity<Booking_Time_Slot>()
            .HasOne(bts => bts.Booking)
            .WithMany()
            .HasForeignKey(bts => bts.Booking_ID)
            .OnDelete(DeleteBehavior.NoAction);

           builder.Entity<Booking_Time_Slot>()
            .HasOne(bts => bts.Time_Slot)
            .WithMany()
            .HasForeignKey(bts => bts.Time_Slot_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Attendance_List>()
            .HasOne(b => b.Time_Slot)
            .WithMany()
            .HasForeignKey(b => b.Time_Slot_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Lesson_Plan_Workout>()
            .HasOne(lpw => lpw.Workout)
            .WithMany()
            .HasForeignKey(lpw => lpw.Workout_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Lesson_Plan_Workout>()
            .HasOne(lpw => lpw.Lesson_Plan)
            .WithMany()
            .HasForeignKey(lpw => lpw.Lesson_Plan_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Workout>()
           .HasOne(w => w.Workout_Category)
           .WithMany()
           .HasForeignKey(w => w.Workout_Category_ID)
           .IsRequired()
           .OnDelete(DeleteBehavior.Restrict);

            base.OnModelCreating(builder);



            //var Contract_Types = new Contract_Type[]
            //{
            //    new Contract_Type { Contract_Type_ID = 1, Contract_Type_Name = "3-Month Membership", Contract_Description = "Three-month gym membership contract" },              
            //};
            //builder.Entity<Contract_Type>().HasData(Contract_Types);



            var Discounts = new Discount[]
            {
                new Discount
                {
                    Discount_ID = 1,
                    Discount_Code = "SPR-123",
                    Discount_Percentage = 10.00m,
                    Discount_Date = new DateTime(2024, 4, 10),
                    End_Date = new DateTime(2024, 4, 10).AddDays(30)
                }
            };
            builder.Entity<Discount>().HasData(Discounts);


            //var Employee_Types = new Employee_Type[]
            //{
            //    new Employee_Type { Employee_Type_ID = 1, Job_Title = "Administrator", Job_Description = "Responsible for managing administrative tasks and operations" }
            //};
            //builder.Entity<Employee_Type>().HasData(Employee_Types);

            var Inspection_Statuses = new Inspection_Status[]
            {
                new Inspection_Status { Inspection_Status_ID = 1, Inspection_Status_Description= "Pending" }


            };
            builder.Entity<Inspection_Status>().HasData(Inspection_Statuses);

            var Inspection_Types = new Inspection_Type[]
            {
                new Inspection_Type { Inspection_Type_ID = 1, Inspection_Type_Name = "Safety Inspection", Inspection_Type_Criteria = "Ensure compliance with safety standards" }
    
            };
            builder.Entity<Inspection_Type>().HasData(Inspection_Types);

            var Membership_Statuses = new Membership_Status[]
            {
                new Membership_Status { Membership_Status_ID = 1, Membership_Status_Description = "Active" }

            };
            builder.Entity<Membership_Status>().HasData(Membership_Statuses);

            var Newsletters = new Newsletter[]
            {
                new Newsletter { Newsletter_ID = 1, Newsletter_Title = "Fitness Tips", Newsletter_Photo = "fitness_tips.jpg", Newsletter_Description = "Stay updated with our latest fitness tips!" }

            };
            builder.Entity<Newsletter>().HasData(Newsletters);

            //var Payment_Methods = new Payment_Method[]
            //{
            //    new Payment_Method { Payment_Method_ID = 1, Payment_Method_Name = "Payfast" }  
            //};
            //builder.Entity<Payment_Method>().HasData(Payment_Methods);

            var Payment_Types = new Payment_Type[]
            {
                new Payment_Type { Payment_Type_ID = 1, Payment_Type_Name = "Payfast" },
                new Payment_Type { Payment_Type_ID = 2, Payment_Type_Name = "EFT" },
                new Payment_Type { Payment_Type_ID = 3, Payment_Type_Name = "Debit Order" }

            };
            builder.Entity<Payment_Type>().HasData(Payment_Types);

            var ProductCategories = new Product_Category[]
            {
                new Product_Category { Product_Category_ID = 1, Category_Name = "Tops", Category_Description = "Gym Tops" },
                new Product_Category { Product_Category_ID = 2, Category_Name = "Bottoms", Category_Description = "Gym Bottoms" }
            };

            builder.Entity<Product_Category>().HasData(ProductCategories);

            var Reports = new Report[]
            {
                new Report { Report_ID = 1, Report_Name = "Monthly Sales Report", Report_Description = "Report summarizing monthly sales data", Generated_Date = new DateTime(2024, 4, 10) }
            };
            builder.Entity<Report>().HasData(Reports);

            var Reward_Types = new Reward_Type[]
            {
                new Reward_Type { Reward_Type_ID = 1, Reward_Type_Name = "Membership Renewal Discount", Reward_Criteria = "Receive a discount on membership renewal after completing a certain number of workouts" }

            };
            builder.Entity<Reward_Type>().HasData(Reward_Types);

            var Suppliers = new Supplier[]
            {
                new Supplier { Supplier_ID = 1, Name = "FitnessGear", Contact_Number = "1234567890", Email_Address = "info@fitnessgear.com", Physical_Address = "123 Fitness Street, Cityville, South Africa" }
            };
            builder.Entity<Supplier>().HasData(Suppliers);


            var userStatus = new User_Status[]
            {
                new User_Status { User_Status_ID = 1, User_Status_Description = "Actived" },
                new User_Status { User_Status_ID = 2, User_Status_Description = "Deactivated" }
            };
            builder.Entity<User_Status>().HasData(userStatus);

            var userTypes = new User_Type[]
    {
                new User_Type { User_Type_ID = 1, User_Type_Name = "Owner" },
                new User_Type { User_Type_ID = 2, User_Type_Name = "Employee" },
                new User_Type { User_Type_ID = 3, User_Type_Name = "Member" }
    };
            builder.Entity<User_Type>().HasData(userTypes);



        //    var Users = new User[]                
        //    {
        //        new User 
        //        {
        //            User_ID = 1,
        //            Id = 1,
        //            Name = "Don",
        //            Surname = "Percival",
        //            ID_Number = "0203057644931",
        //            Email = "DonPercival@gmail.com",
        //            Physical_Address = "456 Oak Avenue",
        //            PhoneNumber = "0734457681",
        //            Photo = "DonProfilePic.jpg",
        //            PasswordHash = "AEWR54Q35H5T4HRGRGQ",
        //            Date_of_Birth = new DateTime(1994,10,11),
        //            User_Type_ID =1,
        //            User_Status_ID =1
        //        },
        //        new User
        //        {
        //            User_ID = 2,
        //            Id = 2,
        //            Name = "Barbra",
        //            Surname = "Gordon",
        //            ID_Number = "1220231231312",
        //            Email = "barbragordon@gmail.com",
        //            Physical_Address = "456 Oak Avenue",
        //            PhoneNumber = "9876543210",
        //            Photo = "barbra_photo.jpg",
        //            PasswordHash = "HJDKL3948SJDF3JSHFD",
        //            Date_of_Birth = new DateTime(1985, 5, 15),
        //            User_Type_ID =2,
        //            User_Status_ID =1
        //        },

        //        new User

        //        {
        //        User_ID = 3,
        //        Id = 3,
        //        Name = "Jane",
        //        Surname = "Smith",
        //        ID_Number = "1220231231312",
        //        Email = "JaneSmith@gmail.com",
        //        Physical_Address = "456 Oak Avenue",
        //        PhoneNumber = "9876543210",
        //        Photo = "jane_smith_photo.jpg",    
        //        PasswordHash = "JKLFSF34JKLRE983JFSD",
        //        Date_of_Birth = new DateTime(1985, 5, 15),
        //        User_Type_ID =3,
        //        User_Status_ID =1
        //        }


        //    };
        //builder.Entity<User>().HasData(Users);








            //var Contracts = new Contract[]
            //{
            //   new Contract { Contract_ID = 1, Subscription_Date = new DateTime(2023, 1, 1), Expiry_Date = new DateTime(2023, 4, 1), Terms_Of_Agreement = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", Approval_Status = true, Approval_Date = new DateTime(2023, 1, 1), Initial_Fee = 100.00m, Contract_Type_ID = 1, Payment_Type_ID = 1 }
            //};
            //builder.Entity<Contract>().HasData(Contracts);


            //var ContractHistories = new Contract_History[]
            //{
            //    new Contract_History { Contract_History_ID = 1, Modification_Date = new DateTime(2023, 5, 15), Previous_Terms = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", Updated_Terms = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut enim ad minim veniam.", Reasons_For_Changes = "To include additional benefits for members.", Contract_ID = 1 },

            //};
            //builder.Entity<Contract_History>().HasData(ContractHistories);



            var VAT = new VAT[]
            {
               new VAT { VAT_ID = 1, VAT_Percentage = 15.00m, VAT_Date = new DateTime(2024, 1, 1) }
            };
            builder.Entity<VAT>().HasData(VAT);


            var Audit_Trails = new Audit_Trail[]
            {
                new Audit_Trail { Audit_Trail_ID = 1, Action = "Action description", Timestamp = DateTime.Now }

            };
            builder.Entity<Audit_Trail>().HasData(Audit_Trails);

            var shifts = new List<Shift>();

            // Default shift (placeholder)
            int defaultShiftId = 1;
            shifts.Add(new Shift
            {
                Shift_ID = defaultShiftId,
                Shift_Number = defaultShiftId,
                Start_Time = new TimeSpan(0, 0, 0),
                End_Time = new TimeSpan(0, 0, 0)
            });

            // Weekdays (Monday - Friday) shifts
            var startTime = new TimeSpan(6, 0, 0);
            var endTime = new TimeSpan(22, 0, 0);
            int shiftId = defaultShiftId + 1; // Start after the default shift ID

            while (startTime < endTime)
            {
                shifts.Add(new Shift
                {
                    Shift_ID = shiftId,
                    Shift_Number = shiftId,
                    Start_Time = startTime,
                    End_Time = startTime.Add(new TimeSpan(2, 0, 0))
                });
                startTime = startTime.Add(new TimeSpan(2, 0, 0));
                shiftId++;
            }

            // Saturday shifts
            startTime = new TimeSpan(6, 0, 0);
            endTime = new TimeSpan(20, 0, 0);

            while (startTime < endTime)
            {
                shifts.Add(new Shift
                {
                    Shift_ID = shiftId,
                    Shift_Number = shiftId,
                    Start_Time = startTime,
                    End_Time = startTime.Add(new TimeSpan(2, 0, 0))
                });
                startTime = startTime.Add(new TimeSpan(2, 0, 0));
                shiftId++;
            }

            // Sunday shifts
            startTime = new TimeSpan(6, 0, 0);
            endTime = new TimeSpan(14, 0, 0);

            while (startTime < endTime)
            {
                shifts.Add(new Shift
                {
                    Shift_ID = shiftId,
                    Shift_Number = shiftId,
                    Start_Time = startTime,
                    End_Time = startTime.Add(new TimeSpan(2, 0, 0))
                });
                startTime = startTime.Add(new TimeSpan(2, 0, 0));
                shiftId++;
            }

            builder.Entity<Shift>().HasData(shifts);


            //var Employees = new Employee[]
            //{
            //   new Employee { Employee_ID = 1, Employment_Date = new DateTime(2024, 4, 12), Employee_Type_ID = 1 , Shift_ID =1, User_ID = 2 }
            //};
            //builder.Entity<Employee>().HasData(Employees);


            //var Members = new Member[]
            //{
            //   new Member { Member_ID = 1, Contract_ID = 1,User_ID = 3 }
               
            //};
            //builder.Entity<Member>().HasData(Members);


            //var AttendanceLists = new Attendance_List[]
            //{

            //    new Attendance_List { Attendance_ID = 1, Number_Of_Bookings = 1, Members_Present = 10, Members_Absent = 5, Time_Slot_ID = 1}
            //};
            //builder.Entity<Attendance_List>().HasData(AttendanceLists);


            //var Bookings = new Booking[]
            //{
            //    new Booking { Booking_ID = 1,  Member_ID = 1}
            //};
            //builder.Entity<Booking>().HasData(Bookings);

            var employeeTypes = new Employee_Type[]
            {
                new Employee_Type
                {
                    Employee_Type_ID = 1,
                    Job_Title = "Admin",
                    Job_Description = "Manages administrative tasks and oversees operations."
                },
                new Employee_Type
                {
                    Employee_Type_ID = 2,
                    Job_Title = "Trainer",
                    Job_Description = "Provides training and fitness guidance to members."
                }
            };
            builder.Entity<Employee_Type>().HasData(employeeTypes);

            var workoutcategories = new Workout_Category[]
            {
                new Workout_Category { Workout_Category_ID = 1, Workout_Category_Name = "Cardio", Workout_Category_Description = "Cardio workouts to improve endurance and burn calories." },
                new Workout_Category { Workout_Category_ID = 2, Workout_Category_Name = "Strength", Workout_Category_Description = "Strength training workouts to build muscle and increase strength." },
                new Workout_Category { Workout_Category_ID = 3, Workout_Category_Name = "Flexibility", Workout_Category_Description = "Flexibility workouts to improve range of motion and reduce injury risk." }
            };
            builder.Entity<Workout_Category>().HasData(workoutcategories);


            var workouts = new Workout[]
            {
                    new Workout
                    {
                        Workout_ID = 1,
                        Workout_Name = "Cardio Blast",
                        Workout_Description = "High-intensity cardio workout to burn calories and improve endurance.",
                        Sets = 4,
                        Reps = 10,
                        Workout_Category_ID = 1
                    },
                    new Workout
                    {
                        Workout_ID = 2,
                        Workout_Name = "Strength Training",
                        Workout_Description = "Build muscle strength and endurance.",
                        Sets = 3,
                        Reps = 12,
                        Workout_Category_ID = 2
                    },
                    new Workout
                    {
                        Workout_ID = 3,
                        Workout_Name = "Flexibility Routine",
                        Workout_Description = "Improve your flexibility with this stretching routine.",
                        Sets = 2,
                        Reps = 15,
                        Workout_Category_ID = 3
                    }
            };
            builder.Entity<Workout>().HasData(workouts);


            var Lesson_Plans = new Lesson_Plan[]
            {
                new Lesson_Plan { Lesson_Plan_ID = 1, Program_Name = "Base", Program_Description = "Base program description", }

            };
            builder.Entity<Lesson_Plan>().HasData(Lesson_Plans);


            var orderStatuses = new Order_Status[]
            {
                new Order_Status { Order_Status_ID = 1, Order_Status_Description = "Ready for Collection" },
                new Order_Status { Order_Status_ID = 2, Order_Status_Description = "Overdue for Collection" },
                new Order_Status { Order_Status_ID = 3, Order_Status_Description = "Collected" },
                new Order_Status { Order_Status_ID = 4, Order_Status_Description = "Late Collection" }
            };
            builder.Entity<Order_Status>().HasData(orderStatuses);


            //var Orders = new Order[]
            //{
            //   new Order { Order_ID = 1, Order_Date = new DateTime(2024, 4, 12), Order_Details = "Example order details", Total_Price = 100.00m, Member_ID = 1, Order_Status_ID = 1 }
            //};
            //builder.Entity<Order>().HasData(Orders);


            //var Outstanding_Payments = new Outstanding_Payment[]
            //{
            //   new Outstanding_Payment { Outstanding_Payment_ID = 1, Due_Date = new DateTime(2024, 4, 12), Amount_Due = 50.00m, Late_Fee = 0.00m, Member_ID = 1, Payment_ID = 1 }
            //};
            //builder.Entity<Outstanding_Payment>().HasData(Outstanding_Payments);


            //var Owners = new Owner[]
            //{
            //   new Owner { Owner_ID = 1, User_ID = 1 }
            //};
            //builder.Entity<Owner>().HasData(Owners);



            //var Payments = new Payment[]
            //{
            //  new Payment { Payment_ID = 1, Amount = 50.00m, Payment_Date = new DateTime(2024, 4, 12) }
            //};
            //builder.Entity<Payment>().HasData(Payments);



            //var Products = new Product[]
            //{
            //    new Product { Product_ID = 1, Product_Name = "Gym T-Shirt", Product_Description = "Breathable cotton gym shirt", Product_Img = "gym_tshirt.jpg", Quantity = 50, Unit_Price = 19.99M, Size = "XS", Product_Category_ID = 1, Supplier_ID = 1 },
            //    new Product { Product_ID = 2, Product_Name = "Running Shorts", Product_Description = "Lightweight running shorts", Product_Img = "running_shorts.jpg", Quantity = 40, Unit_Price = 24.99M, Size = "M", Product_Category_ID = 2, Supplier_ID = 1 },
            //    new Product { Product_ID = 3, Product_Name = "Hoodie", Product_Description = "Fleece-lined gym hoodie", Product_Img = "hoodie.jpg", Quantity = 30, Unit_Price = 39.99M, Size = "L", Product_Category_ID = 2, Supplier_ID = 1 },
            //    new Product { Product_ID = 4, Product_Name = "Compression Tights", Product_Description = "High-performance compression tights", Product_Img = "compression_tights.jpg", Quantity = 60, Unit_Price = 29.99M, Size = "S", Product_Category_ID = 2, Supplier_ID = 1 },
            //    new Product { Product_ID = 5, Product_Name = "Gym Tank Top", Product_Description = "Sleeveless tank for workouts", Product_Img = "tank_top.jpg", Quantity = 70, Unit_Price = 15.99M, Size = "M", Product_Category_ID = 1, Supplier_ID = 1 },
            //    new Product { Product_ID = 6, Product_Name = "Sweatpants", Product_Description = "Comfortable gym sweatpants", Product_Img = "sweatpants.jpg", Quantity = 50, Unit_Price = 25.99M, Size = "L", Product_Category_ID = 2, Supplier_ID = 1 },
            //    new Product { Product_ID = 7, Product_Name = "Sports Bra", Product_Description = "Supportive sports bra", Product_Img = "sports_bra.jpg", Quantity = 40, Unit_Price = 19.99M, Size = "S", Product_Category_ID = 1, Supplier_ID = 1 },
            //    new Product { Product_ID = 8, Product_Name = "Gym Leggings", Product_Description = "High-waisted gym leggings", Product_Img = "gym_leggings.jpg", Quantity = 60, Unit_Price = 34.99M, Size = "M", Product_Category_ID = 2, Supplier_ID = 1 }
            //};

            //builder.Entity<Product>().HasData(Products);


            //var prices = new Price[]
            //{
            //    new Price { Price_ID = 1, Unit_Price = 50.00m, Product_ID = 1 }
            //};
            //builder.Entity<Price>().HasData(prices);


            //var OrderLines = new Order_Line[]
            //{
            //    new Order_Line { Order_Line_ID = 1, Order_ID = 1, Product_ID = 1 }

            //};
            //builder.Entity<Order_Line>().HasData(OrderLines);


            //var Received_Supplier_Orders = new Received_Supplier_Order[]
            //{
            //    new Received_Supplier_Order { Received_Supplier_Order_ID = 1, Supplies_Received_Date = new DateTime(20, 04, 10) }
            //};

            //builder.Entity<Received_Supplier_Order>().HasData(Received_Supplier_Orders);



            //var Received_Supplier_Order_Lines = new Received_Supplier_Order_Line[]
            //{
            //    new Received_Supplier_Order_Line { Received_Supplier_Order_Line_ID = 1,Received_Supplier_Order_ID = 1,Supplier_Order_ID = 1,Product_ID = 1,Received_Supplies_Quantity = 10 }
            //};

            //builder.Entity<Received_Supplier_Order_Line>().HasData(Received_Supplier_Order_Lines);

            var Rewards = new Reward[]
            {
                new Reward { Reward_ID = 1, IsPosted = false, Reward_Issue_Date = new DateTime(2024, 4, 10), Reward_Type_ID = 1 }

            };
            builder.Entity<Reward>().HasData(Rewards);

            //var Reward_Members = new Reward_Member[]
            //{
            //    new Reward_Member{ Reward_Member_ID = 1, IsRedeemed = false, Member_ID = 1, Reward_ID = 1}
            //};
            //builder.Entity<Reward_Member>().HasData(Reward_Members);

            var Roles = new Role[]
            {
                new Role{ Id = 1, Name = "Owner", NormalizedName= "OWNER", isEditable = false},
                new Role{ Id = 2, Name = "Employee", NormalizedName= "EMPLOYEE", isEditable =true},
                new Role{ Id = 3, Name = "Member", NormalizedName= "MEMBER", isEditable =true}
            };
            builder.Entity<Role>().HasData(Roles);


            int claimId = 1;
            //Owner Claims
            //for each admin claim
            var ownerClaims = new Claim[]

            {
                new Claim("Booking Manager", "Create"),
                new Claim("Booking Manager", "Read"),
                new Claim("Booking Manager", "Update"),
                new Claim("Booking Manager", "Delete"),

                new Claim("Equipment Manager", "Create"),
                new Claim("Equipment Manager", "Read"),
                new Claim("Equipment Manager", "Update"),
                new Claim("Equipment Manager", "Delete"),

                new Claim("Employee Manager", "Create"),
                new Claim("Employee Manager", "Read"),
                new Claim("Employee Manager", "Update"),
                new Claim("Employee Manager", "Delete"),

                new Claim("Inventory Manager", "Create"),
                new Claim("Inventory Manager", "Read"),
                new Claim("Inventory  Manager", "Update"),
                new Claim("Inventory Manager", "Delete"),

                new Claim("Gym Manager", "Create"),
                new Claim("Gym Manager", "Read"),
                new Claim("Gym  Manager", "Update"),
                new Claim("Gym Manager", "Delete"),
            };
            //create a refrence of it in the Role Claims table
            foreach (var claim in ownerClaims) 
            {
                builder.Entity<IdentityRoleClaim<int>>().HasData(new IdentityRoleClaim<int>
                { 
                   Id = claimId++,
                   RoleId = Roles[0].Id,
                   ClaimType = claim.Type,
                   ClaimValue = claim.Value
                });
            }

            //Employee Claims , they are admin too but just for separation        
            //for each employee claim
            var employeeClaims = new Claim[]
            {
                new Claim("Booking Manager", "Create"),
                new Claim("Booking Manager", "Read"),
                new Claim("Booking Manager", "Update"),
                new Claim("Booking Manager", "Delete"),

                new Claim("Equipment Manager", "Create"),
                new Claim("Equipment Manager", "Read"),
                new Claim("Equipment Manager", "Update"),
                new Claim("Equipment Manager", "Delete"),

                new Claim("Employee Manager", "Read"),
                new Claim("Employee Manager", "Update"),

                new Claim("Inventory Manager", "Create"),
                new Claim("Inventory Manager", "Read"),
                new Claim("Inventory Manager", "Update"),
                new Claim("Inventory Manager", "Delete"),
            };
            //create a refrence of it in the Role Claims table
            foreach (var claim in employeeClaims)
            {
                builder.Entity<IdentityRoleClaim<int>>().HasData(new IdentityRoleClaim<int>
                {
                    Id = claimId++,
                    RoleId = Roles[1].Id,
                    ClaimType = claim.Type,
                    ClaimValue = claim.Value
                });
            }

            var memberClaims = new Claim[]
            {
                new Claim("Booking Interface", "Create"),
                new Claim("Booking Interface", "Read"),
                new Claim("Booking Interface", "Update"),
                new Claim("Booking Interface", "Delete"),

                new Claim("Profile", "Create"),
                new Claim("Profile", "Read"),
                new Claim("Profile", "Update"),

            };
            //create a refrence of it in the Role Claims table
            foreach (var claim in memberClaims)
            {
                builder.Entity<IdentityRoleClaim<int>>().HasData(new IdentityRoleClaim<int>
                {
                    Id = claimId++,
                    RoleId = Roles[2].Id,
                    ClaimType = claim.Type,
                    ClaimValue = claim.Value
                });
            }

            //var Supplier_Orders = new Supplier_Order[]
            //{
            //    new Supplier_Order { Supplier_Order_ID = 1, Date = new DateTime(2024, 4, 10), Supplier_Order_Details = "Ordered 50 units of dumbbells and 20 yoga mats", Total_Price = 1500.00m, Supplier_ID = 1, Owner_ID = 1 }

            //};
            //builder.Entity<Supplier_Order>().HasData(Supplier_Orders);

            //var Supplier_Order_Lines = new Supplier_Order_Line[]
            //{
            //    new Supplier_Order_Line { Supplier_Order_Line_ID = 1, Supplier_Qauntity = 12, Supplier_ID = 1, Product_ID = 1 }

            //};
            //builder.Entity<Supplier_Order_Line>().HasData(Supplier_Order_Lines);

            //var Inventory = new Inventory[]
            //{
            //    new Inventory { Inventory_ID = 1, Inventory_Item_Category = "Clothes", Inventory_Item_Name = "Men's Dry-fit Tops", Inventory_Item_Quantity = 20, Inventory_Item_Photo = "dry_fit_tops.jpg", Received_Supplier_Order_ID = 1, Supplier_ID = 1 }

            //};
            //builder.Entity<Inventory>().HasData(Inventory);

            var Equipments = new Equipment[]
            {
                
                 new Equipment{ Equipment_ID = 1, Equipment_Name = "Treadmill", Equipment_Description = "A motorized device used for running or walking while staying in one place." }
                
            };
            builder.Entity<Equipment>().HasData(Equipments);

            var Inspections = new Inspection[]
            {
                new Inspection { Inspection_ID = 1, Inspection_Date = new DateTime(2024, 4, 12),Inspection_Notes = "Holes in AVS pants" , Equipment_ID = 1,  Inspection_Type_ID = 1, Inspection_Status_ID = 1 }

            };
            builder.Entity<Inspection>().HasData(Inspections);

            var Booking_Time_Slots = new Booking_Time_Slot[]
            {
                new Booking_Time_Slot{Booking_Time_Slot_ID = 1, Booking_ID = 1,Time_Slot_ID = 1}
            };
            builder.Entity<Booking_Time_Slot>();


            //var Time_Slots = new Time_Slot[]
            //{

            //    new Time_Slot{Time_Slot_ID = 1,Slot_Date =  new DateTime(2024, 4, 12)  , Slot_Time = DateTime.Parse("11:00:00"), Availability = true, Lesson_Plan_ID= 1, Employee_ID=1}

            //};
            //builder.Entity<Time_Slot>().HasData(Time_Slots);


            //var Write_Offs = new Write_Off[]
            //{
            //    new Write_Off { Write_Off_ID = 1, Date = new DateTime(2024, 4, 12), Write_Off_Reason = "Expired items", Inventory_ID = 1 }

            //};
            //builder.Entity<Write_Off>().HasData(Write_Offs);


            var lessonPlanWorkOuts = new Lesson_Plan_Workout[]
            {
                new Lesson_Plan_Workout {Lesson_Plan_Workout_ID =1, Lesson_Plan_ID = 1, Workout_ID = 1}
            };
            builder.Entity<Lesson_Plan_Workout>().HasData(lessonPlanWorkOuts);

        }

    }
}

$("[data-lenis-start]").on("click", function () {
  lenis.start();
});
$("[data-lenis-stop]").on("click", function () {
  lenis.stop();
});
$("[data-lenis-toggle]").on("click", function () {
  $(this).toggleClass("stop-scroll");
  if ($(this).hasClass("stop-scroll")) {
    lenis.stop();
  } else {
    lenis.start();
  }
});
<script src="https://cdn.jsdelivr.net/gh/studio-freight/lenis@1.0.23/bundled/lenis.min.js"></script> 
<script>
// LENIS SMOOTH SCROLL
let lenis;
if (Webflow.env("editor") === undefined) {
  lenis = new Lenis({
    lerp: 0.1,
    wheelMultiplier: 0.7,
    gestureOrientation: "vertical",
    normalizeWheel: false,
    smoothTouch: false
  });
  function raf(time) {
    lenis.raf(time);
    requestAnimationFrame(raf);
  }
  requestAnimationFrame(raf);
}
</script>
<script src="https://cdn.jsdelivr.net/gh/studio-freight/lenis@1.0.23/bundled/lenis.min.js"></script> 
<script>
// LENIS SMOOTH SCROLL
let lenis;
if (Webflow.env("editor") === undefined) {
  lenis = new Lenis({
    lerp: 0.1,
    wheelMultiplier: 0.7,
    gestureOrientation: "vertical",
    normalizeWheel: false,
    smoothTouch: false
  });
  function raf(time) {
    lenis.raf(time);
    requestAnimationFrame(raf);
  }
  requestAnimationFrame(raf);
}
</script>
<style>
html.lenis {
  height: auto;
}
.lenis.lenis-smooth {
  scroll-behavior: auto;
}
.lenis.lenis-smooth [data-lenis-prevent] {
  overscroll-behavior: contain;
}
.lenis.lenis-stopped {
  overflow: hidden;
}
</style>
@extends('new_layouts.app')
@section('styles')
    <style>
        .modal-icon {
            font-size: 3rem;
            color: #dc3545;
        }

        .modal-body {
            padding: 2rem;
        }

        .modal-title {
            font-size: 1.25rem;
            margin-top: 1rem;
        }

        .modal-body p {
            font-size: 1rem;
            margin-top: 0.5rem;
        }

        .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>
            <div class="d-flex flex-column">
                <h1>Title: {{ $material->title }}</h1>
                @if ($material->description)
                    <p class="description-text"><strong>Description:</strong> {{ $material->description }}</p>
                @endif
            </div>

            <div class="d-flex justify-content-end mb-4">
                <a class="btn rounded-3" style="background-color: #4CAF50; color: white"
                    href="{{ route('materials.downloadAll', $material) }}">
                    <i class="fas fa-download me-1"></i> Download All
                </a>
            </div>

            <div class="table-responsive">
                <table class="table table-striped custom-table">
                    <thead>
                        <tr>
                            <th scope="col">Bookmarks</th>
                            <th scope="col">Document</th>
                            <th scope="col">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($files as $file)
                            <tr>
                                <td>
                                    @php
                                        $isBookmarked = $file->bookmarks()->where('user_id', Auth::id())->exists();
                                    @endphp
                                    <button type="button"
                                        class="btn btn-outline-dark bookmark-toggle {{ $isBookmarked ? 'bookmark-active' : '' }}"
                                        data-file-id="{{ $file->id }}">
                                        @if ($isBookmarked)
                                            <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
                                            <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>
                                        @endif
                                        <span class="visually-hidden">Button</span>
                                    </button>
                                </td>
                                <td>
                                    <div>
                                        @php
                                            $extension = pathinfo($file->name, PATHINFO_EXTENSION);
                                        @endphp
                                        <i class="fa-solid fa-file-lines" style="color: #0068b8; margin-right: 5px;"></i>
                                        <a href="{{ Storage::url($file->path) }}" target="_blank">
                                            {{ pathinfo($file->name, PATHINFO_FILENAME) }}
                                        </a>
                                        <span>
                                            <span class="badge badge-file-extension">
                                                {{ strtoupper($extension) }} File
                                            </span>
                                        </span>
                                    </div>
                                </td>
                                <td>
                                    <a class="btn btn-primary rounded-pill" href="{{ Storage::url($file->path) }}" download>
                                        <i class="fas fa-download me-1"></i> Download
                                    </a>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>


        <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="reply-form-error" class="text-danger"></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="reply-form-error" class="text-danger"></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>
    <!-- delete model -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body text-center">
                    <div class="mb-3">
                        <i class="fa-solid fa-triangle-exclamation modal-icon"></i>
                    </div>
                    <h5 class="modal-title" id="deleteModalLabel">Delete Comment</h5>
                    <p>Are you sure you want to delete this comment?</p>
                </div>
                <div class="modal-footer d-flex justify-content-center">
                    <button type="button" class="btn btn-danger ms-2" id="confirmDelete">Delete</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>
@endsection


@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const commentForm = document.getElementById('comment-form');
            const replyForms = document.querySelectorAll('.reply-form');

            commentForm.addEventListener('submit', function(e) {
                const content = this.querySelector('textarea[name="content"]').value.trim();
                if (content === '') {
                    e.preventDefault();
                    document.getElementById('comment-form-error').innerText =
                        'Error: Comment cannot be empty';
                }
            });

            replyForms.forEach(function(replyForm) {
                replyForm.addEventListener('submit', function(e) {
                    const content = this.querySelector('textarea[name="content"]').value.trim();
                    if (content === '') {
                        e.preventDefault();
                        this.querySelector('#reply-form-error').innerText =
                            'Error: Reply cannot be empty';
                    }
                });
            });

            const commentList = document.getElementById('comment-list');

            // Handle edit button click
            commentList.addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="edit"]');
                if (button) {
                    event.preventDefault();
                    const commentId = button.getAttribute('data-comment-id');
                    const commentElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"]`);
                    const commentBodyElement = commentElement.querySelector('.comment-body');

                    // Extract mention and content
                    const mentionElement = commentBodyElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const contentElement = mentionElement ? mentionElement.nextElementSibling :
                        commentBodyElement;
                    const content = contentElement.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>
                            <div class="d-flex justify-content-between mt-2">
                                <div id="edit-comment-form-error" class="text-danger"></div>
                                <div>
                                    <button type="submit" class="btn btn-primary">Save</button>
                                    <button type="button" class="btn btn-secondary cancel-edit">Cancel</button>
                                </div>
                            </div>
                        </form>
                    `;

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

            function attachEditFormListeners(commentId) {
                const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);

                editForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const textarea = this.querySelector('textarea');
                    const content = textarea.value.trim();
                    const mention = this.querySelector('.reply-mention') ? this.querySelector(
                        '.reply-mention').innerText.trim() : '';

                    if (content === '') {
                        this.querySelector('#edit-comment-form-error').innerText =
                            'Error: Comment cannot be empty';
                        return;
                    }

                    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);
                        });
                });

                editForm.querySelector('.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');
                    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));

                    document.getElementById('confirmDelete').onclick = function() {
                        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();
                                    }
                                    deleteModal.hide();
                                } else {
                                    alert(data.message || 'Error deleting comment');
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                alert('Something went wrong');
                            });
                    };

                    deleteModal.show();
                }
            });


            // 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" style="display: none;">
                                            @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="#" class="reply-mention">@${data.reply.parent_name}</a> ` : ''}
                                                <span class="reply-content">${data.reply.content}</span>
                                            </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" style="display: none;">
                                                @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();
                                    form.style.display =
                                        'none'; 

                                    // Ensure the replies are displayed
                                    const replyToggle = form.closest('.comment').querySelector(
                                        '.reply-toggle');
                                    if (replyToggle) {
                                        const replyList = replyToggle.nextElementSibling
                                            .nextElementSibling;
                                        replyList.style.display = 'block';
                                        replyToggle.textContent = 'Hide replies';
                                    }

                                    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
Embark on a lucrative journey with our turnkey vacation rental business – your golden ticket to making money while providing unforgettable travel experiences! Just like Airbnb, We at Appticz develop a vacation rental business that empowers you to transform your property into a revenue-generating oasis. Imagine waking up to a stream of bookings and delighted guests, all while enjoying the financial rewards of the booming vacation rental market. Get a free airbnb clone business quotation.
https://appticz.com/airbnb-clone
app.get('/auth/google',
  passport.authenticate('google', { scope: [ 'email', 'profile' ]
}));
app.get('/auth/google/callback', passport.authenticate( 'google', {
   successRedirect: '/dashboard',
   failureRedirect: '/login'
}));
1: Using Control Panel
control panel - programs - turn windows features on or off

2: Using the Command Prompt (admin)
bcdedit /set hypervisorlaunchtype off

The DISM Command
cmd (admin)
dism /online /disable-feature /featurename:Microsoft-hyper-v-all

3: Using PowerShell (admin)
Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All

4: Using BIOS
Configuration tab (or such - check)
select the Virtualization Technology - disable






echo var_export(something) die();
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler,StandardScaler,OneHotEncoder
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer

#Set Seed for reproducability
np.random.seed(42)
#Create synthetic dataset 
data={
    'Age':np.random.randint(29,77,size=200),
    'Sex':np.random.choice(['Male','Female'],size=200),
    'ChestPainType':np.random.choice(['ATA','NAP','ASY','TA'],size=200),
    'RestingBP':np.random.randint(94,200,size=200),
    'Cholesterol':np.random.randint(126,564,size=200),
    'FastingBS':np.random.choice([0,1],size=200),
    'RestingECG':np.random.choice(['Normal','ST','LVH'],size=200),
    'MaxHR':np.random.randint(71,202,size=200),
    'ExerciseAngina':np.random.choice(['N','Y'],size=200),
    'Oldpeak':np.random.uniform(0,6.2,size=200),
    'ST_Slope':np.random.choice(['Up','Flat','Down'],size=200),
    'HeartAttack':np.random.choice([0,1],size=200)
}

#Convert to DataFrame
df=pd.DataFrame(data)
df.head()
from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler()
columns_to_scale=['Age','Salary','Experience','Dependents','Rating']
df[columns_to_scale]=scaler.fit_transform(df[columns_to_scale])
df.head()
*******************************
  from sklearn.preprocessing import LabelEncoder,OneHotEncoder
from sklearn.compose import ColumnTransformer
l=LabelEncoder()
df['Purchased']=l.fit_transform(df['Purchased'])
ed_mapping={'Bachelor':1,'Master':2,'PhD':3}
df['Education']=df['Education'].map(ed_mapping)
df=pd.get_dummies(df,columns=['City','Product_Category'],drop_first=True)
df.head()
********************************
  from sklearn.decomposition import PCA
pca=PCA(n_components=2)
pca_f=pca.fit_transform(df[columns_to_scale])
pca_df=pd.DataFrame(pca_f,columns=['PCA1','PCA2'])
df=pd.concat([df,pca_df],axis=1)
df.head()
***********************
  df.drop('Name',axis=1,inplace=True)
df.head()
***************************
  import seaborn as sns
import matplotlib.pyplot as plt
corr_mat=df.corr()
plt.figure(figsize=(10,8))
sns.heatmap(corr_mat,annot=True,cmap="coolwarm")
plt.title("Correlation Matrix")
plt.show()
**********************************
  df.hist(bins=20,figsize=(20,15))
plt.show()
skewness=df.skew()
print(skewness)
**********************
  # prompt: plt.figure(figsize=(15,10))

plt.figure(figsize=(15,10))
sns.boxplot(data=df[['Age','Salary','Experience','Dependents','Rating']])
plt.title("Box Plots for Numerical Features")
plt.show()
*********************************
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;
}
/**
 * Plugin Name
 *
 * @package           PluginPackage
 * @author            Your Name
 * @copyright         2019 Your Name or Company Name
 * @license           GPL-2.0-or-later
 *
 * @wordpress-plugin
 * Plugin Name:       Plugin Name
 * Plugin URI:        https://example.com/plugin-name
 * Description:       Description of the plugin.
 * Version:           1.0.0
 * Requires at least: 5.2
 * Requires PHP:      7.2
 * Author:            Your Name
 * Author URI:        https://example.com
 * Text Domain:       plugin-slug
 * License:           GPL v2 or later
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Update URI:        https://example.com/my-plugin/
 * Requires Plugins:  my-plugin, yet-another-plugin
 */
/*
 * Plugin Name:       My Basics Plugin
 * Plugin URI:        https://example.com/plugins/the-basics/
 * Description:       Handle the basics with this plugin.
 * Version:           1.10.3
 * Requires at least: 5.2
 * Requires PHP:      7.2
 * Author:            John Smith
 * Author URI:        https://author.example.com/
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Update URI:        https://example.com/my-plugin/
 * Text Domain:       my-basics-plugin
 * Domain Path:       /languages
 * Requires Plugins:  my-plugin, yet-another-plugin
 */
//html
<div class="container-fluid" style="margin-top: 60px;">
  <div class="row justify-content-start">
    <!-- Back Button -->
    <div class="col-6">
      <i class="bi bi-arrow-left-circle header-icon" (click)="goBack()"></i>
    </div>

    <!-- My Profile Heading -->
    <div class="col-6">
      <h2 class="text-left">My Profile</h2>
      <span style="float: right;">
        <a class="navbar-brand" href="#" data-bs-toggle="modal" data-bs-target="#helpModal">
            <i class="bi bi-info-circle-fill">Help</i>
          </a>
      </span>
    </div>

    <!-- Left Side Menu -->
    <div class="col-md-3">
      <div routerLink="/orders" *ngIf="userTypeID === 3">
        <h5 class="small-heading">
          <i class="bi bi-cart4"></i>
          Orders
        </h5>
      </div>  
      <br>
      <h5 class="small-heading">
        <i class="bi bi-bell-fill"></i>
        Notifications
      </h5>
      <!-- Notification placeholder -->
      <div class="card mt-3">
        <div class="card-body">
          <div *ngIf="unredeemedRewards.length === 0" class="notification-item">
            <span>No Notifications</span>
          </div>
          <div *ngFor="let reward of unredeemedRewards" class="notification-item">
            <span style="float:left">{{ reward.rewardTypeName }}</span>
            <span style="float: right"><button class="btn btn-sm btn-primary" (click)="openRedeemModal(reward)">Redeem</button></span>
          </div>
        </div>
      </div>
    </div>

    

    <!-- Vertical Line Separator -->
    <div class="col-md-1">
      <div class="vertical-line"></div>
    </div>

    <!-- Right Side Form -->
    <div class="col-md-6">
      <form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
        <h5 class="small-heading">
          <i class="bi bi-house-gear-fill"></i>
          Personal Details
        </h5>
        <div class="text-center mb-3">
          <div class="profile-photo-wrapper">
            <img [src]="userProfileImage" alt="Profile Photo" class="img-fluid rounded-circle profile-photo" *ngIf="userProfileImage">
            <div class="edit-photo-wrapper">
              <a href="#" (click)="enableEditMode($event)" class="edit-link">Edit</a>
              <label [class.disabled-icon]="!isEditMode" for="photoUpload" class="photo-upload-icon">
                <i class="bi bi-camera"></i>
              </label>
            </div>
            <input type="file" id="photoUpload" formControlName="photo" class="d-none" (change)="onPhotoChange($event)" [readonly]="!isEditMode" >
          </div>
        </div>
        

        <br>

      
        <div class="row">
          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="name" class="form-label">Name</label>
              <input type="text" class="form-control" id="name" formControlName="name" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['name'].invalid && (profileForm.controls['name'].dirty || profileForm.controls['name'].touched)" class="alert">
                <div *ngIf="profileForm.controls['name'].errors?.['required']">Name is required.</div>
                <div *ngIf="profileForm.controls['name'].errors?.['minlength']">Name must be at least 2 characters long.</div>
                <div *ngIf="profileForm.controls['name'].errors?.['maxlength']">Name must be at most 20 characters long.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">            
              <label for="surname" class="form-label">Surname</label>
              <input type="text" class="form-control" id="surname" formControlName="surname" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['surname'].invalid && (profileForm.controls['surname'].dirty || profileForm.controls['surname'].touched)" class="alert">
                <div *ngIf="profileForm.controls['surname'].errors?.['required']">Surname is required.</div>
                <div *ngIf="profileForm.controls['surname'].errors?.['minlength']">Surname must be at least 2 characters long.</div>
                <div *ngIf="profileForm.controls['surname'].errors?.['maxlength']">Surname must be at most 20 characters long.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="email" class="form-label">Email Address</label>
              <input type="email" class="form-control" id="email" formControlName="email" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['email'].invalid && (profileForm.controls['email'].dirty || profileForm.controls['email'].touched)" class="alert">
                <div *ngIf="profileForm.controls['email'].errors?.['required']">Email is required.</div>
                <div *ngIf="profileForm.controls['email'].errors?.['email']">Email is invalid.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="phoneNumber" class="form-label">Phone Number</label>
              <input type="text" class="form-control" id="phoneNumber" formControlName="phoneNumber" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['phoneNumber'].invalid && (profileForm.controls['phoneNumber'].dirty || profileForm.controls['phoneNumber'].touched)" class="alert">
                <div *ngIf="profileForm.controls['phoneNumber'].errors?.['required']">Phone Number is required.</div>
                <div *ngIf="profileForm.controls['phoneNumber'].errors?.['minlength']">Phone Number must be a valid 10-digit number.</div>
                <div *ngIf="profileForm.controls['phoneNumber'].errors?.['maxlength']">Phone Number must be a valid 10-digit number.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="physical_Address" class="form-label">Physical Address</label>
              <input type="text" class="form-control" id="physical_Address" formControlName="physical_Address" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['physical_Address'].invalid && (profileForm.controls['physical_Address'].dirty || profileForm.controls['physical_Address'].touched)" class="alert">
                <div *ngIf="profileForm.controls['physical_Address'].errors?.['required']">Physical address is required.</div>
                <div *ngIf="profileForm.controls['physical_Address'].errors?.['minlength']">Physical Address must be at least 7 characters long.</div>
                <div *ngIf="profileForm.controls['physical_Address'].errors?.['maxlength']">Physical Address must be at most 100 characters long.</div>
              </div>
            </div>
          </div>
        </div>

        <div class="d-flex justify-content-end">
          <button type="button" class="btn btn-primary me-2" (click)="openSaveModal()" [disabled]="!isEditMode">Save</button>
          <button type="button" class="btn btn-info" (click)="changePassword()" [disabled]="!isEditMode">Change Password</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Save Confirmation Modal -->
<div class="modal fade" id="saveConfirmationModal" tabindex="-1" role="dialog" aria-labelledby="saveConfirmationModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="saveConfirmationModalTitle">Save Changes</h5>
      </div>
      <div class="modal-body">
        Are you sure you want to update your profile details?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="dismissModal()">Cancel</button>
        <button type="button" class="btn btn-primary" (click)="confirmSave()">Confirm</button>
      </div>
    </div>
  </div>
</div>

<!-- Error Modal -->
<div class="modal fade" id="errorModal" tabindex="-1" role="dialog" aria-labelledby="errorModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="errorModalTitle">Error</h5>
      </div>
      <div class="modal-body">
        Please enter a valid input for the following fields:
        <ul id="errorList"></ul>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" (click)="dismissErrorModal()">OK</button>
      </div>
    </div>
  </div>
</div>

<!-- Redeem Reward Modal -->
<div class="modal fade" id="redeemRewardModal" tabindex="-1" role="dialog" aria-labelledby="redeemRewardModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="redeemRewardModalTitle">Redeem Reward</h5>
      </div>
      <div class="modal-body">
        Are you sure you want to redeem the reward <strong>{{ selectedReward?.rewardTypeName }}</strong>?
        <br>
        <p>The reward criteria met: <strong>{{ selectedReward?.rewardCriteria }}</strong></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="dismissRedeemModal()">No</button>
        <button type="button" class="btn btn-primary" (click)="confirmRedeem()">Yes</button>
      </div>
    </div>
  </div>
</div>

<!-- Success Modal -->
<div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="successModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <strong><h5 class="modal-title" id="successModalTitle">Congratulations</h5></strong>
      </div>
      <div class="modal-body">
        <strong>Congratulations!</strong> You've successfully redeemed this reward <strong>{{ selectedReward?.rewardTypeName }}</strong>. Please contact the gym and provide this code <strong>{{ verificationCode }}</strong> for further instructions.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="dismissSuccessModal()">Close</button>
      </div>
    </div>
  </div>
</div>


<!-- help-modal.component.html -->
<div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        <h5 class="modal-title mx-auto" id="helpModalLabel">Help Guide</h5>
        <div class="search-bar-container">
          <input type="text" class="form-control search-bar" placeholder="Search help" [(ngModel)]="searchTerm" (input)="filterHelpContent()">
        </div>
      </div>
      <div class="modal-body">
        <div *ngFor="let item of filteredContent">
          <h5>{{ item.title }}</h5>
          <p [innerHTML]="item.content"></p>
        </div>
      </div>
    </div>
  </div>
</div>

//ts
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormGroup, Validators, FormBuilder, FormsModule } from '@angular/forms';
import { UserService } from '../Services/userprofile.service';
import { Router, RouterLink } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { Member, updateUser } from '../shared/update-user';
import { Subscription, catchError } from 'rxjs';
import { RewardRedeemViewModel, UnredeemedRewardModel } from '../shared/reward';
import { RewardService } from '../Services/reward.service';

declare var $: any; // Import jQuery

@Component({
  selector: 'app-profile-page',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, RouterLink, FormsModule],
  templateUrl: './profile-page.component.html',
  styleUrls: ['./profile-page.component.css']
})
export class ProfilePageComponent implements OnInit, OnDestroy {
  profileForm: FormGroup;
  user: updateUser | undefined;
  member: Member | undefined;
  isEditMode = false;
  errorMessage = '';  
  userProfileImage: string | null = null;
  photoFile: File | null = null;
  unredeemedRewards: UnredeemedRewardModel[] = [];
  selectedReward: UnredeemedRewardModel | null = null;
  verificationCode: string | null = null;
  userTypeID: number | null = null;
  helpContent: any[] = [];
  filteredContent: any[] = [];
  searchTerm: string = '';

  private userSubscription: Subscription | undefined;
  private memberSubscription: Subscription | undefined;
  private redeemSubscription: Subscription | undefined;
  
  constructor(
    private userService: UserService,
    private rewardService: RewardService,
    private router: Router,
    private fb: FormBuilder
  ) {
    this.profileForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      surname: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      phoneNumber: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(10)]],
      physical_Address: ['', [Validators.required, Validators.minLength(7), Validators.maxLength(100)]],
      photo: ['']
    });
  }

  ngOnInit(): void {
    const userTypeId = JSON.parse(localStorage.getItem('User') || '{}').userTypeId;
    this.userTypeID = userTypeId;
    console.log('User Type ID',userTypeId);
    const userId = JSON.parse(localStorage.getItem('User') || '{}').userId;
    console.log('User ID from local storage:', userId);
    this.loadUserProfile(userId);
    this.isEditMode = false;    


    // Initialize help content
    this.helpContent = [
      {
        title: 'Profile Page Context-Sensitive Help',
        content: `
          <p><strong>Overview:</strong> The Profile Page allows users to view and update their personal information. This includes details such as username, email, and profile picture.</p>
          <p><strong>Elements and Features:</strong></p>`
      },
      {
        title: '1. Back Button',
        content: `
          <ul>
            <li><strong>Description:</strong> An arrow icon located in the header that allows you to return to the previous page.</li>
            <li><strong>Functionality:</strong> Clicking the back button navigates to the previous page you visited.</li>
            <li><strong>Helpful Tips:</strong>
              <ul>
                <li>Use the back button if you want to return to your previous page without losing your current context.</li>
              </ul>
            </li>
          </ul>`
      },
      {
        title: '2. Header Title',
        content: `
          <ul>
            <li><strong>Description:</strong> Displays the title "Profile" to indicate the purpose of the screen.</li>
            <li><strong>Functionality:</strong> Provides a clear indication of the current screen's functionality.</li>
          </ul>`
      },
      {
        title: '3. Profile Information',
        content: `
          <ul>
            <li><strong>Description:</strong> Displays your personal information such as username, email, and profile picture.</li>
            <li><strong>Functionality:</strong> Allows you to view and edit your personal details.</li>
          </ul>`
      },
      {
        title: '4. Change Password Button',
        content: `
          <ul>
            <li><strong>Description:</strong> A button that navigates you to the Change Password screen.</li>
            <li><strong>Functionality:</strong> Allows you to update your password securely.</li>
          </ul>`
      },
      {
        title: 'Technical Details:',
        content: `
          <ul>
            <li>Dynamic Data: The profile information is dynamically updated based on the data retrieved from the backend.</li>
            <li>Navigation: Utilizes Angular's Router for smooth transitions between different sections of the application.</li>
          </ul>`
      },
      {
        title: 'Common Questions:',
        content: `
          <p><strong>Q:</strong> How do I update my profile information?</p>
          <p><strong>A:</strong> Click on the edit button next to the information you want to update, make your changes, and click save.</p>
          <p><strong>Q:</strong> How do I change my password?</p>
          <p><strong>A:</strong> Click the "Change Password" button to navigate to the Change Password screen.</p>
          <p><strong>Q:</strong> What should I do if I encounter an error?</p>
          <p><strong>A:</strong> Refresh the page or contact support for assistance.</p>`
      },
      {
        title: 'Troubleshooting:',
        content: `
          <p><strong>Problem:</strong> The profile information is not loading.</p>
          <p><strong>Solution:</strong> Ensure you are connected to the internet and logged in. If the problem persists, try refreshing the page or contact technical support.</p>
          <p><strong>Problem:</strong> Unable to update profile information.</p>
          <p><strong>Solution:</strong> Check your internet connection and ensure all required fields are filled out correctly. If the issue continues, contact support.</p>`
      }
    ];

    // Initialize filtered content
    this.filteredContent = [...this.helpContent];
  }

  filterHelpContent(): void {
    const term = this.searchTerm.toLowerCase();
    this.filteredContent = this.helpContent.filter(item =>
      item.title.toLowerCase().includes(term) || item.content.toLowerCase().includes(term)
    );
  }

  ngOnDestroy(): void {
    // Clean up subscriptions
    if (this.userSubscription) {
      this.userSubscription.unsubscribe();
    }
    if (this.memberSubscription) {
      this.memberSubscription.unsubscribe();
    }
    if (this.redeemSubscription) {
      this.redeemSubscription.unsubscribe();
    }
  }

  loadUserProfile(userId: number): void {
    this.userSubscription = this.userService.getUserById(userId).pipe(
      catchError(error => {
        console.error('Error fetching user profile:', error);
        return [];
      })
    ).subscribe({
      next: (result) => {
        console.log('User data received:', result);
        this.user = result; 

        // Patch non-file form values
        this.profileForm.patchValue({
          email: this.user.email,
          name: this.user.name,
          surname: this.user.surname,
          phoneNumber: this.user.phoneNumber,
          physical_Address: this.user.physical_Address,
        });

        // Log photo to debug
        console.log('Photo:', this.user.photo);        
        // Set user profile image
        this.userProfileImage = `data:image/jpeg;base64,${this.user.photo}`;
        console.log('User:', this.user);

        const userTypeId = JSON.parse(localStorage.getItem('User') || '{}').userTypeId;
        this.userTypeID = userTypeId;
        if (this.userTypeID === 3) {
          this.loadMemberProfile(userId);
        }
      },
      complete: () => {
        console.log('getUserById subscription completed');
      }
    });
  }

  loadMemberProfile(userId: number): void {
    this.memberSubscription = this.userService.getMemberByUserId(userId).pipe(
      catchError(error => {
        console.error('Error fetching member profile:', error);
        return [];
      })
    ).subscribe({
      next: (result) => {
        this.member = result;
        if (this.member) {
          console.log('Member data received:', this.member); // Detailed debug statement
          console.log('Member ID:', this.member.member_ID); // Debug statement
          this.loadUnredeemedRewards(this.member.member_ID);
        }
      },
      complete: () => {
        console.log('getMemberByUserId subscription completed');
      }
    });
  }

  clearForm() {
    this.profileForm.reset();
  }

  enableEditMode(event: Event) {
    event.preventDefault();
    this.isEditMode = true;
    this.profileForm.enable();
  }

  openSaveModal() {
    if (this.profileForm.invalid) {
      this.showValidationErrors();
      $('#errorModal').modal('show');
      return;
    }
    $('#saveConfirmationModal').modal('show');
  }

  showValidationErrors() {
    const invalidFields: string[] = [];
    Object.keys(this.profileForm.controls).forEach(key => {
      const controlErrors = this.profileForm.get(key)?.errors;
      if (controlErrors) {
        Object.keys(controlErrors).forEach(errorKey => {
          invalidFields.push(`${key}: ${errorKey}`);
        });
      }
    });
    this.errorMessage = `Please enter a valid input: ${invalidFields.join(', ')}`;
  }

  dismissModal() {
    $('#saveConfirmationModal').modal('hide');
  }

  dismissErrorModal() {
    $('#errorModal').modal('hide');
  }

  confirmSave() {
    this.dismissModal();
    this.onSubmit();
    this.isEditMode = false; // Disable edit mode after confirmation
  }

  onSubmit() {
    if (this.profileForm.valid) {
        const userId = JSON.parse(localStorage.getItem('User')!).userId;
        const formValue = this.profileForm.value;

        // If no new photo is selected, use the existing photo
        let photoFile: File | null = this.photoFile;
        if (!photoFile && this.user?.photo) {
          // Ensure the Base64 string is valid
          const base64Prefix = 'data:image/jpeg;base64,';
          let base64String = this.user.photo;
          if (base64String.startsWith(base64Prefix)) {
            base64String = base64String.replace(base64Prefix, '');
          }
          try {
            const byteString = atob(base64String);
            const arrayBuffer = new ArrayBuffer(byteString.length);
            const intArray = new Uint8Array(arrayBuffer);
            for (let i = 0; i < byteString.length; i++) {
              intArray[i] = byteString.charCodeAt(i);
            }
            const blob = new Blob([intArray], { type: 'image/jpeg' });
            photoFile = new File([blob], 'photo.jpg', { type: 'image/jpeg' });
          } catch (e) {
            console.error('Invalid Base64 string:', e);
          }
        }

        // Create the user object
        const user: updateUser = {
            name: formValue.name,
            surname: formValue.surname,
            email: formValue.email,
            physical_Address: formValue.physical_Address,
            phoneNumber: formValue.phoneNumber,
            photo: this.user?.photo ?? '', // Ensure photo is included even if it's not updated
            user_Type_ID: this.user?.user_Type_ID ?? 0
        };

        this.userService.updateUser(userId, user, photoFile).subscribe({
            next: (result) => {
                console.log('User updated successfully:', result);
                this.router.navigateByUrl(`/ProfilePage/${userId}`);
                alert('Successfully updated profile');
            },
            error: (error) => {
                console.error('Error updating user profile:', error);
                alert('Error updating profile.');
            }
        });
    } else {
        console.warn('Form is invalid:', this.profileForm.errors);
    }
  }

  onPhotoChange(event: Event): void {
    if (!this.isEditMode) return;

    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
        const file = input.files[0];
        
        // Ensure file is an image
        if (!file.type.startsWith('image/')) {
            console.error('Selected file is not an image.');
            alert('Please select a valid image file.');
            return;
        }

        const reader = new FileReader();

        reader.onload = (e: any) => {
          if (e.target && e.target.result) {
              this.userProfileImage = e.target.result; // Update the image source for preview
              this.photoFile = file; // Set the file for form submission
              console.log('Base64 string of the image:', this.userProfileImage);
          }
      };

        reader.onerror = (e) => {
            console.error('Error reading file:', e);
            alert('There was an error reading the file. Please try again.');
        };

        reader.onabort = (e) => {
            console.warn('File read aborted:', e);
            alert('File read was aborted. Please try again.');
        };

        reader.onloadend = () => {
            console.log('File read completed.');
        };

        try {
            reader.readAsDataURL(file);
            this.photoFile = file; 
        } catch (error) {
            console.error('An error occurred while reading the file:', error);
            alert('An error occurred while reading the file. Please try again.');
        }
    } else {
        console.error('No file selected or input element is invalid.');
    }
  }


  goBack() {
    const userTypeId = JSON.parse(localStorage.getItem('User')!).userTypeId;
    const userId = JSON.parse(localStorage.getItem('User')!).userId;
    if (userTypeId === 1) {  // Ensure userTypeID is compared as string
      this.router.navigateByUrl(`/OwnerHome/${userId}`);
    } else if (userTypeId === 2) {
      this.router.navigateByUrl(`/EmployeeHome/${userId}`);
    } else if (userTypeId === 3) {
      this.router.navigateByUrl(`/Home/${userId}`);
    }
  }

  changePassword() {
    this.router.navigateByUrl('/ChangePasswordPage');
  }

  // Method to load rewards for the current user
  loadUnredeemedRewards(memberId: number): void {
    console.log('Loading unredeemed rewards for member ID:', memberId); 
    this.rewardService.getUnredeemedRewardsForMember(memberId).subscribe({
      next: rewards => {
        this.unredeemedRewards = rewards;
        console.log("reward", rewards)
      },
      error: error => {
        console.error('Error fetching unredeemed rewards:', error);
      },
      complete: () => {
        console.log('Fetching unredeemed rewards completed.');
      }
    });
  }

  // Method to open redeem modal for a reward
  openRedeemModal(reward: UnredeemedRewardModel): void {
    this.selectedReward = reward;
    $('#redeemRewardModal').modal('show');
  }

  // Method to dismiss redeem modal
  dismissRedeemModal(): void {
    $('#redeemRewardModal').modal('hide');
  }

  // Method to confirm redeeming a reward
  confirmRedeem(): void {
    if (!this.selectedReward) {
      return;
    }
    const redeemRequest = new RewardRedeemViewModel();
    redeemRequest.MemberId = this.member?.member_ID ?? 0;
    redeemRequest.RewardId = this.selectedReward.reward_ID;

    // Call backend service to redeem the reward
    this.redeemSubscription = this.rewardService.redeemReward(redeemRequest).subscribe({
      next: () => {
        // Show success modal on successful redemption
        this.verificationCode = this.generateSixDigitCode(); // Generate code when opening modal
        console.log('Generated verification code:', this.verificationCode); 
        $('#successModal').modal('show');
        // Remove redeemed reward from the list
        this.unredeemedRewards = this.unredeemedRewards.filter(r => r.reward_ID !== this.selectedReward?.reward_ID);
      },
      error: (error) => {
        console.error('Error redeeming reward:', error);
        // Handle error
      }
    });
    this.dismissRedeemModal();
  }

  // Method to dismiss success modal
  dismissSuccessModal(): void {
    $('#successModal').modal('hide');
  }

  generateSixDigitCode(): string {
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    return `${code.slice(0, 3)}-${code.slice(3)}`;
  }
}
function cst_schema_field(){
    add_meta_box(
        'cft_metabox_field',
        'Add Schema',
        'cft_callback_func',
        array('page'),
        'normal',
        'high'
        );
}

add_action('add_meta_boxes','cst_schema_field');

function cft_callback_func($post){
    echo '<style>
        .schema_cft {
            width: 100%;
        }
    </style>';
    
    $meta_value = get_post_meta($post->ID, '_schema_cft', true);
    
    echo '<textarea name="schema_cft" class="schema_cft" rows="15">' . $meta_value . '</textarea>';
}

function cft_save_func($post_id){
    
    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if(!current_user_can('administrator', $post_id)) return;
    
    if(isset($_POST['schema_cft'])){
        update_post_meta($post_id, '_schema_cft', $_POST['schema_cft']);
    }
}

add_action('save_post','cft_save_func');

function display_schema_cft_in_head() {
    if (is_singular('page')) {
        $page_id = get_queried_object_id();
        
        $schema_cft_value = get_post_meta($page_id, '_schema_cft', true);

        if (!empty($schema_cft_value)) {
            echo $schema_cft_value;
        }
    }
}
// Add a column to the posts and pages list in the admin panel to display the last modified date
function add_last_modified_column($columns) {
    $columns['last_modified'] = 'Last Modified';
    return $columns;
}
add_filter('manage_posts_columns', 'add_last_modified_column');
add_filter('manage_pages_columns', 'add_last_modified_column');

// Populate the last modified column with the date and time
function display_last_modified_column($column, $post_id) {
    if ($column == 'last_modified') {
        $last_modified = get_post_modified_time('F j, Y, g:i a', false, $post_id);
        echo $last_modified;
    }
}
add_action('manage_posts_custom_column', 'display_last_modified_column', 10, 2);
add_action('manage_pages_custom_column', 'display_last_modified_column', 10, 2);

// Make the last modified column sortable
function make_last_modified_column_sortable($columns) {
    $columns['last_modified'] = 'last_modified';
    return $columns;
}
add_filter('manage_edit-post_sortable_columns', 'make_last_modified_column_sortable');
add_filter('manage_edit-page_sortable_columns', 'make_last_modified_column_sortable');

// Set the sorting logic for the last modified column
function sort_by_last_modified($vars) {
    if (isset($vars['orderby']) && 'last_modified' == $vars['orderby']) {
        $vars = array_merge($vars, array(
            'orderby' => 'modified'
        ));
    }
    return $vars;
}
add_filter('request', 'sort_by_last_modified');
@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() {
            const commentList = document.getElementById('comment-list');

            // Handle edit button click
            commentList.addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="edit"]');
                if (button) {
                    event.preventDefault();
                    const commentId = button.getAttribute('data-comment-id');
                    const commentElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"]`);
                    const commentBodyElement = commentElement.querySelector('.comment-body');

                    // Extract mention and content
                    const mentionElement = commentBodyElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const contentElement = mentionElement ? mentionElement.nextElementSibling :
                        commentBodyElement;
                    const content = contentElement.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) {
                const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);

                editForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const textarea = this.querySelector('textarea');
                    const content = 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);
                        });
                });

                editForm.querySelector('.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" style="display: none;">
                                            @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="#" class="reply-mention">@${data.reply.parent_name}</a> ` : ''}
                                                <span class="reply-content">${data.reply.content}</span>
                                            </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" style="display: none;">
                                                @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();
                                    form.style.display =
                                    'none'; // Hide the reply form after successful submission

                                    // Ensure the replies are displayed
                                    const replyToggle = form.closest('.comment').querySelector(
                                        '.reply-toggle');
                                    if (replyToggle) {
                                        const replyList = replyToggle.nextElementSibling
                                            .nextElementSibling;
                                        replyList.style.display = 'block';
                                        replyToggle.textContent = 'Hide replies';
                                    }

                                    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
@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() {
            const commentList = document.getElementById('comment-list');

            // Handle edit button click
            commentList.addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="edit"]');
                if (button) {
                    event.preventDefault();
                    const commentId = button.getAttribute('data-comment-id');
                    const commentElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"]`);
                    const commentBodyElement = commentElement.querySelector('.comment-body');

                    // Extract mention and content
                    const mentionElement = commentBodyElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const contentElement = mentionElement ? mentionElement.nextElementSibling :
                        commentBodyElement;
                    const content = contentElement.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) {
                const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);

                editForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const textarea = this.querySelector('textarea');
                    const content = 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);
                        });
                });

                editForm.querySelector('.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="#" class="reply-mention">@${data.reply.parent_name}</a> ` : ''}
                                                    <span class="reply-content">${data.reply.content}</span>
                                                </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
localStorage.ampConfig = `{"amp":{"services":{"fitprofile":{"url":"http://127.0.0.1:5500/fitpredictor/demo/dist/loader.js","enabled":"true"},"fitprofilepreview":{"url":"http://127.0.0.1:5500/fitpredictor/demo/dist/fitProfilePreviewLoader.js","enabled":"true"}}}}`
<script src="https://unpkg.com/lenis@1.1.9/dist/lenis.min.js"></script>
<script>
const lenis = new Lenis()

lenis.on('scroll', (e) => {
  console.log(e)
})

function raf(time) {
  lenis.raf(time)
  requestAnimationFrame(raf)
}

requestAnimationFrame(raf)
</script>
@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() {
            const commentList = document.getElementById('comment-list');

            // Handle edit button click
            commentList.addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="edit"]');
                if (button) {
                    event.preventDefault();
                    const commentId = button.getAttribute('data-comment-id');
                    const commentBodyElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"] .comment-body`
                    );
                    const contentElement = commentBodyElement.querySelector('.reply-content') ||
                        commentBodyElement;
                    const mentionElement = contentElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const content = contentElement.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) {
                const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);

                editForm.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);
                        });
                });

                editForm.querySelector('.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
@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() {
            const commentList = document.getElementById('comment-list');

            // Handle edit button click
            commentList.addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="edit"]');
                if (button) {
                    event.preventDefault();
                    const commentId = button.getAttribute('data-comment-id');
                    const commentBodyElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"] .comment-body`
                    );
                    const contentElement = commentBodyElement.querySelector('.reply-content') ||
                        commentBodyElement;
                    const mentionElement = contentElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const content = contentElement.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) {
                const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);

                editForm.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);
                        });
                });

                editForm.querySelector('.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
Convert a non-negative integer num to its English words representation.
@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() {
        // Attach event listeners to all edit buttons
        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 contentElement = commentBodyElement.querySelector('.reply-content') || commentBodyElement;
                const mentionElement = contentElement.querySelector('.reply-mention');
                const mention = mentionElement ? mentionElement.innerText.trim() : '';
                const content = contentElement.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) {
        const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);
        
        editForm.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);
            });
        });

        editForm.querySelector('.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
LET vFieldCount = NoOfFields('LINK');


FOR i = 1 TO $(vFieldCount)
    LET vFieldName$(i) = FieldName($(i), 'LINK');
NEXT i;

// Step 2: Construct dynamic load script
SET vLoadScript = '';

set vSkipFields = 'el1#,el2#,el3#';

FOR i = 1 TO $(vFieldCount)


	trace TRACE field $(vFieldName$(i));
    
    
    	IF WildMatch(vSkipFields, '*$(vFieldName$(i))*')  THEN
        // If both match, log the result and continue
        TRACE Matched: $(vFieldName$(i)) and skipped;
        
        else
        
    
    
    	LET vLoadScript = '$(vLoadScript)' & '$(vFieldName$(i)),';
        
        ENDIF;
NEXT i;

LET vLoadScript = LEFT('$(vLoadScript)', LEN('$(vLoadScript)') - 1);  // Remove the trailing comma

exit script;
<?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>
star

Sat Aug 10 2024 06:14:08 GMT+0000 (Coordinated Universal Time)

@Wittinunt

star

Sat Aug 10 2024 05:12:30 GMT+0000 (Coordinated Universal Time)

@poojitha #typescriptreact

star

Sat Aug 10 2024 04:26:44 GMT+0000 (Coordinated Universal Time) https://www.prothomalo.com/bangladesh/01jf3e36k2

@golam

star

Sat Aug 10 2024 03:42:54 GMT+0000 (Coordinated Universal Time) https://docs.pydantic.dev/1.10/usage/models/#recursive-orm-models

@theshyxin

star

Sat Aug 10 2024 03:40:30 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Aug 09 2024 13:25:53 GMT+0000 (Coordinated Universal Time) https://maticz.com/solana-dapp-development

@carolinemax ##maticz ##usa

star

Fri Aug 09 2024 13:09:10 GMT+0000 (Coordinated Universal Time)

@StephenThevar

star

Fri Aug 09 2024 12:16:37 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Fri Aug 09 2024 12:16:37 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Fri Aug 09 2024 12:13:33 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Thu Aug 08 2024 23:18:08 GMT+0000 (Coordinated Universal Time) https://getbootstrap.com/docs/5.3/components/dropdowns/

@poramet128

star

Thu Aug 08 2024 22:53:05 GMT+0000 (Coordinated Universal Time)

@k_m_s_avinash6

star

Thu Aug 08 2024 22:50:01 GMT+0000 (Coordinated Universal Time)

@k_m_s_avinash6

star

Thu Aug 08 2024 22:36:46 GMT+0000 (Coordinated Universal Time)

@k_m_s_avinash6

star

Thu Aug 08 2024 19:10:16 GMT+0000 (Coordinated Universal Time) https://cyberleninka.ru/search?q

@Pavlo190

star

Thu Aug 08 2024 16:02:12 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Thu Aug 08 2024 15:54:40 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Aug 08 2024 15:54:06 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Aug 08 2024 15:54:06 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Aug 08 2024 15:52:03 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Aug 08 2024 15:14:30 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Thu Aug 08 2024 13:06:35 GMT+0000 (Coordinated Universal Time) https://medium.com/@prashantramnyc/how-to-implement-google-authentication-in-node-js-using-passport-js-9873f244b55e

@abhi_550

star

Thu Aug 08 2024 11:37:34 GMT+0000 (Coordinated Universal Time) https://www.rginfotech.com/games/poker-game-development/

@kishanrg ##poker ##pokergame ##pokergamedevelopment ##gameapp

star

Thu Aug 08 2024 11:12:41 GMT+0000 (Coordinated Universal Time) https://www.guidingtech.com/how-to-disable-hyper-v-windows/

@Curable1600 #windows

star

Thu Aug 08 2024 10:38:45 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/crypto-casino-game-development

@smithtaylor ##crypto #casino ##game

star

Thu Aug 08 2024 08:09:55 GMT+0000 (Coordinated Universal Time)

@Merel1988 #php

star

Thu Aug 08 2024 05:28:45 GMT+0000 (Coordinated Universal Time)

@signup

star

Thu Aug 08 2024 04:21:05 GMT+0000 (Coordinated Universal Time)

@signup

star

Thu Aug 08 2024 03:10:01 GMT+0000 (Coordinated Universal Time) https://aovup.com/woocommerce/custom-order-status/

@mediasolutions

star

Wed Aug 07 2024 22:25:04 GMT+0000 (Coordinated Universal Time) https://developer.wordpress.org/plugins/plugin-basics/header-requirements/

@mediasolutions #php

star

Wed Aug 07 2024 22:24:53 GMT+0000 (Coordinated Universal Time) https://developer.wordpress.org/plugins/plugin-basics/header-requirements/

@mediasolutions #php

star

Wed Aug 07 2024 22:24:32 GMT+0000 (Coordinated Universal Time) https://developer.wordpress.org/plugins/plugin-basics/header-requirements/

@mediasolutions #php

star

Wed Aug 07 2024 21:31:35 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Wed Aug 07 2024 21:00:10 GMT+0000 (Coordinated Universal Time)

@wasim_mm1

star

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

@wasim_mm1

star

Wed Aug 07 2024 18:11:55 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Wed Aug 07 2024 17:49:48 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Wed Aug 07 2024 16:25:03 GMT+0000 (Coordinated Universal Time)

@kblanka #javascript

star

Wed Aug 07 2024 15:43:25 GMT+0000 (Coordinated Universal Time) https://github.com/darkroomengineering/lenis

@zily

star

Wed Aug 07 2024 15:24:15 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Wed Aug 07 2024 15:24:14 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Wed Aug 07 2024 13:51:35 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/integer-to-english-words/?envType

@0541 #java

star

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

@Sayed

star

Wed Aug 07 2024 10:07:59 GMT+0000 (Coordinated Universal Time) https://www.reddit.com/r/Windows11/comments/15txhve/comment/jwr1l87/

@Curable1600 #windows #ntlite

star

Wed Aug 07 2024 10:05:12 GMT+0000 (Coordinated Universal Time) https://htm-rapportage.eu.qlikcloud.com/dataloadeditor/app/7cead63c-b08c-4c31-831d-fb32b17f8310

@bogeyboogaard

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

Save snippets that work with our extensions

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