CREATE  PROCEDURE `getProductdetailsBySliderAd` (IN `advid` INT)   begin
SELECT
    product_id,
    product_name,
    product_display,
    product_featured,
  product_popular,
  product_prescrption,
    prodpack_id,
    prodpack_quantity,
    packing_type,
    measunit_shortname,
    strstk_mrp,
    strstk_msp,
    prodpack_maxstock,
  prodpack_minstock,
    product_imageurl,
    strstk_discount,
    strstk_id,
    strstk_item
FROM (
    SELECT
        p.product_id,
        p.product_name,
        p.product_display,
    p.product_featured,
  p.product_popular,
  p.product_prescrption,
        r.prodpack_id,
        r.prodpack_quantity,
        t.packing_type,
        m.measunit_shortname,
        e.strstk_mrp,
        e.strstk_msp,
       r.prodpack_maxstock,
  r.prodpack_minstock,
        (
            SELECT g.prodgal_url
            FROM product_gallery g
            WHERE g.prodgal_prodpack = r.prodpack_id
              AND g.prodgal_placedat = 1
              AND g.prodgal_medium = 1
              AND g.prodgal_publish = 1
              AND g.prodgal_status = 1
            ORDER BY g.prodgal_serial ASC
            LIMIT 1
        ) AS product_imageurl,
        e.strstk_discount,
        e.strstk_id,
        e.strstk_item,

        ROW_NUMBER() OVER (
            PARTITION BY e.strstk_item
            ORDER BY
                s.stockin_expiry ASC,
                e.strstk_discount DESC,
                (e.strstk_stock - e.strstk_reserved) DESC
        ) AS rn

    FROM tbl_homepageslier h,products_tbl p
    
    JOIN product_packing r 
        ON r.prodpack_product = p.product_id
    JOIN packing_tbl t 
        ON t.packing_id = r.prodpack_package
    JOIN measure_units m 
        ON m.measunit_id = r.prodpack_unit
    JOIN stock_inwards s 
        ON s.stockin_item = r.prodpack_id
    JOIN storestock_pricing e 
        ON e.strstk_item = r.prodpack_id
       AND s.stockin_id = e.strstk_refer

    WHERE p.product_status = 1
      AND p.product_online = 1
      AND p.product_publish = 1
    AND  h.slider_id=advid
    AND fIND_IN_SET(p.product_id,h.slider_product)
    AND e.strstk_discount != 0
AND (e.strstk_stock - e.strstk_reserved) > 0
      AND s.stockin_expiry >= CURRENT_DATE()) ranked
WHERE rn = 1;
END$$

CREATE  PROCEDURE `getProductforFrontendByIDandBatch` (IN `prdid` INT, IN `propackid` INT, IN `strstkid` INT)   BEGIN
SET @p0=prdid;
SET @p1=propackid;
SET @p2=strstkid;
CREATE TEMPORARY TABLE IF NOT EXISTS TempStockSelection (
    product_id INT,
    prodpack_id INT,
    strstk_discount DECIMAL(9,2),
    strstk_item INT,
    stockin_expiry DATE,
    product_name VARCHAR(200),
    product_display VARCHAR(200),
    product_maincategory  INT,
    product_subcategory INT,
    product_category  INT,
    product_prescrption TEXT,
    product_highlights TEXT,
    product_information TEXT,
    product_working TEXT,
    product_benefits TEXT,
    product_precautions TEXT,
    product_warnings TEXT,
    product_sideffects TEXT,
    product_antidot TEXT,
    product_specifications TEXT,
    brand_name VARCHAR(200),
    manuf_name VARCHAR(200),
    brand_id INT,
    prodpack_quantity INT,
    prodpack_maxstock INT,
    prodpack_minstock INT,
    prodpack_taxgroup DECIMAL(9,2),
    packing_type VARCHAR(200),
    measunit_name VARCHAR(200),
    measunit_shortname VARCHAR(200),
    strstk_msp DECIMAL(9,2),
    strstk_mrp DECIMAL(9,2),
    store_id INT,
    product_imageurl VARCHAR(200),
    stockin_batch VARCHAR(200),
    stock_available INT,
    strstk_id INT,
    selected INT,
    stockout INT,
    composition VARCHAR(200)
);

INSERT INTO TempStockSelection (
    product_id,
    prodpack_id,
    strstk_discount,
    strstk_item,
    stockin_expiry,
    product_name,
    product_display,
    product_maincategory,
    product_subcategory,
    product_category,
    product_prescrption,
    product_highlights,
    product_information,
    product_working,
    product_benefits,
    product_precautions,
    product_warnings,
    product_sideffects,
    product_antidot,
    product_specifications,
    brand_name,
     manuf_name,
    brand_id,
    prodpack_quantity,
    prodpack_maxstock,
    prodpack_minstock,
    prodpack_taxgroup,
    packing_type,
    measunit_name,
    measunit_shortname,
    strstk_msp,
    strstk_mrp,
    store_id,
    product_imageurl,
    stockin_batch,
    stock_available,
    strstk_id,
    selected,
    stockout,
    composition
)
SELECT 
    p.product_id,
    r.prodpack_id,
    e.strstk_discount,
    e.strstk_item,
    s.stockin_expiry,
    p.product_name,
    p.product_display,
    p.product_maincategory,
    p.product_subcategory,
    p.product_category,
    p.product_prescrption,
    p.product_highlights,
    p.product_information,
    p.product_working,
    p.product_benefits,
    p.product_precautions,
    p.product_warnings,
    p.product_sideffects,
    p.product_antidot,
    p.product_specifications,
    b.brand_name,
    f.manuf_name,
    b.brand_id,
    r.prodpack_quantity,
    r.prodpack_maxstock,
    r.prodpack_minstock,
    r.prodpack_taxgroup,
    k.packing_type,
    m.measunit_name,
    m.measunit_shortname,
    e.strstk_msp,
    e.strstk_mrp,
    st.store_id,
    (
        SELECT g.prodgal_url
        FROM product_gallery g
        WHERE g.prodgal_prodpack = r.prodpack_id
            AND g.prodgal_placedat = 1
            AND g.prodgal_medium = 1
            AND g.prodgal_publish = 1
            AND g.prodgal_status = 1
        ORDER BY g.prodgal_serial ASC
        LIMIT 1
    ) AS product_imageurl,
    s.stockin_batch,
    (e.strstk_stock - e.strstk_reserved) AS stock_available,
    e.strstk_id,
    (CASE WHEN r.prodpack_id = @p1 AND e.strstk_id = @p2 THEN 1 ELSE 0 END) AS selected,
    (CASE WHEN (GetProductTotalQuantity(@p0,e.strstk_item,e.strstk_id))>0 THEN 1 ELSE 0 END) AS stockout,
pc.pharma_name as composition
FROM products_tbl p
LEFT JOIN brands_tbl b ON b.brand_id = p.product_brand
JOIN manufacturers_tbl f ON f.manuf_id=p.product_manufacturer
INNER JOIN product_packing r ON r.prodpack_product = p.product_id
INNER JOIN packing_tbl k ON k.packing_id = r.prodpack_package
INNER JOIN measure_units m ON m.measunit_id = r.prodpack_unit
INNER JOIN storestock_pricing e ON e.strstk_item = r.prodpack_id 
INNER JOIN stores_tbl st ON st.store_id = e.strstk_store
INNER JOIN stock_inwards s ON s.stockin_id = e.strstk_refer
LEFT JOIN pharmacologicalcontent_tbl pc ON p.product_pcontent = pc.pharma_id
WHERE p.product_id = @p0
  AND e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
  AND e.strstk_product = @p0
  AND p.product_status = 1
  AND m.measunit_status = 1
  AND p.product_online = 1
  AND p.product_publish = 1
  AND r.prodpack_status = 1
  AND k.packing_status = 1
  AND s.stockin_expiry >= CURRENT_DATE()
  AND r.prodpack_id = @p1
  AND e.strstk_id = @p2;
  
  INSERT INTO TempStockSelection (
    product_id,
    prodpack_id,
    strstk_discount,
    strstk_item,
    stockin_expiry,
    product_name,
    product_display,
    product_maincategory,
    product_subcategory,
    product_category,
    product_prescrption,
    product_highlights,
    product_information,
    product_working,
    product_benefits,
    product_precautions,
    product_warnings,
    product_sideffects,
    product_antidot,
    product_specifications,
    brand_name,
    manuf_name,
    brand_id,
    prodpack_quantity,
    prodpack_maxstock,
    prodpack_minstock,
    prodpack_taxgroup,
    packing_type,
    measunit_name,
    measunit_shortname,
    strstk_msp,
    strstk_mrp,
    store_id,
    product_imageurl,
    stockin_batch,
    stock_available,
    strstk_id,
    selected,
    stockout,
      composition
)
SELECT x.product_id,
    x.prodpack_id,
    x.strstk_discount,
    x.strstk_item,
    x.stockin_expiry,
    x.product_name,
    x.product_display,
    x.product_maincategory,
    x.product_subcategory,
    x.product_category,
    x.product_prescrption,
    x.product_highlights,
    x.product_information,
    x.product_working,
    x.product_benefits,
    x.product_precautions,
    x.product_warnings,
    x.product_sideffects,
    x.product_antidot,
    x.product_specifications,
    x.brand_name,
    x.manuf_name,
    x.brand_id,
    x.prodpack_quantity,
    x.prodpack_maxstock,
    x.prodpack_minstock,
    x.prodpack_taxgroup,
    x.packing_type,
    x.measunit_name,
    x.measunit_shortname,
    x.strstk_msp,
    x.strstk_mrp,
    x.store_id,
    x.product_imageurl,
    x.stockin_batch,
    x.stock_available,
    x.strstk_id,
    x.selected,
    x.stockout,
    x.composition
    FROM (SELECT ( @row_number := @row_number + 1) AS virtual_id,
    p.product_id,
    r.prodpack_id,
    e.strstk_discount,
    e.strstk_item,
    s.stockin_expiry,
    p.product_name,
    p.product_display,
    p.product_maincategory,
    p.product_subcategory,
    p.product_category,
    p.product_prescrption,
    p.product_highlights,
    p.product_information,
    p.product_working,
    p.product_benefits,
    p.product_precautions,
    p.product_warnings,
    p.product_sideffects,
    p.product_antidot,
    p.product_specifications,
    b.brand_name,
     f.manuf_name,
    b.brand_id,
    r.prodpack_quantity,
    r.prodpack_maxstock,
    r.prodpack_minstock,
    r.prodpack_taxgroup,
    k.packing_type,
    m.measunit_name,
    m.measunit_shortname,
    e.strstk_msp,
    e.strstk_mrp,
    st.store_id,
    (
        SELECT g.prodgal_url
        FROM product_gallery g
        WHERE g.prodgal_prodpack = r.prodpack_id
            AND g.prodgal_placedat = 1
            AND g.prodgal_medium = 1
            AND g.prodgal_publish = 1
            AND g.prodgal_status = 1
        ORDER BY g.prodgal_serial ASC
        LIMIT 1
    ) AS product_imageurl,
    s.stockin_batch,
    (e.strstk_stock - e.strstk_reserved) AS stock_available,
    e.strstk_id,
    (CASE WHEN r.prodpack_id = @p1 AND e.strstk_id = @p2 THEN 1 ELSE 0 END) AS selected,
    (CASE WHEN (GetProductTotalQuantity(@p0,e.strstk_item,e.strstk_id))>0 THEN 1 ELSE 0 END) AS stockout,
          pc.pharma_name AS composition
    /*,
    stockout*/
FROM products_tbl p
LEFT JOIN brands_tbl b ON b.brand_id = p.product_brand
          JOIN manufacturers_tbl f ON f.manuf_id=p.product_manufacturer
INNER JOIN product_packing r ON r.prodpack_product = p.product_id
INNER JOIN packing_tbl k ON k.packing_id = r.prodpack_package
INNER JOIN measure_units m ON m.measunit_id = r.prodpack_unit
INNER JOIN storestock_pricing e ON e.strstk_item = r.prodpack_id INNER JOIN stores_tbl st ON st.store_id=e.strstk_store
INNER JOIN stock_inwards s ON s.stockin_id = e.strstk_refer
LEFT JOIN pharmacologicalcontent_tbl pc ON p.product_pcontent = pc.pharma_id

WHERE p.product_id = @p0 
  AND e.strstk_product = p.product_id
  AND  e.strstk_stock>0
  AND e.strstk_item = s.stockin_item
  AND e.strstk_product = @p0
  AND p.product_status = 1
  AND m.measunit_status = 1
  AND p.product_online = 1
  AND p.product_publish = 1
  AND r.prodpack_status = 1
  AND k.packing_status = 1
  AND s.stockin_expiry >= CURRENT_DATE()
ORDER BY selected DESC, s.stockin_expiry ASC, e.strstk_discount DESC,(e.strstk_stock-e.strstk_reserved) DESC) AS x WHERE (GetProductTotalQuantity(@p0,x.strstk_item,x.strstk_id))>0 and x.selected!=1 AND x.prodpack_id != @p1 GROUP BY x.prodpack_id;

  SELECT * FROM TempStockSelection;
  
SELECT i.prodingred_quantity,i.prodingred_unit,c.ingred_name,c.ingred_formula,c.ingred_drugbankid,c.ingred_codes,c.ingred_notes,c.ingred_drugclasses,t.ingredtype_type FROM product_ingredients i JOIN ingredients_tbl c on c.ingred_id=i.prodingred_ingredient JOIN ingredient_types t ON t.ingredtype_id=c.ingred_type WHERE i.prodingred_product=prdid;

SELECT f.faq_question,f.faq_answer,f.faq_id FROM faq_table f WHERE f.faq_item=prdid;

select g.prodgal_url,r.prodpack_id from product_gallery g INNER JOIN product_packing r ON  g.prodgal_prodpack = r.prodpack_id  INNER JOIN products_tbl p ON r.prodpack_product=p.product_id INNER JOIN packing_tbl k on k.packing_id=r.prodpack_package where  g.prodgal_placedat = 2 and g.prodgal_medium = 1 and g.prodgal_publish = 1 and g.prodgal_status = 1 and p.product_status=1 and p.product_id=prdid;

END$$

CREATE  PROCEDURE `getProductforFrontendByIDandBatchOLD` (IN `prdid` INT, IN `propackid` INT)   BEGIN
/*SELECT p.product_id,r.prodpack_id,e.strstk_discount,p.product_name,p.product_display,p.product_maincategory,p.product_subcategory,p.product_category,p.product_prescrption,p.product_highlights,p.product_information,p.product_working,p.product_benefits,p.product_precautions,p.product_warnings,p.product_sideffects,p.product_antidot,p.product_specifications,b.brand_name,b.brand_id,r.prodpack_quantity,r.prodpack_maxstock,r.prodpack_minstock,k.packing_type,m.measunit_name,m.measunit_shortname,e.strstk_msp,e.strstk_mrp,(select g.prodgal_url  from product_gallery g where g.prodgal_prodpack = r.prodpack_id and  g.prodgal_placedat = 1 and g.prodgal_medium = 1 and g.prodgal_publish = 1 and g.prodgal_status = 1 order by g.prodgal_serial asc limit 1) as product_imageurl FROM products_tbl p JOIN brands_tbl b on b.brand_id=p.product_brand INNER JOIN product_packing r ON r.prodpack_product=p.product_id INNER JOIN packing_tbl k on k.packing_id=r.prodpack_package INNER JOIN measure_units m ON m.measunit_id=r.prodpack_unit INNER JOIN storestock_pricing e ON   e.strstk_item=r.prodpack_id INNER JOIN stock_inwards s on s.stockin_id=e.strstk_refer WHERE p.product_id=prdid and e.strstk_product=p.product_id and e.strstk_item=s.stockin_item and e.strstk_product=prdid and p.product_status=1 and m.measunit_status=1 and s.stockin_batch=batchid and p.product_online = 1 and p.product_publish=1 and r.prodpack_status=1 and k.packing_status=1 and s.stockin_expiry >= CURRENT_DATE() order by s.stockin_expiry asc;
*/
SELECT
    p.product_id,
    r.prodpack_id,
    e.strstk_discount,
    s.stockin_expiry,
    p.product_name,
    p.product_display,
    p.product_maincategory,
    p.product_subcategory,
    p.product_category,
    p.product_prescrption,
    p.product_highlights,
    p.product_information,
    p.product_working,
    p.product_benefits,
    p.product_precautions,
    p.product_warnings,
    p.product_sideffects,
    p.product_antidot,
    p.product_specifications,
    b.brand_name,
    b.brand_id,
    r.prodpack_quantity,
    r.prodpack_maxstock,
    r.prodpack_minstock,
    r.prodpack_taxgroup,
    k.packing_type,
    m.measunit_name,
    m.measunit_shortname,
    e.strstk_msp,
    e.strstk_mrp,
    st.store_id
    ,
    (SELECT g.prodgal_url
     FROM product_gallery g
     WHERE g.prodgal_prodpack = r.prodpack_id
       AND g.prodgal_placedat = 1
       AND g.prodgal_medium = 1
       AND g.prodgal_publish = 1
       AND g.prodgal_status = 1
     ORDER BY g.prodgal_serial ASC
     LIMIT 1) AS product_imageurl,
    s.stockin_batch, (e.strstk_stock-e.strstk_reserved) as stock_available , e.strstk_id, (case when r.prodpack_id = propackid then 1 else 0 end) as selected
FROM products_tbl p
JOIN brands_tbl b ON b.brand_id = p.product_brand
INNER JOIN product_packing r ON r.prodpack_product = p.product_id
INNER JOIN packing_tbl k ON k.packing_id = r.prodpack_package
INNER JOIN measure_units m ON m.measunit_id = r.prodpack_unit
INNER JOIN storestock_pricing e ON e.strstk_item = r.prodpack_id INNER JOIN stores_tbl st ON st.store_id=e.strstk_store
INNER JOIN stock_inwards s ON s.stockin_id = e.strstk_refer
INNER JOIN (
    -- Select the highest discount for each prodpack_id and expiry date
    select x.strstk_item, x.stockin_expiry, x.max_discount,x.stock_available,x.strstk_mrp,x.strstk_msp  from (SELECT ( @row_number := @row_number + 1) AS virtual_id,e1.strstk_item, s1.stockin_expiry, (e1.strstk_discount) AS max_discount,(e1.strstk_stock-e1.strstk_reserved) as stock_available ,e1.strstk_mrp,e1.strstk_msp FROM storestock_pricing e1 JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer WHERE e1.strstk_product = prdid  AND (e1.strstk_stock-e1.strstk_reserved)>0 AND s1.stockin_expiry>= CURRENT_DATE() ORDER by s1.stockin_expiry asc, e1.strstk_discount DESC, e1.strstk_stock DESC) as x group by x.strstk_item
) AS Best ON Best.strstk_item = e.strstk_item 
        AND Best.stockin_expiry = s.stockin_expiry 
        AND Best.max_discount = e.strstk_discount
WHERE p.product_id = prdid 
  AND e.strstk_product = p.product_id
  AND  e.strstk_stock>0
  AND e.strstk_item = s.stockin_item
  AND e.strstk_product = prdid
  AND p.product_status = 1
  AND m.measunit_status = 1
  AND p.product_online = 1
  AND p.product_publish = 1
  AND r.prodpack_status = 1
  AND k.packing_status = 1
  AND s.stockin_expiry >= CURRENT_DATE()
   AND (e.strstk_stock-e.strstk_reserved)>0  GROUP by  r.prodpack_id
ORDER BY s.stockin_expiry ASC, e.strstk_discount DESC,(e.strstk_stock-e.strstk_reserved) DESC;
/*SELECT
    p.product_id,
    r.prodpack_id,
    e.strstk_discount,
    p.product_name,
    p.product_display,
    p.product_maincategory,
    p.product_subcategory,
    p.product_category,
    p.product_prescrption,
    p.product_highlights,
    p.product_information,
    p.product_working,
    p.product_benefits,
    p.product_precautions,
    p.product_warnings,
    p.product_sideffects,
    p.product_antidot,
    p.product_specifications,
    b.brand_name,
    b.brand_id,
    r.prodpack_quantity,
    r.prodpack_maxstock,
    r.prodpack_minstock,
    r.prodpack_taxgroup,
    k.packing_type,
    m.measunit_name,
    m.measunit_shortname,
    e.strstk_msp,
    e.strstk_mrp,
    st.store_id
    ,
    (SELECT g.prodgal_url
     FROM product_gallery g
     WHERE g.prodgal_prodpack = r.prodpack_id
       AND g.prodgal_placedat = 1
       AND g.prodgal_medium = 1
       AND g.prodgal_publish = 1
       AND g.prodgal_status = 1
     ORDER BY g.prodgal_serial ASC
     LIMIT 1) AS product_imageurl,
    s.stockin_batch, e.strstk_stock-e.strstk_reserved as stock_available , e.strstk_id, (case when r.prodpack_id = propackid then 1 else 0 end) as selected
FROM products_tbl p
JOIN brands_tbl b ON b.brand_id = p.product_brand
INNER JOIN product_packing r ON r.prodpack_product = p.product_id
INNER JOIN packing_tbl k ON k.packing_id = r.prodpack_package
INNER JOIN measure_units m ON m.measunit_id = r.prodpack_unit
INNER JOIN storestock_pricing e ON e.strstk_item = r.prodpack_id INNER JOIN stores_tbl st ON st.store_id=e.strstk_store
INNER JOIN stock_inwards s ON s.stockin_id = e.strstk_refer
WHERE p.product_id = prdid 
  AND e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
  AND e.strstk_product = prdid 
  AND p.product_status = 1
  AND m.measunit_status = 1
  AND p.product_online = 1
  AND p.product_publish = 1
  AND r.prodpack_status = 1
  AND k.packing_status = 1
  AND s.stockin_expiry >= CURRENT_DATE()
  AND e.strstk_discount=(SELECT MAX(e3.strstk_discount) FROM storestock_pricing e3 JOIN stock_inwards se ON se.stockin_id=e3.strstk_refer WHERE e3.strstk_item=r.prodpack_id and e3.strstk_product=prdid)
  AND s.stockin_expiry = (
    SELECT MIN(s2.stockin_expiry)
    FROM stock_inwards s2
    INNER JOIN storestock_pricing e2 ON e2.strstk_refer = s2.stockin_id
    WHERE e2.strstk_item = r.prodpack_id
      AND e2.strstk_product = prdid
  )  order by selected desc;*/
  
SELECT i.prodingred_quantity,i.prodingred_unit,c.ingred_name,c.ingred_formula,c.ingred_drugbankid,c.ingred_codes,c.ingred_notes,c.ingred_drugclasses,t.ingredtype_type FROM product_ingredients i JOIN ingredients_tbl c on c.ingred_id=i.prodingred_ingredient JOIN ingredient_types t ON t.ingredtype_id=c.ingred_type WHERE i.prodingred_product=prdid;

SELECT f.faq_question,f.faq_answer,f.faq_id FROM faq_table f WHERE f.faq_item=prdid;

select g.prodgal_url,r.prodpack_id from product_gallery g INNER JOIN product_packing r ON  g.prodgal_prodpack = r.prodpack_id  INNER JOIN products_tbl p ON r.prodpack_product=p.product_id INNER JOIN packing_tbl k on k.packing_id=r.prodpack_package where  g.prodgal_placedat = 2 and g.prodgal_medium = 1 and g.prodgal_publish = 1 and g.prodgal_status = 1 and p.product_status=1 and p.product_id=prdid;

END$$

CREATE  PROCEDURE `getProductList` ()   BEGIN
	SELECT x.product_id, x.product_name, x.product_display 
    FROM products_tbl x 
    WHERE x.product_status = 1 
    ORDER BY x.product_name;
END$$

CREATE  PROCEDURE `getProductListByKeyword` (IN `keyword` TEXT)   BEGIN
/*SELECT x.product_display,x.product_id,x.prodpack_id,x.prodpack_quantity,
x.measunit_shortname,x.strstk_mrp,x.strstk_msp,x.strstk_discount,x.packing_type,x.strstk_id, x.product_imageurl,x.product_prescrption   FROM (SELECT (@row_number := @row_number + 1) AS virtual_id,
       
        p.product_name AS product_display,
    p.product_id,
    r.prodpack_id,
                                                                                                       r.prodpack_quantity,
    e.strstk_item,
    m.measunit_shortname,
    e.strstk_msp,
    e.strstk_mrp,
         k.packing_type,                                                                            e.strstk_discount,
    st.store_id,
    (
        SELECT g.prodgal_url
        FROM product_gallery g
        WHERE g.prodgal_prodpack = r.prodpack_id
            AND g.prodgal_placedat = 1
            AND g.prodgal_medium = 1
            AND g.prodgal_publish = 1
            AND g.prodgal_status = 1
        ORDER BY g.prodgal_serial ASC
        LIMIT 1
    ) AS product_imageurl,
    e.strstk_id,p.product_prescrption   
FROM products_tbl p
LEFT JOIN brands_tbl b ON b.brand_id = p.product_brand
LEFT JOIN product_classes pp ON p.product_maincategory = pp.prodclass_id
   LEFT JOIN pharmacologicalcontent_tbl pc ON p.product_pcontent = pc.pharma_id
INNER JOIN product_packing r ON r.prodpack_product = p.product_id
INNER JOIN packing_tbl k ON k.packing_id = r.prodpack_package
INNER JOIN measure_units m ON m.measunit_id = r.prodpack_unit
INNER JOIN storestock_pricing e ON e.strstk_item = r.prodpack_id 
INNER JOIN stores_tbl st ON st.store_id = e.strstk_store
INNER JOIN stock_inwards s ON s.stockin_id = e.strstk_refer
WHERE
              (
    p.product_name LIKE CONCAT('%', keyword, '%') OR
    pc.pharma_name LIKE CONCAT('%', keyword, '%') OR
    b.brand_name LIKE CONCAT('%', keyword, '%') OR
    pp.prodclass_name LIKE CONCAT('%', keyword, '%')
)   
  AND e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
  AND p.product_status = 1
  AND m.measunit_status = 1
  AND p.product_online = 1
  AND p.product_publish = 1
  AND r.prodpack_status = 1
  AND k.packing_status = 1        
  AND s.stockin_expiry >= CURRENT_DATE()
  AND (e.strstk_stock-e.strstk_reserved) > 0 order by s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc LIMIT 20
  ) as x group by x.product_id;*/
  
  SELECT product_name,
product_id,
prodpack_id,
prodpack_quantity,
measunit_shortname,
strstk_mrp,
strstk_msp,
strstk_discount,
packing_type,
strstk_id, 
product_imageurl,
product_prescrption
FROM (SELECT 
      p.product_name,
    p.product_id,
    r.prodpack_id,
r.prodpack_quantity,
    e.strstk_item,
    m.measunit_shortname,
    e.strstk_msp,
    e.strstk_mrp,
    k.packing_type,  
    e.strstk_discount,
    st.store_id,
    (
        SELECT g.prodgal_url
        FROM product_gallery g
        WHERE g.prodgal_prodpack = r.prodpack_id
            AND g.prodgal_placedat = 1
            AND g.prodgal_medium = 1
            AND g.prodgal_publish = 1
            AND g.prodgal_status = 1
        ORDER BY g.prodgal_serial ASC
        LIMIT 1
    ) AS product_imageurl,
    e.strstk_id,p.product_prescrption,  
ROW_NUMBER() OVER (
            PARTITION BY e.strstk_item
            ORDER BY
                s.stockin_expiry ASC,
                e.strstk_discount DESC,
                (e.strstk_stock - e.strstk_reserved) DESC
        ) AS rn
 
FROM products_tbl p
LEFT JOIN brands_tbl b ON b.brand_id = p.product_brand
LEFT JOIN product_classes pp ON p.product_maincategory = pp.prodclass_id
   LEFT JOIN pharmacologicalcontent_tbl pc ON p.product_pcontent = pc.pharma_id
INNER JOIN product_packing r ON r.prodpack_product = p.product_id
INNER JOIN packing_tbl k ON k.packing_id = r.prodpack_package
INNER JOIN measure_units m ON m.measunit_id = r.prodpack_unit
INNER JOIN storestock_pricing e ON e.strstk_item = r.prodpack_id 
INNER JOIN stores_tbl st ON st.store_id = e.strstk_store
INNER JOIN stock_inwards s ON s.stockin_id = e.strstk_refer
WHERE
              (
    p.product_name LIKE CONCAT('%', keyword, '%') OR
    pc.pharma_name LIKE CONCAT('%', keyword, '%') OR
    b.brand_name LIKE CONCAT('%', keyword, '%') OR
    pp.prodclass_name LIKE CONCAT('%', keyword, '%')
)   
  AND e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
  AND p.product_status = 1
  AND m.measunit_status = 1
  AND p.product_online = 1
  AND p.product_publish = 1
  AND r.prodpack_status = 1
  AND k.packing_status = 1        
  AND s.stockin_expiry >= CURRENT_DATE()
  AND (e.strstk_stock-e.strstk_reserved) > 0 
  ) ranked where rn=1 ;
  
  END$$

CREATE  PROCEDURE `getProductListOfCategories` (IN `mainctgry` INT, IN `subctgry` INT, IN `ctgry` INT)   BEGIN
	SELECT p.product_id,p.product_name,p.product_display,p.product_generic,p.product_maincategory,p.product_subcategory,p.product_category,p.product_status  FROM products_tbl p WHERE p.product_maincategory=mainctgry AND p.product_subcategory=subctgry AND p.product_category=ctgry AND p.product_status >0 AND p.product_publish > 0;
END$$

CREATE  PROCEDURE `getProductPackages` (IN `prodid` INT)   BEGIN
	SELECT x.prodpack_id, fnGetProductFromPack(x.prodpack_id, 0) AS package
    FROM product_packing x 
    WHERE x.prodpack_product = prodid AND x.prodpack_status = 1 
    ORDER BY x.prodpack_package;
END$$

CREATE  PROCEDURE `getProductPacksForIntend` (IN `prodid` INT, IN `storeid` INT)   BEGIN
	DECLARE listprods TEXT DEFAULT '';
/*
	SELECT GROUP_CONCAT(p.prodpack_product) INTO listprods 
    FROM `storestock_master` xx
    LEFT JOIN product_packing p ON p.prodpack_id = xx.storestock_item 
    LEFT JOIN products_tbl t ON t.product_id = p.prodpack_product 
    WHERE xx.storestock_store = storeid;
*/
	SELECT x.prodpack_id, fnGetProductFromPack(x.prodpack_id, 0) AS package, x.prodpack_hsn, 
    (SELECT (s.storestock_available - s.storestock_reserved) 
    FROM storestock_master s WHERE s.storestock_store = storeid AND s.storestock_item = x.prodpack_id) AS available 
    FROM product_packing x 
    WHERE x.prodpack_product = prodid AND x.prodpack_status = 1 /* AND FIND_IN_SET(x.prodpack_product, listprods) */
    ORDER BY x.prodpack_package;  
END$$

CREATE  PROCEDURE `getProductSearchResults` (IN `searchs` VARCHAR(100))   BEGIN
	/*SELECT p.product_id, p.product_name, x.manuf_name
    FROM products_tbl p 
    LEFT JOIN manufacturers_tbl x ON x.manuf_id = p.product_manufacturer
    WHERE p.product_name LIKE CONCAT(searchs , '%') 
    AND p.product_status = 1 
    GROUP BY p.product_manufacturer
    ORDER BY p.product_name;*/
    SELECT p.product_id, p.product_name, x.manuf_name
    FROM products_tbl p 
    LEFT JOIN manufacturers_tbl x ON x.manuf_id = p.product_manufacturer
    WHERE p.product_name LIKE CONCAT(searchs , '%') 
    AND p.product_status = 1 
   
    ORDER BY p.product_name;
END$$

CREATE  PROCEDURE `getProductsInstoreNew` (IN `storeid` INT, IN `classcat` INT)   BEGIN
	DECLARE listclass TEXT DEFAULT ''; 

    SELECT GROUP_CONCAT( REPLACE(CONCAT_WS(',', IF(t.product_maincategory > 0, t.product_maincategory, ' ') , IF(t.product_subcategory > 0, t.product_subcategory, ' '), IF(t.product_category > 0, t.product_category, ' ')), ', ', '')) INTO listclass 
    FROM `storestock_pricing` xx
    LEFT JOIN product_packing p ON p.prodpack_id = xx.strstk_item AND xx.strstk_store = storeid  
    LEFT JOIN products_tbl t ON t.product_id = p.prodpack_product 
    WHERE xx.strstk_store = storeid AND (xx.strstk_inward - xx.strstk_reserved) > 0;

	IF classcat > 0 THEN 
    	SELECT sp.strstk_id, sp.strstk_item, fnGetProductFromPack(sp.strstk_item, 0) AS product, 
        s.stockin_batch, s.stockin_expiry, sp.strstk_stack, 
        (sp.strstk_stock - sp.strstk_reserved) AS stock, sp.strstk_store, sp.strstk_refer
        FROM storestock_pricing sp 
        LEFT JOIN stock_inwards s ON s.stockin_id = sp.strstk_refer
        LEFT JOIN product_packing y ON y.prodpack_id = sp.strstk_item
		LEFT JOIN products_tbl p ON p.product_id = y.prodpack_product 
		WHERE sp.strstk_store = storeid AND (sp.strstk_stock - sp.strstk_reserved) > 0 
        AND (p.product_maincategory = classcat OR p.product_subcategory = classcat 
        OR p.product_category = classcat) 
        UNION SELECT 0, 0, 0, 0, 0, 0, 0, 0, 0 
        ORDER BY 3 /*p.product_display*/ ;
    ELSE
    	SELECT sp.strstk_id, sp.strstk_item, fnGetProductFromPack(sp.strstk_item, 0) AS product,
        s.stockin_batch, s.stockin_expiry, sp.strstk_stack, 
        (sp.strstk_stock - sp.strstk_reserved) AS stock, sp.strstk_store, sp.strstk_refer 
        FROM storestock_pricing sp 
        LEFT JOIN stock_inwards s ON s.stockin_id = sp.strstk_refer
        WHERE sp.strstk_store = storeid AND (sp.strstk_stock - sp.strstk_reserved) > 0
        UNION SELECT 0, 0, 0, 0, 0, 0, 0, 0, 0 ;
    END IF;
    
    SELECT x.prodclass_id AS id, x.prodclass_name AS pclname, x.prodclass_parent AS parent, x.prodclass_serial AS serial, x.prodclass_status AS pstatus, x.prodclass_counter AS cntr, x.prodclass_seq AS seq
    FROM product_classes x 
    WHERE FIND_IN_SET(x.prodclass_id, listclass) 
    ORDER BY seq, cntr,  serial;
    #SELECT listclass; 
END$$

CREATE  PROCEDURE `getProductsofManufacturer` (IN `manufid` INT)   BEGIN
	SELECT p.product_id, p.product_name, p.product_display
    FROM products_tbl p 
    WHERE p.product_manufacturer = manufid AND p.product_status = 1 
    ORDER BY p.product_display;
END$$

CREATE  PROCEDURE `GetProductStockk` (IN `p_product_id` INT, IN `p_item_id` INT, IN `p_stock_id` INT, IN `p_required_qty` INT)   BEGIN
    -- Declare variables
    DECLARE mrp, msp, disc DOUBLE DEFAULT 0;
    DECLARE qtys, strk,total_allocated,stock_available,allocated_qty INT DEFAULT 0;
   

    -- Retrieve product pricing details
    SELECT e1.strstk_mrp, e1.strstk_msp, e1.strstk_discount, 
           (e1.strstk_stock - e1.strstk_reserved), e1.strstk_id 
    INTO mrp, msp, disc, qtys, strk 
    FROM storestock_pricing e1
    JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer
    WHERE e1.strstk_product = p_product_id  
      AND e1.strstk_item = p_item_id 
      AND e1.strstk_id = p_stock_id;

    -- Create temporary table
    CREATE TEMPORARY TABLE IF NOT EXISTS TempStockSelection (
        strstk_id INT,
        strstk_item INT,
        strstk_stock INT,
        stockin_expiry DATE,
        max_discount DECIMAL(10,2),
        allocated_quantity INT,
        strstk_mrp DECIMAL(10,2),
        strstk_msp DECIMAL(10,2)
    );
 -- Insert eligible stock entries sorted by expiry
    CREATE TEMPORARY TABLE IF NOT EXISTS TempStockData AS
    SELECT 
        e1.strstk_id, 
        e1.strstk_item, 
        (e1.strstk_stock - e1.strstk_reserved) AS available_stock, 
        s1.stockin_expiry, 
        e1.strstk_discount, 
        e1.strstk_mrp, 
        e1.strstk_msp
    FROM storestock_pricing e1
    JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer
    WHERE e1.strstk_product = p_product_id
      AND e1.strstk_item = p_item_id
      AND (e1.strstk_stock - e1.strstk_reserved) > 0
      AND s1.stockin_expiry >= CURRENT_DATE()
       AND e1.strstk_mrp = CAST(mrp AS DECIMAL(10,2)) 
      AND e1.strstk_msp = CAST(msp AS DECIMAL(10,2)) 
      AND e1.strstk_discount = CAST(disc AS DECIMAL(10,2))
    ORDER BY s1.stockin_expiry ASC,e1.strstk_discount DESC,(e1.strstk_stock - e1.strstk_reserved) DESC;
    -- Process stock entries dynamically
    WHILE total_allocated < p_required_qty AND EXISTS (SELECT 1 FROM TempStockData) DO
        -- Get the next available stock
        SELECT strstk_id, strstk_item, available_stock, stockin_expiry, 
               strstk_discount, strstk_mrp, strstk_msp
        INTO @stock_id, @stock_item, stock_available, @stock_expiry, 
             @stock_discount, @stock_mrp, @stock_msp
        FROM TempStockData
        ORDER BY stockin_expiry ASC,strstk_discount DESC, available_stock DESC
        LIMIT 1;

        -- Determine allocated quantity
        SET allocated_qty = LEAST(stock_available, p_required_qty - total_allocated);
        
        -- Insert into TempStockSelection
        INSERT INTO TempStockSelection (
            strstk_id, strstk_item, strstk_stock, stockin_expiry, max_discount, allocated_quantity, strstk_mrp, strstk_msp
        ) VALUES (
            @stock_id, @stock_item, stock_available, @stock_expiry, 
            @stock_discount, allocated_qty, @stock_mrp, @stock_msp
        );

        -- Update total allocated quantity
        SET total_allocated = total_allocated + allocated_qty;

        -- Remove processed row from TempStockData
        DELETE FROM TempStockData WHERE strstk_id = @stock_id;
    END WHILE;

    -- Return the selected stock with allocated quantities
    SELECT * FROM TempStockSelection;

    -- Cleanup
    DROP TEMPORARY TABLE IF EXISTS TempStockSelection;
    DROP TEMPORARY TABLE IF EXISTS TempStockData;
END$$

CREATE  PROCEDURE `getProductSubcategoriesList` (IN `categ` INT)   BEGIN
	SELECT x.prodclass_id, x.prodclass_name 
    FROM product_classes x 
    WHERE x.prodclass_parent = categ AND x.prodclass_status = 1
    ORDER BY x.prodclass_serial, x.prodclass_name;
END$$

CREATE  PROCEDURE `getProductSubclasses` (IN `prclsid` INT)   BEGIN
	DECLARE parents, subs TEXT DEFAULT '';
    
  
    
    SELECT GROUP_CONCAT(x.prodclass_id) INTO parents 
    FROM product_classes x 
    WHERE x.prodclass_parent = prclsid;
   
    SELECT prodclass_id AS id, prodclass_name AS pclname, prodclass_parent AS parent, prodclass_serial AS serial, prodclass_status AS pstatus, IF(prodclass_parent = prclsid, 0, 1) AS cntr, IF(prodclass_parent = prclsid, prodclass_id, CONCAT(prodclass_parent, '_', prodclass_parent)) AS seq, prodclass_thumb AS thumb,(SELECT COUNT(p.prodclass_id) 
     FROM product_classes p 
     WHERE p.prodclass_parent = pp.prodclass_id) AS subcount
    FROM product_classes pp
    WHERE FIND_IN_SET(prodclass_id, parents) OR FIND_IN_SET(prodclass_parent, parents)
    ORDER BY seq, serial;

END$$

CREATE  PROCEDURE `getProductSubclassesSeq` (IN `prclsid` INT)   BEGIN
	DECLARE parents, subs TEXT DEFAULT '';
    
    SELECT GROUP_CONCAT(x.prodclass_id) INTO parents 
    FROM product_classes_seq x 
    WHERE x.prodclass_parent = prclsid;
    
    SELECT parents;
    
    SELECT prodclass_id AS id, prodclass_name AS pclname, prodclass_parent AS parent, prodclass_serial AS serial, prodclass_status AS pstatus, prodclass_counter AS cntr, IF(prodclass_parent = prclsid, prodclass_id, CONCAT(prodclass_parent, '_', prodclass_parent)) AS seq, prodclass_thumb AS thumb
    FROM product_classes_seq
    WHERE FIND_IN_SET(prodclass_id, parents) OR FIND_IN_SET(prodclass_parent, parents)
    ORDER BY seq, serial;
END$$

CREATE  PROCEDURE `getProgramById` (IN `id` INT)   begin

SELECT p.progr_id,p.progr_menu,p.progr_url,p.progr_icon,p.progr_serial,p.progr_parent,p.progr_status from programs_table p WHERE p.progr_id = id;

END$$

CREATE  PROCEDURE `getProgramListForMenu` ()   BEGIN 

    SELECT p.progr_id AS progmid, p.progr_menu AS progmname, p.progr_url AS progmurl, p.progr_icon AS progmicon, p.progr_parent AS progmparent, IF(p.progr_parent = 0, p.progr_url, z.progr_menu) AS progmparentname , p.progr_serial AS programserial, IF(p.progr_parent = 0, p.progr_id, CONCAT(p.progr_parent, '_', p.progr_id)) AS seq, p.progr_status AS programstatus
    FROM programs_table p 
    LEFT JOIN programs_table z ON z.progr_id = p.progr_parent
    WHERE p.progr_status = 1 
    ORDER BY progmparent, programserial, progmid asc,seq;
        
END$$

CREATE  PROCEDURE `getProgramListForRoles` ()   BEGIN 

    SELECT p.progr_id AS progmid, p.progr_menu AS progmname, p.progr_url AS progmurl, p.progr_icon AS progmicon, p.progr_parent AS progmparent, IF(p.progr_parent = 0, p.progr_url, z.progr_menu) AS progmparentname , p.progr_serial AS programserial, IF(p.progr_parent = 0, p.progr_id, CONCAT(p.progr_parent, '_', CAST(p.progr_id AS CHAR(10)))) AS seq, p.progr_status AS programstatus
    FROM programs_table p 
    LEFT JOIN programs_table z ON z.progr_id = p.progr_parent
    WHERE p.progr_status = 1 
    ORDER BY seq, programserial;
        
END$$

CREATE  PROCEDURE `getProgramRolesById` (IN `id` INT)   BEGIN 
	DECLARE rolename varchar(50);
	DECLARE rolepgms mediumtext;
	
    SELECT x.usrprog_name, x.usrprog_programs INTO rolename, rolepgms
    FROM user_program x WHERE x.usrprog_id = id; 
    
    SELECT p.progr_id AS progmid, p.progr_menu AS progmname, p.progr_url AS progmurl, p.progr_icon AS progmicon, p.progr_parent AS progmparent, IF(p.progr_parent = 0, p.progr_url, z.progr_menu) AS progmparentname , p.progr_serial AS programserial, IF(p.progr_parent = 0, p.progr_id, CONCAT(p.progr_parent, '_', CAST(p.progr_id AS CHAR(10)))) AS seq, p.progr_status AS programstatus , IF(FIND_IN_SET(p.progr_id, rolepgms), 1, 0) AS selected
    FROM programs_table p 
    LEFT JOIN programs_table z ON z.progr_id = p.progr_parent
    WHERE p.progr_status = 1 
    ORDER BY seq, programserial;
      
    SELECT rolename, rolepgms;
END$$

CREATE  PROCEDURE `getProgramsForDropdown` ()   BEGIN

	SELECT p.progr_id AS progmid, p.progr_menu AS progmname, p.progr_url AS progmurl, p.progr_icon AS progmicon, p.progr_parent AS progmparent, IF(p.progr_parent = 0, p.progr_url, z.progr_menu) AS progmparentname , p.progr_serial AS programserial, IF(p.progr_parent = 0, p.progr_id, CONCAT(p.progr_parent, '_', p.progr_id)) AS seq, p.progr_status AS programstatus
    FROM programs_table p 
    LEFT JOIN programs_table z ON z.progr_id = p.progr_parent
    ORDER BY seq, programserial;

END$$

CREATE  PROCEDURE `getPurchaseDetails` (IN `storeid` INT, IN `fromdate` DATE, IN `todate` DATE)   BEGIN
IF storeid >1 THEN
SELECT i.invoice_id, i.invoice_number, i.invoice_vendertype, i.invoice_vendor, i.invoice_vendorgst, i.invoice_delstore, i.invoice_delgst,i.invoice_dated, i.invoice_amount, i.invoice_cgst, i.invoice_sgst, i.invoice_payby, id.invdet_item, id.invdet_qty, id.invdet_free, id.invdet_schdisc, id.invdet_price, id.invdet_hsn, id.invdet_cstpc, id.invdet_cst, id.invdet_sstpc, id.invdet_sst, id.invdet_mrp, id.invdet_ptr, id.invdet_taxamt, id.invdet_discpc, id.invdet_discount, id.invdet_batch, id.invdet_expiry, fnGetVendorName(i.invoice_vendertype, i.invoice_vendor) AS vendor, fnGetProductFromPack(id.invdet_item, 1) AS item, pp.prodpack_product, p.product_name, p.product_generic, p.product_maincategory, g.genmed_name, pc.prodclass_name, s.store_name FROM invoices_tbl i LEFT JOIN invoice_details id ON id.invdet_invoice= i.invoice_id LEFT JOIN product_packing pp ON pp.prodpack_id=id.invdet_item LEFT JOIN products_tbl p ON p.product_id=pp.prodpack_product LEFT JOIN generic_medicines g ON g.genmed_id=p.product_generic LEFT JOIN product_classes pc ON pc.prodclass_id = p.product_maincategory LEFT JOIN stores_tbl s ON s.store_id= i.invoice_delstore WHERE i.invoice_delstore=storeid AND i.invoice_dated BETWEEN fromdate AND todate;
ELSE
SELECT i.invoice_id, i.invoice_number, i.invoice_vendertype, i.invoice_vendor, i.invoice_vendorgst, i.invoice_delstore, i.invoice_delgst,i.invoice_dated, i.invoice_amount, i.invoice_cgst, i.invoice_sgst, i.invoice_payby, id.invdet_item, id.invdet_qty, id.invdet_free, id.invdet_schdisc, id.invdet_price, id.invdet_hsn, id.invdet_cstpc, id.invdet_cst, id.invdet_sstpc, id.invdet_sst, id.invdet_mrp, id.invdet_ptr, id.invdet_taxamt, id.invdet_discpc, id.invdet_discount, id.invdet_batch, id.invdet_expiry, fnGetVendorName(i.invoice_vendertype, i.invoice_vendor) AS vendor, fnGetProductFromPack(id.invdet_item, 1) AS item, pp.prodpack_product, p.product_name, p.product_generic, p.product_maincategory, g.genmed_name, pc.prodclass_name, s.store_name FROM invoices_tbl i LEFT JOIN invoice_details id ON id.invdet_invoice= i.invoice_id LEFT JOIN product_packing pp ON pp.prodpack_id=id.invdet_item LEFT JOIN products_tbl p ON p.product_id=pp.prodpack_product LEFT JOIN generic_medicines g ON g.genmed_id=p.product_generic LEFT JOIN product_classes pc ON pc.prodclass_id = p.product_maincategory LEFT JOIN stores_tbl s ON s.store_id= i.invoice_delstore WHERE i.invoice_dated BETWEEN fromdate AND todate;
END IF;
END$$

CREATE  PROCEDURE `getPurchasereturnBillData` ()   BEGIN
SELECT p.returnbill_id,p.returnbill_number,p.returnbill_dated,p.returnbill_vendertype,p.returnbill_vendor,p.returnbill_amt,p.returnbill_subamt,p.returnbill_difnce ,fnGetVendorName(p.returnbill_vendertype, p.returnbill_vendor) AS vendor,p.returnbill_status  FROM purchasereturn_tbl p ORDER BY p.returnbill_crtdon DESC;

END$$

CREATE  PROCEDURE `getReasonByIssueId` (IN `id` INT)   BEGIN
SELECT t.reason_help,t.reason_issue from tbl_help_desk_reason t WHERE t.reason_id=id and t.reason_status=1;

END$$

CREATE  PROCEDURE `getRetunOrderReasons` (IN `catId` INT)   BEGIN
SELECT r.return_id,r.return_catid,r.return_category FROM returnreason_tbl r GROUP BY r.return_catid;
SELECT r.return_id,r.return_catid,r.return_reason FROM returnreason_tbl r WHERE r.return_catid=catId;
END$$

CREATE  PROCEDURE `getRoqStock` (IN `itemid` INT)   BEGIN
SELECT p.prodpack_id, p.prodpack_roq, (x.strstk_stock-x.strstk_reserved) AS stock FROM product_packing p LEFT JOIN storestock_pricing x ON p.prodpack_id = x.strstk_item WHERE p.prodpack_roq <= (x.strstk_stock - x.strstk_reserved) AND p.prodpack_id=itemid;
END$$

CREATE  PROCEDURE `getSaleDetiles` (IN `storeid` INT, IN `saledate` DATE)   BEGIN
IF storeid >1 THEN
SELECT a.bill_store, a.bill_date,a.bill_name, a.bill_no, a.bill_pharmacist, a.bill_customer, a.bill_payby, b.billit_item, b.billit_name, b.billit_hsn, b.billit_mfr, b.billit_batch, b.billit_expiry, b.billit_sched, b.billit_mrp, b.billit_discount, b.billit_rate, b.billit_qty, b.billit_amount, b.billit_cgstpc, b.billit_sgstpc, c.store_name, e.product_generic, g.genmed_name, f.brand_name FROM bills_table a LEFT JOIN bill_items b ON b.billit_id= a.bill_id LEFT JOIN stores_tbl c ON c.store_id=a.bill_store LEFT JOIN product_packing d ON d.prodpack_id=b.billit_item LEFT JOIN products_tbl e ON e.product_id= d.prodpack_product LEFT JOIN generic_medicines g ON g.genmed_id=e.product_generic LEFT JOIN brands_tbl f ON f.brand_id=e.product_brand WHERE a.bill_store=storeid AND a.bill_date=saledate;
ELSE
SELECT a.bill_store, a.bill_date,a.bill_name, a.bill_no, a.bill_pharmacist, a.bill_customer, a.bill_payby, b.billit_item, b.billit_name, b.billit_hsn, b.billit_mfr, b.billit_batch, b.billit_expiry, b.billit_sched, b.billit_mrp, b.billit_discount, b.billit_rate, b.billit_qty, b.billit_amount, b.billit_cgstpc, b.billit_sgstpc, c.store_name, e.product_generic, g.genmed_name, f.brand_name FROM bills_table a LEFT JOIN bill_items b ON b.billit_id= a.bill_id LEFT JOIN stores_tbl c ON c.store_id=a.bill_store LEFT JOIN product_packing d ON d.prodpack_id=b.billit_item LEFT JOIN products_tbl e ON e.product_id= d.prodpack_product LEFT JOIN generic_medicines g ON g.genmed_id=e.product_generic LEFT JOIN brands_tbl f ON f.brand_id=e.product_brand WHERE a.bill_date=saledate;
END IF;
END$$

CREATE  PROCEDURE `getSalesBillDatasPerDate` (IN `saledate` DATE, IN `storeid` INT)   BEGIN
IF storeid>1 THEN
SELECT b.bill_id,DATE_FORMAT(b.bill_date, '%d-%m-%Y') AS billdate,b.bill_store,s.store_code,s.store_name, b.bill_no,b.bill_netpay AS amount,b.bill_status FROM bills_table b JOIN stores_tbl s ON s.store_id=b.bill_store WHERE b.bill_date=saledate AND b.bill_store=storeid ORDER BY b.bill_crtdon DESC;
 ELSE
 SELECT b.bill_id,DATE_FORMAT(b.bill_date, '%d-%m-%Y') AS billdate,b.bill_store,s.store_code,s.store_name, b.bill_no,b.bill_netpay AS amount,b.bill_status FROM bills_table b JOIN stores_tbl s ON s.store_id=b.bill_store WHERE b.bill_date=saledate ORDER BY b.bill_crtdon DESC;
 END IF;
END$$

CREATE  PROCEDURE `getSalesdiscount` (IN `storeid` INT)   BEGIN
IF storeid>1 THEN
SELECT a.`bill_id`, a.`bill_date`, a.`bill_store`,s.store_name, s.store_code, a.`bill_no`, a.`bill_pharmacist`,a.`bill_customer`, a.`bill_name`,a.`bill_doctor`,d.doctor_name, a.`bill_taxable`, a.`bill_cgst`, a.`bill_sgst`, a.`bill_discounts` , b.billit_item, b.billit_name, b.billit_mfr, b.billit_batch, b.billit_mrp, b.billit_discount, b.billit_rate, b.billit_qty, a.bill_crtdby, u.user_staffname, b.billit_cgstpc, b.billit_sgstpc FROM `bills_table` a LEFT JOIN bill_items b ON b.billit_id = bill_id LEFT JOIN doctors_tbl d ON d.doctor_id= a.bill_doctor LEFT JOIN stores_tbl s ON s.store_id= a.bill_store LEFT JOIN users_tbl u ON u.user_id= a.bill_crtdby WHERE `bill_store`=storeid order by b.billit_name;
ELSE
SELECT a.`bill_id`, a.`bill_date`, a.`bill_store`,s.store_name, s.store_code, a.`bill_no`, a.`bill_pharmacist`,a.`bill_customer`, a.`bill_name`,a.`bill_doctor`,d.doctor_name, a.`bill_taxable`, a.`bill_cgst`, a.`bill_sgst`, a.`bill_discounts` , b.billit_item, b.billit_name, b.billit_mfr, b.billit_batch, b.billit_mrp, b.billit_discount, b.billit_rate, b.billit_qty, a.bill_crtdby, u.user_staffname, b.billit_cgstpc, b.billit_sgstpc FROM `bills_table` a LEFT JOIN bill_items b ON b.billit_id = bill_id LEFT JOIN doctors_tbl d ON d.doctor_id= a.bill_doctor LEFT JOIN stores_tbl s ON s.store_id= a.bill_store LEFT JOIN users_tbl u ON u.user_id= a.bill_crtdby  order by b.billit_name;
END IF;
END$$

CREATE  PROCEDURE `getSalesScheme` (IN `itemid` INT)   BEGIN
SELECT dis_id, dis_date, dis_store,
       (SELECT GROUP_CONCAT(CONCAT(product_display, ' ', k.packing_type, ':', pt.prodpack_quantity, ' ', m.measunit_shortname))
        FROM products_tbl
        JOIN product_packing pt ON pt.prodpack_product = product_id
        LEFT JOIN packing_tbl k ON k.packing_id = pt.prodpack_package
        LEFT JOIN measure_units m ON m.measunit_id = pt.prodpack_unit
        WHERE FIND_IN_SET(pt.prodpack_id, dis_mainitem)) AS mainitem,
       dis_mainitem,
       (SELECT GROUP_CONCAT(CONCAT(product_display, ' ', k.packing_type, ':', pt.prodpack_quantity, ' ', m.measunit_shortname))
        FROM products_tbl
        JOIN product_packing pt ON pt.prodpack_product = product_id
        LEFT JOIN packing_tbl k ON k.packing_id = pt.prodpack_package
        LEFT JOIN measure_units m ON m.measunit_id = pt.prodpack_unit
        WHERE FIND_IN_SET(pt.prodpack_id, dis_freeitem)) AS freeitem,
       dis_freeitem,
       dis_crtdby,
       dis_approvedby,
       (SELECT u.user_staffname FROM users_tbl u WHERE u.user_id = dis_crtdby) AS crtdby,
       (SELECT u.user_staffname FROM users_tbl u WHERE u.user_id = dis_approvedby) AS approvedby,
       dis_status,
       (SELECT s.store_name FROM stores_tbl s WHERE s.store_id = dis_store) AS store_name
FROM schedulediscount_tbl
WHERE FIND_IN_SET(itemid,dis_mainitem)
ORDER BY dis_crtdon DESC;
END$$

CREATE  PROCEDURE `getSearchbySalesBillnum` (IN `billnum` VARCHAR(50))   BEGIN
SELECT b.bill_id, b.bill_date, b.bill_store, b.bill_no, b.bill_counter, b.bill_pharmacist,
       b.bill_customer, b.bill_mobile, b.bill_name, b.bill_age, b.bill_gender, b.bill_address, b.bill_referrer,
       b.bill_doctor, d.doctor_name, b.bill_quantity, b.bill_mrp, b.bill_taxable, b.bill_cgst, b.bill_sgst,
       b.bill_discounts, b.bill_netpay, b.bill_paid, b.bill_payref, b.bill_transid, b.bill_payby,
       bi.billit_id, bi.billit_item, bi.billit_name, bi.billit_hsn, bi.billit_mfr, bi.billit_batch,
       bi.billit_expiry, bi.billit_sched,(x.strstk_stock - x.strstk_reserved) AS available, bi.billit_mrp, bi.billit_discount, bi.billit_rate,
       bi.billit_qty, bi.billit_amount, bi.billit_cgstpc, bi.billit_cgst, bi.billit_sgstpc,
       bi.billit_sgst,  bi.billit_itid, pp.packing_type, p.prodpack_package, x.strstk_id, x.strstk_item, x.strstk_product, p.prodpack_quantity, b.bill_status, st.store_name, st.store_address , st.store_mobile,st.store_contactno
FROM bills_table b
LEFT JOIN bill_items bi ON bi.billit_id = b.bill_id
    LEFT JOIN  storestock_pricing x ON x.strstk_item=bi.billit_item AND x.strstk_id=bi.billit_strstkid
    LEFT JOIN doctors_tbl d ON d.doctor_id=b.bill_doctor
       LEFT JOIN  product_packing p ON p.prodpack_id=x.strstk_item
       join stores_tbl st on st.store_id = b.bill_store 
    LEFT JOIN packing_tbl pp ON pp.packing_id = p.prodpack_package
WHERE b.bill_no = billnum and x.strstk_refer IN (select stockin_id from stock_inwards where stockin_item=bi.billit_item and stockin_batch = bi.billit_batch) ;
/*GROUP BY bi.billit_item*/
END$$

CREATE  PROCEDURE `getSearchList` (IN `search_term` VARCHAR(255))   BEGIN
    -- First: Keyword-based suggestions (distinct labels)
    if search_term!="" THEN
    SELECT
   product_name,product_id,prodpack_id,strstk_item,prodpack_quantity,
packing_type,
measunit_shortname,strstk_mrp,strstk_msp,strstk_discount,strstk_id, product_imageurl
FROM (
    SELECT
 p.product_name,
    p.product_id,
    r.prodpack_id,
    e.strstk_item,
    r.prodpack_quantity,
        t.packing_type,
        m.measunit_shortname,
        e.strstk_mrp,
        e.strstk_msp,
      e.strstk_discount,
    st.store_id,
        (
            SELECT g.prodgal_url
            FROM product_gallery g
            WHERE g.prodgal_prodpack = r.prodpack_id
              AND g.prodgal_placedat = 1
              AND g.prodgal_medium = 1
              AND g.prodgal_publish = 1
              AND g.prodgal_status = 1
            ORDER BY g.prodgal_serial ASC
            LIMIT 1
        ) AS product_imageurl,
     
        e.strstk_id,
      
        ROW_NUMBER() OVER (
            PARTITION BY e.strstk_item
            ORDER BY
                s.stockin_expiry ASC,
                e.strstk_discount DESC,
                (e.strstk_stock - e.strstk_reserved) DESC
        ) AS rn

    FROM products_tbl p
    LEFT JOIN brands_tbl b ON b.brand_id = p.product_brand
 LEFT JOIN manufacturers_tbl f ON f.manuf_id=p.product_manufacturer                                                                                    
LEFT JOIN product_classes pp ON p.product_maincategory = pp.prodclass_id
   LEFT JOIN pharmacologicalcontent_tbl pc ON p.product_pcontent = pc.pharma_id
    JOIN product_packing r 
        ON r.prodpack_product = p.product_id
    JOIN packing_tbl t 
        ON t.packing_id = r.prodpack_package
    JOIN measure_units m 
        ON m.measunit_id = r.prodpack_unit
    JOIN stock_inwards s 
        ON s.stockin_item = r.prodpack_id
    JOIN storestock_pricing e 
        ON e.strstk_item = r.prodpack_id
       AND s.stockin_id = e.strstk_refer
INNER JOIN stores_tbl st ON st.store_id = e.strstk_store


    WHERE
  (    p.product_name LIKE CONCAT('%', search_term, '%') OR
        pc.pharma_name LIKE CONCAT('%', search_term, '%') OR
           f.manuf_name LIKE CONCAT('%', search_term, '%') OR
        b.brand_name LIKE CONCAT('%', search_term, '%') OR
        pp.prodclass_name LIKE CONCAT('%', search_term, '%'))

AND p.product_status = 1
      AND p.product_online = 1
      AND p.product_publish = 1
    
    
AND (e.strstk_stock - e.strstk_reserved) > 0
      AND s.stockin_expiry >= CURRENT_DATE()) ranked
WHERE rn = 1;
   /* SELECT x.product_name,x.product_id,x.prodpack_id,x.strstk_item,                                               x.prodpack_quantity,x.packing_type,
x.measunit_shortname,x.strstk_mrp,x.strstk_msp,x.strstk_discount,x.strstk_id, x.product_imageurl FROM (SELECT (@row_number := @row_number + 1) AS virtual_id,
        p.product_name,
    p.product_id,
    r.prodpack_id,
    e.strstk_item,
r.prodpack_quantity,
k.packing_type,
    m.measunit_shortname,
    e.strstk_msp,
    e.strstk_mrp,
 e.strstk_discount,
    st.store_id,
    (
        SELECT g.prodgal_url
        FROM product_gallery g
        WHERE g.prodgal_prodpack = r.prodpack_id
            AND g.prodgal_placedat = 1
            AND g.prodgal_medium = 1
            AND g.prodgal_publish = 1
            AND g.prodgal_status = 1
        ORDER BY g.prodgal_serial ASC
        LIMIT 1
    ) AS product_imageurl,
    e.strstk_id 
FROM products_tbl p
LEFT JOIN brands_tbl b ON b.brand_id = p.product_brand
 LEFT JOIN manufacturers_tbl f ON f.manuf_id=p.product_manufacturer                                                                                    
LEFT JOIN product_classes pp ON p.product_maincategory = pp.prodclass_id
   LEFT JOIN pharmacologicalcontent_tbl pc ON p.product_pcontent = pc.pharma_id
INNER JOIN product_packing r ON r.prodpack_product = p.product_id
INNER JOIN packing_tbl k ON k.packing_id = r.prodpack_package
INNER JOIN measure_units m ON m.measunit_id = r.prodpack_unit
INNER JOIN storestock_pricing e ON e.strstk_item = r.prodpack_id 
INNER JOIN stores_tbl st ON st.store_id = e.strstk_store
INNER JOIN stock_inwards s ON s.stockin_id = e.strstk_refer
WHERE
           (    p.product_name LIKE CONCAT('%', search_term, '%') OR
        pc.pharma_name LIKE CONCAT('%', search_term, '%') OR
           f.manuf_name LIKE CONCAT('%', search_term, '%') OR
        b.brand_name LIKE CONCAT('%', search_term, '%') OR
        pp.prodclass_name LIKE CONCAT('%', search_term, '%'))
              
  AND e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
  AND p.product_status = 1
  AND m.measunit_status = 1
  AND p.product_online = 1
  AND p.product_publish = 1
  AND r.prodpack_status = 1
  AND k.packing_status = 1        
  AND s.stockin_expiry >= CURRENT_DATE()
  AND (e.strstk_stock-e.strstk_reserved) > 0 order by s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc LIMIT 20
  ) as x group by x.product_id;*/
 END IF;
END$$

CREATE  PROCEDURE `getsearchLogByStore` ()   BEGIN

SELECT  st.store_code,st.store_name,fnGetProductFromPack(s.search_item, 0) AS orditem,s.search_item,s.search_store,MAX(s.search_crtdon) FROM searchlog_tbl s JOIN stores_tbl st on st.store_id=s.search_store WHERE date(s.search_crtdon)=CURRENT_DATE GROUP BY s.search_store,s.search_item ORDER BY s.search_crtdon DESC;



END$$

CREATE  PROCEDURE `getSearchSuggestions` (IN `search_term` VARCHAR(255))   BEGIN
    -- First: Keyword-based suggestions (distinct labels)
    if search_term!="" THEN
/*  SELECT 
    'suggestion' AS type,
   TRIM(CONCAT_WS(' ',
        pc.pharma_name,
        CASE
            WHEN p.product_name LIKE '%500%' AND pc.pharma_name NOT LIKE '%500%' THEN '500'
            WHEN p.product_name LIKE '%650%' AND pc.pharma_name NOT LIKE '%650%' THEN '650'
            ELSE ''
        END,
        CASE
            WHEN p.product_name LIKE '%Syrup%' AND pc.pharma_name NOT LIKE '%Syrup%' THEN 'Syrup'
            WHEN p.product_name LIKE '%Tablet%' AND pc.pharma_name NOT LIKE '%Tablet%' THEN 'Tablet'
            ELSE ''
        END
    )) AS product_display,NULL AS product_id,NULL AS prodpack_id,
NULL AS measunit_shortname,NULL AS strstk_mrp,NULL AS strstk_msp,NULL AS strstk_id, NULL AS product_imageurl
FROM products_tbl p
LEFT JOIN pharmacologicalcontent_tbl pc ON p.product_pcontent = pc.pharma_id
WHERE pc.pharma_name LIKE CONCAT('%', search_term, '%')
GROUP BY product_display
UNION
SELECT 
        'suggestion' AS type,
        TRIM(SUBSTRING_INDEX(p.product_name, ' ', 2)) AS product_display,NULL AS product_id,NULL AS prodpack_id,
NULL AS measunit_shortname,NULL AS strstk_mrp,NULL AS strstk_msp,NULL AS strstk_id, NULL AS product_imageurl
    FROM products_tbl p
    WHERE LOWER(p.product_name) LIKE CONCAT(LOWER(search_term), '%')
    OR LOWER(p.product_name) LIKE CONCAT('% ', LOWER(search_term), '%')
    GROUP BY product_display*/
   SELECT
    'suggestion' AS type,
    product_display,
    NULL AS product_id,
    NULL AS prodpack_id,
    NULL AS strstk_item,
    NULL AS prodpack_quantity,
    NULL AS packing_type,
    NULL AS measunit_shortname,
    NULL AS strstk_mrp,
    NULL AS strstk_msp,
    NULL AS strstk_discount,
    NULL AS strstk_id,
    NULL AS product_imageurl
FROM (
    SELECT DISTINCT
        TRIM(SUBSTRING_INDEX(product_name, ' ', 2)) AS product_display
    FROM products_tbl
    WHERE product_name LIKE CONCAT(search_term, '%')
) t

    UNION

    -- Second: Direct product links
   SELECT
    type,product_display,product_id,prodpack_id,strstk_item,prodpack_quantity,
packing_type,
measunit_shortname,strstk_mrp,strstk_msp,strstk_discount,strstk_id, product_imageurl
FROM (
    SELECT
'product' AS type,
        p.product_name AS product_display,
    p.product_id,
    r.prodpack_id,
    e.strstk_item,
    r.prodpack_quantity,
        t.packing_type,
        m.measunit_shortname,
        e.strstk_mrp,
        e.strstk_msp,
      e.strstk_discount,
    st.store_id,
        (
            SELECT g.prodgal_url
            FROM product_gallery g
            WHERE g.prodgal_prodpack = r.prodpack_id
              AND g.prodgal_placedat = 1
              AND g.prodgal_medium = 1
              AND g.prodgal_publish = 1
              AND g.prodgal_status = 1
            ORDER BY g.prodgal_serial ASC
            LIMIT 1
        ) AS product_imageurl,
     
        e.strstk_id,
      
        ROW_NUMBER() OVER (
            PARTITION BY e.strstk_item
            ORDER BY
                s.stockin_expiry ASC,
                e.strstk_discount DESC,
                (e.strstk_stock - e.strstk_reserved) DESC
        ) AS rn

    FROM products_tbl p
    LEFT JOIN brands_tbl b ON b.brand_id = p.product_brand
 LEFT JOIN manufacturers_tbl f ON f.manuf_id=p.product_manufacturer                                                                                    
LEFT JOIN product_classes pp ON p.product_maincategory = pp.prodclass_id
   LEFT JOIN pharmacologicalcontent_tbl pc ON p.product_pcontent = pc.pharma_id
    JOIN product_packing r 
        ON r.prodpack_product = p.product_id
    JOIN packing_tbl t 
        ON t.packing_id = r.prodpack_package
    JOIN measure_units m 
        ON m.measunit_id = r.prodpack_unit
    JOIN stock_inwards s 
        ON s.stockin_item = r.prodpack_id
    JOIN storestock_pricing e 
        ON e.strstk_item = r.prodpack_id
       AND s.stockin_id = e.strstk_refer
INNER JOIN stores_tbl st ON st.store_id = e.strstk_store


    WHERE
  (    p.product_name LIKE CONCAT('%', search_term, '%') OR
        pc.pharma_name LIKE CONCAT('%', search_term, '%') OR
           f.manuf_name LIKE CONCAT('%', search_term, '%') OR
        b.brand_name LIKE CONCAT('%', search_term, '%') OR
        pp.prodclass_name LIKE CONCAT('%', search_term, '%'))

AND p.product_status = 1
      AND p.product_online = 1
      AND p.product_publish = 1
    
    
AND (e.strstk_stock - e.strstk_reserved) > 0
      AND s.stockin_expiry >= CURRENT_DATE()) ranked
WHERE rn = 1;
    
   
 END IF;
END$$

CREATE  PROCEDURE `getStaffDetailsById` (IN `id` INT)   begin
	SELECT s.staff_id, s.staff_name, s.staff_code, s.staff_branch, s.staff_dob, s.staff_gender, s.staff_mobile, s.staff_email, s.staff_address, s.staff_status, s.staff_crtby, u.user_id, u.user_login, u.user_password, u.user_programid, u.user_programcontains, u.user_checkid, s.staff_image,s.staff_signature
	from staff_tbl s
    left JOIN users_tbl u on s.staff_id = u.user_staffid
    where s.staff_id = id;
SELECT u.store_id, u.store_name, u.store_code FROM stores_tbl u;
END$$

CREATE  PROCEDURE `getStaffForCourier` (IN `staffid` INT)   BEGIN
	SELECT x.staff_id, x.staff_name, x.staff_code, x.staff_mobile, x.staff_email, x.staff_address  
    FROM staff_tbl x 
    WHERE x.staff_id = staffid;
END$$

CREATE  PROCEDURE `getStaffImage` (IN `staffid` INT)   BEGIN
SELECT CONCAT('dist/img/staff/', s.staff_image) AS staff_image_path
FROM `staff_tbl` s
WHERE staff_id = staffid;
END$$

CREATE  PROCEDURE `getStaffList` ()   begin

SELECT s.staff_id,s.staff_name,s.staff_code,s.staff_dob,s.staff_gender,s.staff_mobile,s.staff_email,s.staff_status from staff_tbl s;

END$$

CREATE  PROCEDURE `getstaffListforusers` (IN `str` VARCHAR(100))   begin

select s.staff_id,s.staff_name from staff_tbl s WHERE s.staff_status = 1 and s.staff_id not in (SELECT u.user_staffid from users_tbl u ) and s.staff_name like concat('%',str,'%');


END$$

CREATE  PROCEDURE `getStockistProductsOfManufacturer` (IN `stkid` INT, IN `manufid` INT)   BEGIN
	SELECT x.product_id, x.product_name, x.product_manufacturer 
    FROM products_tbl x 
    WHERE x.product_manufacturer = manufid AND x.product_id NOT IN(
    	SELECT p.stockistprod_product FROM stockist_products p 
        WHERE p.stockistprod_stockist = stkid AND p.stockistprod_product = x.product_id AND p.stockistprod_status=1
    )
    AND x.product_status = 1 
    ORDER BY x.product_name;
END$$

CREATE  PROCEDURE `getStockTransferOrderDetailsNew` (IN `stkordid` INT)   BEGIN
	DECLARE listclass TEXT DEFAULT '';
    
	SELECT x.stocktrans_id, x.stocktrans_order, x.stocktrans_date, 
    x.stocktrans_strfrom, s.store_name AS storefrom, s.store_code AS codefrom, s.store_address AS addrfrom, 
    x.stocktrans_strto, t.store_name AS storeto, t.store_code AS codeto, t.store_address AS addrto, 
    x.stocktrans_packing, x.stocktrans_delivery, x.stocktrans_notes, x.stocktrans_status, 
    x.stocktrans_prprdby, pr.user_staffname AS prpdby, x.stocktrans_apprdby, ap.user_staffname AS aprvdby 
    FROM stock_transfers x 
    LEFT JOIN stores_tbl s ON s.store_id = x.stocktrans_strfrom 
    LEFT JOIN stores_tbl t ON t.store_id = x.stocktrans_strto 
    LEFT JOIN users_tbl pr ON pr.user_id = x.stocktrans_prprdby 
    LEFT JOIN users_tbl ap ON ap.user_id = x.stocktrans_apprdby 
    WHERE x.stocktrans_id = stkordid; 
    
    SELECT y.stockorder_id, y.stockorder_refer, y.stockorder_item, y.stockorder_batch, y.stockorder_expiry, y.stockorder_quantity, s.strstk_item, fnGetProductFromPack(s.strstk_item, 0) AS product, s.strstk_stack, (s.strstk_stock - s.strstk_reserved) AS stock, y.stockorder_packed, y.stockorder_packing, y.stockorder_delivery, y.stockorder_delivered  
    FROM stocktransfer_details y 
    LEFT JOIN storestock_pricing s ON s.strstk_id = y.stockorder_item 
    WHERE y.stockorder_refer = stkordid 
    ORDER BY y.stockorder_status;
    
    SELECT t.transpack_id, t.transpack_packid, t.transpack_trackid, t.transpack_from, sfr.store_name AS fromstore, 
    t.transpack_to, sto.store_name AS tostore, t.transpack_items, t.transpack_collectby, t.transpack_status
    FROM transfer_packets t 
    LEFT JOIN stores_tbl sfr ON sfr.store_id = t.transpack_from 
    LEFT JOIN stores_tbl sto ON sto.store_id = t.transpack_to 
    WHERE t.transpack_refer = stkordid;
    
    SELECT tp.transferpack_packet, trp.transpack_packid, tp.transferpack_item, fnGetProductFromPack(si.stockin_item, 0)AS item, tp.transferpack_qty, tp.transferpack_status, si.stockin_batch, si.stockin_expiry, trp.transpack_notes, tp.transferpack_packon  
    FROM transferpack_items tp
    LEFT JOIN storestock_pricing sp ON sp.strstk_id = tp.transferpack_orditem
    LEFT JOIN stock_inwards si ON si.stockin_id = sp.strstk_refer  
    LEFT JOIN transfer_packets trp ON trp.transpack_id = tp.transferpack_packet 
    WHERE tp.transferpack_packet IN( 
        SELECT t.transpack_id FROM transfer_packets t WHERE t.transpack_refer = stkordid)
    ORDER BY tp.transferpack_packet;  
    
    SELECT GROUP_CONCAT( REPLACE(CONCAT_WS(',', IF(t.product_maincategory > 0, t.product_maincategory, ' ') , IF(t.product_subcategory > 0, t.product_subcategory, ' '), IF(t.product_category > 0, t.product_category, ' ')), ', ', '')) INTO listclass 
    FROM `storestock_master` xx
    LEFT JOIN product_packing p ON p.prodpack_id = xx.storestock_item 
    LEFT JOIN products_tbl t ON t.product_id = p.prodpack_product 
    WHERE xx.storestock_store = (SELECT sx.stocktrans_strfrom FROM stock_transfers sx WHERE sx.stocktrans_id = stkordid);
	
    	SELECT prodclass_id AS id, prodclass_name AS pclname, prodclass_parent AS parent, prodclass_serial AS serial, prodclass_status AS pstatus, prodclass_counter AS cntr, prodclass_seq AS seq 
    	FROM product_classes 
    	WHERE FIND_IN_SET(prodclass_id, listclass) 
    	ORDER BY seq, cntr,  serial;
    
END$$

CREATE  PROCEDURE `getStockTransferOrders` (IN `storeid` INT)   BEGIN
   	SELECT x.stocktrans_id, x.stocktrans_order, x.stocktrans_date, 
    x.stocktrans_strfrom, s.store_name AS storefrom, x.stocktrans_strto, t.store_name AS storeto, 
    x.stocktrans_items, x.stocktrans_packing, x.stocktrans_delivery, x.stocktrans_status, 
    (SELECT COUNT(*) FROM transfer_packets p WHERE p.transpack_refer = x.stocktrans_id) AS packets  
  	FROM stock_transfers x 
    LEFT JOIN stores_tbl s ON s.store_id = x.stocktrans_strfrom 
    LEFT JOIN stores_tbl t ON t.store_id = x.stocktrans_strto 
  	WHERE (x.stocktrans_strfrom = storeid OR x.stocktrans_strto = storeid) AND x.stocktrans_status = 1;
END$$

CREATE  PROCEDURE `getStorageTypes` ()   BEGIN
SELECT s.strgtype_id, s.strgtype_type FROM storage_types s;
END$$

CREATE  PROCEDURE `GetStoreId` (IN `pincode` VARCHAR(10))   BEGIN
SELECT d.delarea_location,d.delarea_pincode,d.delarea_geomap,d.delarea_country,d.delarea_province,d.delarea_district FROM delivery_areas d WHERE d.delarea_pincode = pincode and d.delarea_status=1;
   /* DECLARE del_id INT;
    DECLARE store_id INT;
    
 
    
    -- Search for delivery area ID based on pincode
    SELECT delarea_id INTO del_id FROM delivery_areas WHERE delarea_pincode = pincode LIMIT 1;
    
  
    
    -- Check if delivery area ID was found
    IF del_id IS NOT NULL THEN
        -- Search for store ID based on the found delarea_id
        SELECT strdelv_store INTO store_id FROM store_delivery WHERE strdelv_area = del_id LIMIT 1;
        -- Check if store ID was found
        IF store_id IS NOT NULL THEN
            -- Return the store ID
            SELECT store_id;
        END IF;
    END IF;*/
END$$

CREATE  PROCEDURE `getStorelocator` ()   BEGIN
SELECT * FROM (SELECT s.store_name,s.store_address,s.store_mobile,s.store_email,s.store_location,DATE_FORMAT(t.strtme_from, '%l %p') AS strtme_from, DATE_FORMAT(t.strtme_to, '%l:%i %p') AS strtme_to, (CASE WHEN t.strtme_day=1 THEN "Monday" WHEN t.strtme_day=2 THEN "Tuesday" WHEN t.strtme_day=3 THEN "Wednesday" WHEN t.strtme_day=4 THEN "Thursday" WHEN t.strtme_day=5 THEN "Friday" WHEN t.strtme_day=6 THEN "Saturday" ELSE "Sunday" END  ) AS day   FROM stores_tbl s JOIN  store_timings t on s.store_id=t.strtme_store WHERE s.store_id!=1 and s.store_status=1) AS x WHERE  x.day=(SELECT DAYNAME(CURDATE()) AS today);
END$$

CREATE  PROCEDURE `getStorelocatoreByName` (IN `search_key` TEXT)   BEGIN
SELECT * FROM (SELECT s.store_name,s.store_address,s.store_mobile,s.store_email,s.store_location,DATE_FORMAT(t.strtme_from, '%l %p') AS strtme_from, DATE_FORMAT(t.strtme_to, '%l:%i %p') AS strtme_to, (CASE WHEN t.strtme_day=1 THEN "Monday" WHEN t.strtme_day=2 THEN "Tuesday" WHEN t.strtme_day=3 THEN "Wednesday" WHEN t.strtme_day=4 THEN "Thursday" WHEN t.strtme_day=5 THEN "Friday" WHEN t.strtme_day=6 THEN "Saturday" ELSE "Sunday" END  ) AS day   FROM stores_tbl s JOIN  store_timings t on s.store_id=t.strtme_store WHERE s.store_id!=1 and s.store_status=1) AS x WHERE  x.day=(SELECT DAYNAME(CURDATE()) AS today) AND (x.store_name LIKE CONCAT('%',search_key) OR  x.store_name LIKE CONCAT('%',search_key,'%'));
END$$

CREATE  PROCEDURE `getStoreProducts` (IN `storeid` INT)   BEGIN
if storeid > 1 THEN
SELECT s.storestock_item,fnGetProductFromPack(s.storestock_item, 0) AS product, s.storestock_store, st.store_name, (s.storestock_available-s.storestock_reserved) AS stock, (select count(x.stockin_id) from stock_inwards x where x.stockin_expiry <= CURRENT_DATE() + INTERVAL 44 DAY and x.stockin_store = storeid and x.stockin_item = s.storestock_item ) as expirycount FROM  storestock_master s LEFT JOIN stores_tbl st ON st.store_id=s.storestock_store WHERE  s.storestock_store=storeid;
ELSE
SELECT s.storestock_item,fnGetProductFromPack(s.storestock_item, 0) AS product, s.storestock_store, st.store_name, (s.storestock_available-s.storestock_reserved) AS stock, (select count(x.stockin_id) from stock_inwards x where x.stockin_expiry <= CURRENT_DATE() + INTERVAL 44 DAY and x.stockin_store = storeid and x.stockin_item = s.storestock_item ) as expirycount FROM  storestock_master s LEFT JOIN stores_tbl st ON st.store_id=s.storestock_store;
END IF;
END$$

CREATE  PROCEDURE `getStoreRegister` (IN `storeid` INT)   BEGIN
IF storeid>1 THEN
SELECT b.billit_item, b.billit_name, b.billit_hsn, b.billit_mfr, b.billit_batch, b.billit_expiry, b.billit_sched, b.billit_mrp,b.billit_discount, b.billit_rate, b.billit_qty, b.billit_amount, b.billit_cgstpc, b.billit_cgst, b.billit_sgstpc, b.billit_sgst, a.bill_no, a.bill_pharmacist, a.bill_customer, a.bill_name, a.bill_doctor, a.bill_crtdon, c.doctor_name, a.bill_store, d.store_name, a.bill_taxable FROM bill_items b LEFT JOIN bills_table a ON a.bill_id=b.billit_id LEFT JOIN doctors_tbl c ON c.doctor_id=a.bill_doctor LEFT JOIN stores_tbl d ON d.store_id= a.bill_store WHERE a.bill_store=storeid;
ELSE
SELECT b.billit_item, b.billit_name, b.billit_hsn, b.billit_mfr, b.billit_batch, b.billit_expiry, b.billit_sched, b.billit_mrp,b.billit_discount, b.billit_rate, b.billit_qty, b.billit_amount, b.billit_cgstpc, b.billit_cgst, b.billit_sgstpc, b.billit_sgst, a.bill_no, a.bill_pharmacist, a.bill_customer, a.bill_name, a.bill_doctor, a.bill_crtdon, c.doctor_name, a.bill_store, d.store_name, a.bill_taxable FROM bill_items b LEFT JOIN bills_table a ON a.bill_id=b.billit_id LEFT JOIN doctors_tbl c ON c.doctor_id=a.bill_doctor LEFT JOIN stores_tbl d ON d.store_id= a.bill_store; 
END IF;
END$$

CREATE  PROCEDURE `getStoreStockForBilling` (IN `storeid` INT)   BEGIN
	SELECT x.strstk_item, x.strstk_refer, x.strstk_store, x.strstk_product, x.strstk_id, fnGetProductFromPack(x.strstk_item, 1) AS product
    FROM storestock_pricing x
    LEFT JOIN products_tbl p ON p.product_id = x.strstk_product
    LEFT JOIN stock_inwards si ON si.stockin_id = x.strstk_refer 
    WHERE x.strstk_store = storeid AND x.strstk_status = 1 
    GROUP BY x.strstk_item
    ORDER BY p.product_name, x.strstk_item ;
END$$

CREATE  PROCEDURE `getSubdrugClasses` (IN `parent` INT)   BEGIN
	SELECT x.drugclass_id, x.drugclass_name 
    FROM drug_classifications x 
    WHERE x.drugclass_parent = parent AND x.drugclass_status = 1 
    ORDER BY x.drugclass_name;
END$$

CREATE  PROCEDURE `getSupplierListForItem` (IN `stkid` INT, IN `intend` INT)   BEGIN
	DECLARE prodid, packid INT DEFAULT 0; 
    
    SELECT p.prodpack_product, /*p.prodpack_package,*/ p.prodpack_id INTO prodid, packid 
    FROM product_packing p WHERE p.prodpack_id = stkid;
    
	SELECT x.vendsup_id, x.vendsup_type, x.vendsup_vendor, fnGetVendorName(x.vendsup_type, x.vendsup_vendor) AS vendor, x.vendsup_price, 
    (SELECT CONCAT(COUNT(*), '|', IFNULL(SUM(y.intdallocit_quantity), 0)) FROM intend_allocation_items y 
     	WHERE y.intdallocit_item = stkid AND y.intdallocit_intend = intend 
    	AND y.intdallocit_source = x.vendsup_vendor AND y.intdallocit_method = 2 AND y.intdallocit_type = x.vendsup_type ) AS allotted 
    FROM vendor_supplies  x  
    WHERE x.vendsup_product = prodid AND x.vendsup_packing = packid AND x.vendsup_status = 1 
    ORDER BY 2;
END$$

CREATE  PROCEDURE `getSupplierProducts` (IN `stype` INT, IN `supplier` INT)   BEGIN
	IF stype = 1 THEN   /* Stockists */
    	SELECT x.stockistprod_product AS pid, p.product_name, 'Stockist' AS suppliertype,s.stockist_GST,p.product_taxgroup
        FROM stockist_products x
        LEFT JOIN products_tbl p ON p.product_id = x.stockistprod_product LEFT JOIN vendor_supplies v on v.vendsup_product=p.product_id LEFT JOIN stockists_tbl s ON s.stockist_id=x.stockistprod_stockist
        WHERE x.stockistprod_stockist = supplier AND x.stockistprod_status = 1 AND v.vendsup_vendor = supplier AND v.vendsup_type = stype AND v.vendsup_status = 1 GROUP by p.product_name;
       
    ELSEIF stype = 2 THEN  /* Distributors */
    	SELECT d.distriprod_product AS pid, p.product_name,  'Distributor' AS suppliertype ,dt.distri_GST,p.product_taxgroup
        FROM distributor_products d
        LEFT JOIN products_tbl p ON p.product_id = d.distriprod_product INNER JOIN vendor_supplies v on v.vendsup_product=p.product_id INNER JOIN distributors_tbl dt ON dt.distri_id=d.distriprod_distributor
        WHERE d.distriprod_distributor = supplier AND d.distriprod_status = 1 AND v.vendsup_vendor = supplier AND v.vendsup_type = stype AND v.vendsup_status = 1 GROUP by p.product_name;
       
    ELSE
    	SELECT q.dealerprod_product AS pid, p.product_name,'Dealer' AS suppliertype ,dt.dealer_GST,p.product_taxgroup
        FROM dealer_products q
        LEFT JOIN products_tbl p ON p.product_id = q.dealerprod_product INNER JOIN vendor_supplies v on v.vendsup_product=p.product_id INNER JOIN dealers_tbl dt ON dt.dealer_id=q.dealerprod_dealer
        WHERE q.dealerprod_dealer = supplier AND q.dealerprod_status = 1 AND v.vendsup_vendor = supplier AND v.vendsup_type = stype AND v.vendsup_status = 1 GROUP by p.product_name;
       
    END IF;
    #store selection
    SELECT s.store_id,s.store_type,s.store_code,s.store_name,s.store_GST  FROM stores_tbl s WHERE s.store_status=1;
END$$

CREATE  PROCEDURE `getSuppliersOfPackage` (IN `prodid` INT, IN `packid` INT)   BEGIN
	SELECT x.vendsup_id, x.vendsup_type, x.vendsup_vendor, fnGetVendorName(x.vendsup_type, x.vendsup_vendor) AS vendor 
    FROM vendor_supplies x 
    WHERE x.vendsup_product = prodid AND x.vendsup_packing = packid AND x.vendsup_status = 1 
    ORDER BY 2;
    
END$$

CREATE  PROCEDURE `getSuppliersofType` (IN `stype` INT)   BEGIN
	IF stype = 1 THEN   /* Stockists */
    	SELECT x.stockist_id, x.stockist_name, 'Stockists' AS supliertype  
        FROM stockists_tbl x WHERE x.stockist_status = 1
        ORDER BY x.stockist_name;
    ELSEIF stype = 2 THEN  /* Distributors */
    	SELECT d.distri_id, d.distri_name, 'Distributor' AS supliertype
        FROM distributors_tbl d WHERE d.distri_status = 1 
        ORDER BY d.distri_name;
    ELSE
    	SELECT q.dealer_id, q.dealer_name, 'Dealers' AS supliertype
        FROM dealers_tbl q WHERE q.dealer_status = 1 
        ORDER BY q.dealer_name;
    END IF;
END$$

CREATE  PROCEDURE `getThePrescriptionForOrder` (IN `ordid` INT)   BEGIN

/*SELECT * FROM prescription_files WHERE order_id=ordid;*/
SELECT p.* FROM prescription_files_attached p JOIN orders_tbl o ON o.order_customer=p.user_id JOIN prescription_files f ON f.order_id=o.order_id WHERE FIND_IN_SET( p.file_id,(SELECT l.file_name FROM prescription_files l WHERE l.order_id=o.order_id)) AND o.order_id=ordid;

END$$

CREATE  PROCEDURE `getTheProductDetailsBySearch` (IN `searchs` TEXT)   BEGIN
	SELECT p.product_id, p.product_name, x.manuf_name
    FROM products_tbl p 
    LEFT JOIN manufacturers_tbl x ON x.manuf_id = p.product_manufacturer
    WHERE p.product_name LIKE CONCAT(searchs , '%') 
    AND p.product_status = 1 
   /* GROUP BY product_manufacturer*/ 
    ORDER BY p.product_name;
END$$

CREATE  PROCEDURE `getTrackOrderByOrderID` (IN `orderId` VARCHAR(200), IN `phone` VARCHAR(200))   BEGIN
DECLARE suppliers  TEXT;
DROP TEMPORARY TABLE IF EXISTS temp_cartdetails;
CREATE TEMPORARY TABLE temp_cartdetails (
        product_id INT,
        product_name VARCHAR(255),
    product_display VARCHAR(255),
    product_featured INT,
    product_popular INT,
    prodpack_id INT,
    prodpack_quantity INT,
    packing_type VARCHAR(255),
    measunit_name VARCHAR(255),
    measunit_shortname VARCHAR(255),
    strstk_mrp DECIMAL(9, 2),
    strstk_msp DECIMAL(9, 2),
    stockin_batch VARCHAR(50),
    stockin_expiry DATE,
    strstk_stock INT,
    strstk_stack INT,
    product_imageurl VARCHAR(255),
    strstk_discount	DECIMAL(5, 2),
    strstk_id INT,prd_qty INT,orderstatus INT,deliverystatus INT,ordcrton DATETIME,ordproc DATETIME,ordship DATETIME,orddeliv DATETIME, ordcancl DATETIME, ordref DATETIME, remarks TEXT);
    SELECT d.delivery_to,d.delivery_phone,d.delivery_email,d.delivery_pin,d.delivery_house,d.delivery_street,d.delivery_landmark,d.delivery_city,d.delivery_state,d.delivery_type,DATE_FORMAT(o.order_date, '%M %d, %Y at %l:%i %p') AS order_date,o.orders_delivered,o.orders_shipped,o.orders_cancelled,o.order_delivery,o.order_status,DATEDIFF(CURDATE(), o.orders_delivered) AS days_difference,o.order_quick,DATE_FORMAT(o.order_quick_processed, '%M %d, %Y at %l:%i %p') AS order_processed,DATEDIFF(CURDATE(), o.order_quick_processed) AS days_datedifference ,r.return_status,DATE_FORMAT(r.status_date, '%M %d, %Y at %l:%i %p') AS status_date ,DATE_FORMAT(r.approved_date, '%M %d, %Y at %l:%i %p') AS approved_date ,DATE_FORMAT(r.pickup_date, '%M %d, %Y at %l:%i %p') AS pickup_date,DATE_FORMAT(r.refund_date, '%M %d, %Y at %l:%i %p') AS refund_date,f.refund_paymentid,f.refund_amount,DATE_FORMAT(f.refund_created, '%M %d, %Y at %l:%i %p') AS refund_created FROM delivery_address d JOIN  orders_tbl o ON o.order_deliverId=d.delivery_id AND d.delivery_user=o.order_customer  JOIN customers_tbl c ON c.customer_id=o.order_customer LEFT JOIN order_return_status_history r ON r.order_id=o.order_id LEFT JOIN refund_table f ON f.refund_orderid=o.order_id  WHERE (d.delivery_phone=phone OR c.customer_phone =phone)  AND o.order_orderid=orderId;
    
/*SELECT GROUP_CONCAT(CONCAT(ordet_producpackid, ',', order_batchid, ',', ordet_quantity,',',ordet_status,',',ordet_active,',',ordet_cron,',',order_prdate,',',order_shipped,',',order_delivered,',',order_cancelled,',',order_refund,',',order_cancelReason) SEPARATOR '##') INTO suppliers
FROM order_details d JOIN orders_tbl o ON d.ordet_order=o.order_id WHERE o.order_orderid=orderId  AND o.order_customer=userid;*/

/*SELECT GROUP_CONCAT(CONCAT(ordet_producpackid, ',', order_batchid, ',', ordet_quantity,',',ordet_status,',',ordet_active,',',ordet_cron,',',order_prdate,',',COALESCE(order_prdate,''),',',COALESCE(order_shipped,''),',',COALESCE(order_delivered,''),',',COALESCE(order_cancelled,''),',',COALESCE(order_refund,''),',',COALESCE(order_cancelReason,'')) SEPARATOR '##')INTO suppliers FROM(SELECT ordet_producpackid, order_batchid, SUM(ordet_quantity) AS ordet_quantity,ordet_status,ordet_active,ordet_cron,order_prdate,order_shipped,order_delivered,order_cancelled,order_refund,order_cancelReason FROM order_details d JOIN orders_tbl o ON d.ordet_order=o.order_id JOIN customers_tbl c ON c.customer_id=o.order_customer JOIN delivery_address a ON a.delivery_id=o.order_deliverId WHERE o.order_orderid=orderId AND (a.delivery_phone=phone OR c.customer_phone=phone) GROUP BY ordet_cartid) AS X;
*/


SELECT GROUP_CONCAT(CONCAT(ordet_producpackid, ',', order_batchid, ',', ordet_quantity,',',ordet_status,',',ordet_active,',',COALESCE(ordet_cron,''),',',COALESCE(order_prdate,''),',',COALESCE(order_shipped,''),',',COALESCE(order_delivered,''),',',COALESCE(order_cancelled,''),',',COALESCE(order_refund,''),',',COALESCE(order_cancelReason,''),',',order_mrp,',',order_msp,',',order_disc) SEPARATOR '##') INTO suppliers
FROM order_details d JOIN orders_tbl o ON d.ordet_order=o.order_id 
JOIN customers_tbl c ON c.customer_id = o.order_customer
    JOIN delivery_address a ON a.delivery_id = o.order_deliverId   WHERE o.order_orderid = orderId
      AND (a.delivery_phone = phone
           OR c.customer_phone = phone);

IF trim(suppliers) <> '' THEN
 SET @text := TRIM(BOTH '##' FROM suppliers);
  		SET @strLen := 0;
  		SET @i := 1;
  		WHILE @strLen < LENGTH(@text) DO
        SET @str := SUBSTRING_INDEX(@text, '##', @i);
    		SET @strLen := LENGTH(@str);
             SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
             SET @GRAPE := TRIM(BOTH ',' FROM @GRPS);
  	 		SET @strGLen := 0;
     		SET @Gi := 1;
     		SET @icols := 1;
           WHILE @strGLen < LENGTH(@GRAPE) DO
		       	SET @Gstr := SUBSTRING_INDEX(@GRAPE, ',', @Gi);
               	SET @strGLen := LENGTH(@Gstr);
               	SET @Gi := @Gi + 1;
                IF @icols = 1 THEN
                   	SET @pack := SUBSTRING_INDEX(@Gstr, ',', -1);
                    ELSEIF @icols = 2 THEN
                    SET @batch := SUBSTRING_INDEX(@Gstr, ',', -1);
                      ELSEIF @icols = 3 THEN
                     SET @qty := SUBSTRING_INDEX(@Gstr, ',', -1);
                     ELSEIF @icols = 4 THEN
                     SET @orderstatus := SUBSTRING_INDEX(@Gstr, ',', -1);
                     ELSEIF @icols = 5 THEN
                       SET @deliverystatus := SUBSTRING_INDEX(@Gstr, ',', -1);
                 ELSEIF @icols = 6 THEN
                       SET @ordcrton := SUBSTRING_INDEX(@Gstr, ',', -1);
                 ELSEIF @icols = 7 THEN
                       SET @ordproc := SUBSTRING_INDEX(@Gstr, ',', -1);
                 ELSEIF @icols = 8 THEN
                       SET @ordship := SUBSTRING_INDEX(@Gstr, ',', -1);
                 ELSEIF @icols = 9 THEN
                       SET @orddeliv := SUBSTRING_INDEX(@Gstr, ',', -1);
                ELSEIF @icols = 10 THEN
                       SET @ordcancl := SUBSTRING_INDEX(@Gstr, ',', -1);
                       ELSEIF @icols = 11 THEN
                       SET @ordref := SUBSTRING_INDEX(@Gstr, ',', -1);
                       ELSEIF @icols = 12 THEN
                       SET @remarks := SUBSTRING_INDEX(@Gstr, ',', -1);
                       
                       ELSEIF @icols = 13 THEN
                       SET @mrp := SUBSTRING_INDEX(@Gstr, ',', -1);
                       
                       ELSEIF @icols = 14 THEN
                       SET @msp := SUBSTRING_INDEX(@Gstr, ',', -1);
                       ELSE
                       SET @disc := SUBSTRING_INDEX(@Gstr, ',', -1);
                END IF;
        		SET @icols := @icols + 1;
                SET @ordcrton  = NULLIF(@ordcrton, '');
SET @ordproc   = NULLIF(@ordproc, '');
SET @ordship   = NULLIF(@ordship, '');
SET @orddeliv  = NULLIF(@orddeliv, '');
SET @ordcancl  = NULLIF(@ordcancl, '');
SET @ordref    = NULLIF(@ordref, '');
           	END WHILE;
            INSERT INTO temp_cartdetails(product_id,
        product_name,
    product_display,
    product_featured ,
    product_popular,
    prodpack_id,
    prodpack_quantity,
    packing_type,
    measunit_name,
    measunit_shortname,
    strstk_mrp,
    strstk_msp,
    stockin_batch,
    stockin_expiry,
    strstk_stock,
    strstk_stack,
    product_imageurl,
    strstk_discount,
    strstk_id,prd_qty,orderstatus,deliverystatus,ordcrton,ordproc,ordship,orddeliv,ordcancl,ordref,remarks)
            SELECT p.product_id,p.product_name,p.product_display,p.product_featured,p.product_popular,r.prodpack_id,r.prodpack_quantity,t.packing_type,m.measunit_name,
m.measunit_shortname,@mrp,@msp,s.stockin_batch,s.stockin_expiry,e.strstk_stock,e.strstk_stack,(select g.prodgal_url  from product_gallery g where g.prodgal_prodpack = r.prodpack_id and  g.prodgal_placedat = 1 and g.prodgal_medium = 1 and g.prodgal_publish = 1 and g.prodgal_status = 1 order by g.prodgal_serial asc limit 1) as product_imageurl,@disc, e.strstk_id,@qty,@orderstatus,@deliverystatus,@ordcrton,@ordproc,@ordship,@orddeliv,@ordcancl,@ordref,@remarks from products_tbl p join product_packing r on r.prodpack_product = p.product_id join packing_tbl t on t.packing_id = r.prodpack_package join measure_units m on m.measunit_id = r.prodpack_unit  join  stock_inwards s on s.stockin_item = r.prodpack_id join storestock_pricing e on e.strstk_item = r.prodpack_id and s.stockin_id=e.strstk_refer
WHERE  e.strstk_item = @pack and e.strstk_id = @batch;
    		SET @i := @i + 1;
            END WHILE;
      SELECT * FROM temp_cartdetails;
END IF;


END$$

CREATE  PROCEDURE `getTransferPackets` (IN `stkordid` INT)   BEGIN
	SELECT t.transpack_id, t.transpack_packid, t.transpack_trackid, t.transpack_from, sfr.store_name AS fromstore, 
    t.transpack_to, sto.store_name AS tostore, t.transpack_items, t.transpack_collectby, t.transpack_status
    FROM transfer_packets t 
    LEFT JOIN stores_tbl sfr ON sfr.store_id = t.transpack_from 
    LEFT JOIN stores_tbl sto ON sto.store_id = t.transpack_to 
    WHERE t.transpack_refer = stkordid;
END$$

CREATE  PROCEDURE `getUserAllOrderDetailsbyUserId` (IN `userid` INT, IN `status_list` TEXT, IN `time_filter` TEXT, IN `final_date` VARCHAR(225))   BEGIN

/*SELECT o.order_orderid,DATE_FORMAT(o.order_date, '%M %d, %Y') as order_date,o.order_delivery, DATE_FORMAT(o.orders_delivered, 'On %a, %d %b') as orders_delivered,o.order_status,DATE_FORMAT(o.orders_cancelled, 'On %a, %d %b')as orders_cancelled, p.product_id,p.product_name,p.product_display,r.prodpack_id,t.packing_type,m.measunit_name,
m.measunit_shortname,(select g.prodgal_url  from product_gallery g where g.prodgal_prodpack = r.prodpack_id and  g.prodgal_placedat = 1 and g.prodgal_medium = 1 and g.prodgal_publish = 1 and g.prodgal_status = 1 order by g.prodgal_serial asc limit 1) as product_imageurl, e.strstk_id FROM customers_tbl c JOIN orders_tbl o ON o.order_customer =c.customer_id JOIN order_details d ON d.ordet_order=o.order_id JOIN products_tbl p ON p.product_id=d.ordet_productid join product_packing r on r.prodpack_product = p.product_id join packing_tbl t on t.packing_id = r.prodpack_package join measure_units m on m.measunit_id = r.prodpack_unit  join  stock_inwards s on s.stockin_item = r.prodpack_id join storestock_pricing e on e.strstk_item = r.prodpack_id and s.stockin_id=e.strstk_refer  WHERE c.customer_id=userid AND c.customer_type=1 and e.strstk_item = d.ordet_producpackid and e.strstk_id=d.order_batchid order by o.order_id DESC  ;
*/
 DECLARE base_sql TEXT;
    DECLARE status_sql,cancelled_sql TEXT DEFAULT '';
    DECLARE date_sql TEXT DEFAULT '';
    DECLARE full_sql TEXT;
    DECLARE phone VARCHAR(255) DEFAULT '';
    
SELECT c.customer_phone INTO phone FROM customers_tbl c WHERE c.customer_id=userid;

    -- Filter: status
    
    SET status_sql = '';

IF status_list != '' THEN
    SET status_sql = CONCAT(
        ' AND (',

        /* Cancelled */
        ' (FIND_IN_SET(0, "', status_list, '") AND o.order_status = 0)',

        ' OR ',

        /* Returned */
        ' (FIND_IN_SET(2, "', status_list, '") AND o.order_status = 2)',

        ' OR ',

        /* Placed / Processing */
        ' (FIND_IN_SET(1, "', status_list, '") 
            AND o.order_status = 1 
            AND o.order_delivery IN (1,2,3))',

        ' OR ',

        /* Delivered */
        ' (FIND_IN_SET(4, "', status_list, '") 
            AND o.order_status = 1 
            AND o.order_delivery = 4)',

        ' )'
    );
END IF;

/*IF status_list != '' THEN
 
    SET status_sql = CONCAT(
        ' AND o.order_delivery IN (', status_list, ')');
       
END IF;*/


    -- Filter: time
    IF time_filter = 'Last 30 days' THEN
        SET date_sql = " AND o.order_date >= CURDATE() - INTERVAL 30 DAY";
    ELSEIF time_filter = 'Older' THEN
        SET date_sql = CONCAT(' AND YEAR(o.order_date) < ', final_date);
     ELSEIF time_filter LIKE '%,%' THEN
        SET date_sql = CONCAT(" AND FIND_IN_SET(YEAR(o.order_date), '", time_filter, "') > 0");

    -- ✅ SINGLE YEAR FILTER (e.g. '2023')
    ELSEIF time_filter REGEXP '^[0-9]{4}$' THEN
        SET date_sql = CONCAT(" AND YEAR(o.order_date) = ", time_filter);
        ELSE
        SET date_sql = "";
    END IF;

    -- Base Query
   
SET @sql  = CONCAT(
    '
    (SELECT 
        o.order_orderid,
        DATE_FORMAT(o.order_date, "%M %d, %Y") AS order_date,
        o.order_delivery,
        DATE_FORMAT(o.orders_delivered, "On %a, %d %b") AS orders_delivered,
            DATE_FORMAT(o.orders_shipped, "On %a, %d %b") AS orders_shipped,
        o.order_status,
        DATE_FORMAT(o.orders_cancelled, "On %a, %d %b") AS orders_cancelled,
    h.return_status,DATE_FORMAT(h.status_date, "On %a, %d %b") AS status_date ,DATE_FORMAT(h.approved_date, "On %a, %d %b") AS approved_date ,DATE_FORMAT(h.pickup_date, "On %a, %d %b") AS pickup_date,DATE_FORMAT(h.refund_date, "On %a, %d %b") AS refund_date,
        null AS product_id,
        null AS product_name,
        null AS product_display,
        null AS prodpack_id,
        null AS packing_type,
        null AS measunit_name,
        null AS measunit_shortname,
        null  AS product_imageurl,
        null AS strstk_id,
        o.order_quick,
        o.order_quick_status,DATE_FORMAT(order_quick_processed, "On %a, %d %b") AS order_quick_processed
     FROM 
        customers_tbl c
     JOIN orders_tbl o ON o.order_customer = c.customer_id
    LEFT JOIN order_return_status_history h ON h.order_id=o.order_id
    
     WHERE 
        c.customer_id = ', userid, '
        AND c.customer_type = 1
       
        AND o.order_quick=1 ', status_sql, date_sql, '
   
          )
    UNION
    
    ',cancelled_sql,'
    (SELECT 
        o.order_orderid,
        DATE_FORMAT(o.order_date, "%M %d, %Y") AS order_date,
        o.order_delivery,
        DATE_FORMAT(o.orders_delivered, "On %a, %d %b") AS orders_delivered,
            DATE_FORMAT(o.orders_shipped, "On %a, %d %b") AS orders_shipped,
        o.order_status,
        DATE_FORMAT(o.orders_cancelled, "On %a, %d %b") AS orders_cancelled,
    h.return_status,DATE_FORMAT(h.status_date, "On %a, %d %b") AS status_date ,DATE_FORMAT(h.approved_date, "On %a, %d %b") AS approved_date ,DATE_FORMAT(h.pickup_date, "On %a, %d %b") AS pickup_date,DATE_FORMAT(h.refund_date, "On %a, %d %b") AS refund_date,
        p.product_id,
        p.product_name,
        p.product_display,
        r.prodpack_id,
        t.packing_type,
        m.measunit_name,
        m.measunit_shortname,
        (SELECT g.prodgal_url
         FROM product_gallery g
         WHERE g.prodgal_prodpack = r.prodpack_id
           AND g.prodgal_placedat = 1
           AND g.prodgal_medium = 1
           AND g.prodgal_publish = 1
           AND g.prodgal_status = 1
         ORDER BY g.prodgal_serial ASC
         LIMIT 1) AS product_imageurl,
        e.strstk_id,
    o.order_quick,
        o.order_quick_status,DATE_FORMAT(order_quick_processed, "On %a, %d %b") AS order_quick_processed
     FROM 
        customers_tbl c
     JOIN orders_tbl o ON o.order_customer = c.customer_id
    LEFT JOIN order_return_status_history h ON h.order_id=o.order_id
     JOIN order_details d ON d.ordet_order = o.order_id
     JOIN products_tbl p ON p.product_id = d.ordet_productid
     JOIN product_packing r ON r.prodpack_product = p.product_id
     JOIN packing_tbl t ON t.packing_id = r.prodpack_package
     JOIN measure_units m ON m.measunit_id = r.prodpack_unit
     JOIN stock_inwards s ON s.stockin_item = r.prodpack_id
     JOIN storestock_pricing e ON e.strstk_item = r.prodpack_id AND s.stockin_id = e.strstk_refer
     WHERE 
        c.customer_id = ', userid, '
        AND c.customer_type = 1
        AND e.strstk_item = d.ordet_producpackid
   
        AND e.strstk_id = d.order_batchid ', status_sql, date_sql, ' )
UNION
( 
     SELECT 
        o.order_orderid,
        DATE_FORMAT(o.order_date, "%M %d, %Y") AS order_date,
        o.order_delivery,
        DATE_FORMAT(o.orders_delivered, "On %a, %d %b") AS orders_delivered,
                DATE_FORMAT(o.orders_shipped, "On %a, %d %b") AS orders_shipped,
        o.order_status,
        DATE_FORMAT(o.orders_cancelled, "On %a, %d %b") AS orders_cancelled,
    h.return_status,DATE_FORMAT(h.status_date, "On %a, %d %b") AS status_date ,DATE_FORMAT(h.approved_date, "On %a, %d %b") AS approved_date ,DATE_FORMAT(h.pickup_date, "On %a, %d %b") AS pickup_date,DATE_FORMAT(h.refund_date, "On %a, %d %b") AS refund_date,

        p.product_id,
        p.product_name,
        p.product_display,
        r.prodpack_id,
        t.packing_type,
        m.measunit_name,
        m.measunit_shortname,
        (SELECT g.prodgal_url
         FROM product_gallery g
         WHERE g.prodgal_prodpack = r.prodpack_id
           AND g.prodgal_placedat = 1
           AND g.prodgal_medium = 1
           AND g.prodgal_publish = 1
           AND g.prodgal_status = 1
         ORDER BY g.prodgal_serial ASC
         LIMIT 1) AS product_imageurl,
        e.strstk_id,
    o.order_quick,
        o.order_quick_status,DATE_FORMAT(order_quick_processed, "On %a, %d %b") AS order_quick_processed
     FROM 
        customers_tbl c
     JOIN orders_tbl o ON o.order_customer = c.customer_id
    LEFT JOIN order_return_status_history h ON h.order_id=o.order_id

     JOIN delivery_address dd ON o.order_deliverId = dd.delivery_id
     JOIN order_details d ON d.ordet_order = o.order_id
     JOIN products_tbl p ON p.product_id = d.ordet_productid
     JOIN product_packing r ON r.prodpack_product = p.product_id
     JOIN packing_tbl t ON t.packing_id = r.prodpack_package
     JOIN measure_units m ON m.measunit_id = r.prodpack_unit
     JOIN stock_inwards s ON s.stockin_item = r.prodpack_id
     JOIN storestock_pricing e ON e.strstk_item = r.prodpack_id AND s.stockin_id = e.strstk_refer
     WHERE 
        dd.delivery_phone = ', phone, '
        AND c.customer_type = 1
        AND e.strstk_item = d.ordet_producpackid
        AND e.strstk_id = d.order_batchid ', status_sql, date_sql, ' ) ORDER BY order_orderid DESC

');


    -- Combine final query
   
    -- Prepare and Execute
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

END$$

CREATE  PROCEDURE `getUserByID` (IN `id` INT)   begin
select u.user_id,u.user_login,u.user_password,u.user_staffid,u.user_staffname,u.user_programid,u.user_programcontains,up.usrprog_name,u.user_status from users_tbl u join user_program up on u.user_programid = up.usrprog_id where u.user_id = id;
 END$$

CREATE  PROCEDURE `getUserCredentials` (IN `phone` VARCHAR(50), IN `pass` VARCHAR(50), IN `flag` INT)   BEGIN
declare ids,counts int;
if flag=1 THEN
SELECT count(*) INTO counts FROM customers_tbl c WHERE (c.customer_phone = phone OR c.customer_email=phone) and c.customer_type=1;
IF(counts=1)THEN
IF EXISTS (
    SELECT customer_id
    FROM customers_tbl
    WHERE (customer_phone = phone OR customer_email = phone)
    AND customer_password = pass
) THEN
    SELECT customer_id INTO ids
    FROM customers_tbl
    WHERE (customer_phone = phone OR customer_email = phone)
    AND customer_password = pass;
 SELECT ids;
 ELSE
 SELECT "wrong password";
 END IF;
 
ELSE
 SELECT "not exists";
 END IF;

END IF;
END$$

CREATE  PROCEDURE `getUserCredentialsbyPhone` (IN `phone` VARCHAR(50))   BEGIN
declare ids,counts int;

SELECT count(*) INTO counts FROM customers_tbl c WHERE (c.customer_phone = phone) and c.customer_type=1;
IF(counts=1)THEN
IF EXISTS (
    SELECT customer_id
    FROM customers_tbl
    WHERE customer_phone = phone AND customer_type=1
    
) THEN
    SELECT customer_id INTO ids
    FROM customers_tbl
    WHERE customer_phone = phone AND customer_type=1;
   
 SELECT ids;

 END IF;
 
ELSE
 SELECT "not exists";
 END IF;

END$$

CREATE  PROCEDURE `getUserDetailsbyID` (IN `customer_id` INT)   BEGIN
SELECT c.customer_number,c.customer_name,c.customer_phone,c.customer_email,c.customer_gender,c.customer_age FROM customers_tbl c WHERE c.customer_id=customer_id AND c.customer_type=1;
END$$

CREATE  PROCEDURE `getUserOrderDetailsbyOrderId` (IN `orderId` VARCHAR(200), IN `userid` INT)   BEGIN
DECLARE suppliers  TEXT;
DECLARE quickorder INT DEFAULT 0;
DROP TEMPORARY TABLE IF EXISTS temp_cartdetails;
CREATE TEMPORARY TABLE temp_cartdetails (
        product_id INT,
        product_name VARCHAR(255),
    product_display VARCHAR(255),
    product_featured INT,
    product_popular INT,
    prodpack_id INT,
    prodpack_quantity INT,
    packing_type VARCHAR(255),
    measunit_name VARCHAR(255),
    measunit_shortname VARCHAR(255),
    strstk_mrp DECIMAL(9, 2),
    strstk_msp DECIMAL(9, 2),
    stockin_batch VARCHAR(50),
    stockin_expiry DATE,
    strstk_stock INT,
    strstk_stack INT,
    product_imageurl VARCHAR(255),
    strstk_discount	DECIMAL(5, 2),
    strstk_id INT,prd_qty INT,orderstatus INT,deliverystatus INT,ordcrton DATETIME,ordproc DATETIME,ordship DATETIME,orddeliv DATETIME, ordcancl DATETIME, ordref DATETIME, remarks TEXT);
    SELECT d.delivery_to,d.delivery_phone,d.delivery_email,d.delivery_pin,d.delivery_house,d.delivery_street,d.delivery_landmark,d.delivery_city,d.delivery_state,d.delivery_type,DATE_FORMAT(o.order_date, '%M %d, %Y at %l:%i %p') AS order_date,o.orders_delivered,o.orders_shipped,o.orders_cancelled,o.order_delivery,o.order_status,DATEDIFF(CURDATE(), o.orders_delivered) AS days_difference,r.return_status,DATE_FORMAT(r.status_date, '%M %d, %Y at %l:%i %p') AS status_date ,DATE_FORMAT(r.approved_date, '%M %d, %Y at %l:%i %p') AS approved_date ,DATE_FORMAT(r.pickup_date, '%M %d, %Y at %l:%i %p') AS pickup_date,DATE_FORMAT(r.refund_date, '%M %d, %Y at %l:%i %p') AS refund_date,o.order_quick_status,
o.order_quick,DATE_FORMAT(o.order_quick_processed, '%M %d, %Y at %l:%i %p') AS order_quick_processed,DATEDIFF(CURDATE(), o.order_quick_processed) AS days_datedifference,f.refund_paymentid,f.refund_amount,DATE_FORMAT(f.refund_created, '%M %d, %Y at %l:%i %p') AS refund_created FROM delivery_address d JOIN  orders_tbl o ON o.order_deliverId=d.delivery_id AND d.delivery_user=o.order_customer LEFT JOIN order_return_status_history r ON r.order_id=o.order_id LEFT JOIN refund_table f ON f.refund_orderid=o.order_id  WHERE d.delivery_user=userid  AND o.order_orderid=orderId;
    
   SELECT GROUP_CONCAT(CONCAT(ordet_producpackid, ',', order_batchid, ',', ordet_quantity,',',ordet_status,',',ordet_active,',',ordet_cron,',',COALESCE(order_prdate,''),',',COALESCE(order_shipped,''),',',COALESCE(order_delivered,''),',',COALESCE(order_cancelled,''),',',COALESCE(order_refund,''),',',COALESCE(order_cancelReason,''),',',order_mrp,',',order_msp,',',order_disc) SEPARATOR '##') INTO suppliers
FROM order_details d JOIN orders_tbl o ON d.ordet_order=o.order_id WHERE o.order_orderid=orderId  AND o.order_customer=userid;

IF quickorder=0 THEN

IF trim(suppliers) <> '' THEN
 SET @text := TRIM(BOTH '##' FROM suppliers);
  		SET @strLen := 0;
  		SET @i := 1;
  		WHILE @strLen < LENGTH(@text) DO
        SET @str := SUBSTRING_INDEX(@text, '##', @i);
    		SET @strLen := LENGTH(@str);
             SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
             SET @GRAPE := TRIM(BOTH ',' FROM @GRPS);
  	 		SET @strGLen := 0;
     		SET @Gi := 1;
     		SET @icols := 1;
           WHILE @strGLen < LENGTH(@GRAPE) DO
		       	SET @Gstr := SUBSTRING_INDEX(@GRAPE, ',', @Gi);
               	SET @strGLen := LENGTH(@Gstr);
               	SET @Gi := @Gi + 1;
                IF @icols = 1 THEN
                   	SET @pack := SUBSTRING_INDEX(@Gstr, ',', -1);
                    ELSEIF @icols = 2 THEN
                    SET @batch := SUBSTRING_INDEX(@Gstr, ',', -1);
                      ELSEIF @icols = 3 THEN
                     SET @qty := SUBSTRING_INDEX(@Gstr, ',', -1);
                     ELSEIF @icols = 4 THEN
                     SET @orderstatus := SUBSTRING_INDEX(@Gstr, ',', -1);
                     ELSEIF @icols = 5 THEN
                       SET @deliverystatus := SUBSTRING_INDEX(@Gstr, ',', -1);
                 ELSEIF @icols = 6 THEN
                       SET @ordcrton := SUBSTRING_INDEX(@Gstr, ',', -1);
                 ELSEIF @icols = 7 THEN
                       SET @ordproc := SUBSTRING_INDEX(@Gstr, ',', -1);
                 ELSEIF @icols = 8 THEN
                       SET @ordship := SUBSTRING_INDEX(@Gstr, ',', -1);
                 ELSEIF @icols = 9 THEN
                       SET @orddeliv := SUBSTRING_INDEX(@Gstr, ',', -1);
                ELSEIF @icols = 10 THEN
                       SET @ordcancl := SUBSTRING_INDEX(@Gstr, ',', -1);
                       ELSEIF @icols = 11 THEN
                       SET @ordref := SUBSTRING_INDEX(@Gstr, ',', -1);
                       ELSEIF @icols = 12 THEN
                       SET @remarks := SUBSTRING_INDEX(@Gstr, ',', -1);
                       
                       ELSEIF @icols = 13 THEN
                       SET @mrp := SUBSTRING_INDEX(@Gstr, ',', -1);
                       
                       ELSEIF @icols = 14 THEN
                       SET @msp := SUBSTRING_INDEX(@Gstr, ',', -1);
                       ELSE
                       SET @disc := SUBSTRING_INDEX(@Gstr, ',', -1);
                END IF;
        		SET @icols := @icols + 1;
                
                SET @ordcrton  = NULLIF(@ordcrton, '');
SET @ordproc   = NULLIF(@ordproc, '');
SET @ordship   = NULLIF(@ordship, '');
SET @orddeliv  = NULLIF(@orddeliv, '');
SET @ordcancl  = NULLIF(@ordcancl, '');
SET @ordref    = NULLIF(@ordref, '');
           	END WHILE;
            
            
            INSERT INTO temp_cartdetails(product_id,
        product_name,
    product_display,
    product_featured ,
    product_popular,
    prodpack_id,
    prodpack_quantity,
    packing_type,
    measunit_name,
    measunit_shortname,
    strstk_mrp,
    strstk_msp,
    stockin_batch,
    stockin_expiry,
    strstk_stock,
    strstk_stack,
    product_imageurl,
    strstk_discount,
    strstk_id,prd_qty,orderstatus,deliverystatus,ordcrton,ordproc,ordship,orddeliv,ordcancl,ordref,remarks)
            SELECT p.product_id,p.product_name,p.product_display,p.product_featured,p.product_popular,r.prodpack_id,r.prodpack_quantity,t.packing_type,m.measunit_name,
m.measunit_shortname,@mrp,@msp,s.stockin_batch,s.stockin_expiry,e.strstk_stock,e.strstk_stack,(select g.prodgal_url  from product_gallery g where g.prodgal_prodpack = r.prodpack_id and  g.prodgal_placedat = 1 and g.prodgal_medium = 1 and g.prodgal_publish = 1 and g.prodgal_status = 1 order by g.prodgal_serial asc limit 1) as product_imageurl,@disc, e.strstk_id,@qty,@orderstatus,@deliverystatus,@ordcrton,@ordproc,@ordship,@orddeliv,@ordcancl,@ordref,@remarks from products_tbl p join product_packing r on r.prodpack_product = p.product_id join packing_tbl t on t.packing_id = r.prodpack_package join measure_units m on m.measunit_id = r.prodpack_unit  join  stock_inwards s on s.stockin_item = r.prodpack_id join storestock_pricing e on e.strstk_item = r.prodpack_id and s.stockin_id=e.strstk_refer
WHERE p.product_status = 1 and p.product_online = 1 and p.product_publish=1 and e.strstk_item = @pack and e.strstk_id = @batch;
    		SET @i := @i + 1;
            END WHILE;
      SELECT * FROM temp_cartdetails;
       
END IF;
 
      END IF;
      
END$$

CREATE  PROCEDURE `getUserPrograms` ()   begin


select u.usrprog_id,u.usrprog_name,u.usrprog_programs,u.usrprog_crtby from user_program u ;

END$$

CREATE  PROCEDURE `getUserQucikOrderDetailsbyOrderId` (IN `orderId` VARCHAR(200), IN `userid` INT)   BEGIN

    SELECT d.delivery_to,d.delivery_phone,d.delivery_email,d.delivery_pin,d.delivery_house,d.delivery_street,d.delivery_landmark,d.delivery_city,d.delivery_state,d.delivery_type,DATE_FORMAT(o.order_date, '%M %d, %Y at %l:%i %p') AS order_date,o.order_quick_status,o.orders_cancelled,o.order_status,DATE_FORMAT(o.order_quick_processed, '%M %d, %Y at %l:%i %p') AS order_processed,DATEDIFF(CURDATE(), o.order_quick_processed) AS days_difference FROM delivery_address d JOIN  orders_tbl o ON o.order_deliverId=d.delivery_id AND d.delivery_user=o.order_customer  WHERE d.delivery_user=userid  AND o.order_orderid=orderId AND o.order_quick=1;
    
 
END$$

CREATE  PROCEDURE `getUsersList` ()   begin
select u.user_id,u.user_login,u.user_staffid,u.user_staffname,u.user_status from users_tbl u;
END$$

CREATE  PROCEDURE `getVendorPOsforInvoice` (IN `vtype` INT, IN `vendor` INT)   BEGIN
    	SELECT x.purchord_id, x.purchord_ref, x.purchord_date ,x.purchord_deliverat,s.store_GST,s.store_name
        FROM purchase_orders x  INNER JOIN stores_tbl s ON s.store_id=x.purchord_deliverat
        WHERE x.purchord_vendtype = vtype AND x.purchord_vendor = vendor AND  x.purchord_status > 0 AND x.purchord_issuedby > 0 and ((select count(*) from purchase_details pd where pd.podetail_order = x.purchord_id) <> (select count(*)  from invoice_details id where id.invdet_porder = x.purchord_id))
        ORDER BY x.purchord_date;
END$$

CREATE  PROCEDURE `getVendorProductSupplies` (IN `vtype` INT, IN `vendid` INT, IN `product` INT)   BEGIN
	SELECT x.vendsup_id, x.vendsup_packing, p.packing_type, pp.prodpack_hsn, pp.prodpack_taxgroup,
    x.vendsup_price, x.vendsup_minqty, x.vendsup_maxqty, x.vendsup_eoq, x.vendsup_deliver,CONCAT(p.packing_type, ' ', pp.prodpack_quantity, ' ', m.measunit_shortname) AS boxunit
    FROM vendor_supplies x
    LEFT JOIN product_packing pp on x.vendsup_packing = pp.prodpack_id
    LEFT JOIN packing_tbl p ON p.packing_id = pp.prodpack_package
    LEFT JOIN measure_units m ON m.measunit_id =pp.prodpack_unit
    WHERE x.vendsup_type = vtype AND x.vendsup_vendor = vendid
    AND x.vendsup_product = product AND x.vendsup_status = 1
    ORDER BY x.vendsup_packing;
END$$

CREATE  PROCEDURE `get_slider` ()   BEGIN
SELECT `slider_id`, `slider_type`, `slider_image`,  `slider_disocunt`, `slider_disctype`, `slider_sort`, `slider_status`,
    
      IFNULL( (SELECT GROUP_CONCAT(p.product_name SEPARATOR ', ')
        FROM products_tbl p
        WHERE FIND_IN_SET(p.product_id, h.slider_product)),'') AS slider_products  FROM tbl_homepageslier h;
END$$

CREATE  PROCEDURE `globalsearchProductByName` (IN `prdname` VARCHAR(200))   BEGIN
if prdname!='' then
select x.product_id,x.product_name,x.product_display,x.product_featured,x.product_popular,x.prodpack_id,x.prodpack_quantity,x.prodpack_maxstock,x.prodpack_minstock,x.packing_type,x.measunit_name,
x.measunit_shortname,x.strstk_mrp,x.strstk_msp,x.stockin_batch,x.stockin_expiry,x.strstk_stock,x.strstk_stack, x.product_imageurl from (SELECT ( @row_number := @row_number + 1) AS virtual_id,p.product_id,p.product_name,p.product_display,p.product_featured,p.product_popular,r.prodpack_id,r.prodpack_quantity,r.prodpack_maxstock,r.prodpack_minstock,t.packing_type,m.measunit_name,
m.measunit_shortname,e.strstk_mrp,e.strstk_msp,s.stockin_batch,s.stockin_expiry,e.strstk_stock,e.strstk_stack,(select g.prodgal_url  from product_gallery g where g.prodgal_prodpack = r.prodpack_id and  g.prodgal_placedat = 1 and g.prodgal_medium = 1 and g.prodgal_publish = 1 and g.prodgal_status = 1 order by g.prodgal_serial asc limit 1) as product_imageurl from products_tbl p join product_packing r on r.prodpack_product = p.product_id join packing_tbl t on t.packing_id = r.prodpack_package join measure_units m on m.measunit_id = r.prodpack_unit  join  stock_inwards s on s.stockin_item = r.prodpack_id join storestock_pricing e on e.strstk_item = r.prodpack_id
                                                                  
WHERE p.product_name like concat(prdname,'%') and p.product_status = 1 and p.product_online = 1 and p.product_publish=1 and s.stockin_expiry >= CURRENT_DATE() order by s.stockin_expiry asc) as x group by x.product_id UNION select x.product_id,x.product_name,x.product_display,x.product_featured,x.product_popular,x.prodpack_id,x.prodpack_quantity,x.prodpack_maxstock,x.prodpack_minstock,x.packing_type,x.measunit_name,
x.measunit_shortname,x.strstk_mrp,x.strstk_msp,x.stockin_batch,x.stockin_expiry,x.strstk_stock,x.strstk_stack, x.product_imageurl from (SELECT ( @row_number := @row_number + 1) AS virtual_id,p.product_id,p.product_name,p.product_display,p.product_featured,p.product_popular,r.prodpack_id,r.prodpack_quantity,r.prodpack_maxstock,r.prodpack_minstock,t.packing_type,m.measunit_name,p.product_generic,
m.measunit_shortname,e.strstk_mrp,e.strstk_msp,s.stockin_batch,s.stockin_expiry,e.strstk_stock,e.strstk_stack,(select g.prodgal_url  from product_gallery g where g.prodgal_prodpack = r.prodpack_id and  g.prodgal_placedat = 1 and g.prodgal_medium = 1 and g.prodgal_publish = 1 and g.prodgal_status = 1 order by g.prodgal_serial asc limit 1) as product_imageurl from products_tbl p join product_packing r on r.prodpack_product = p.product_id join packing_tbl t on t.packing_id = r.prodpack_package join measure_units m on m.measunit_id = r.prodpack_unit  join  stock_inwards s on s.stockin_item = r.prodpack_id join storestock_pricing e on e.strstk_item = r.prodpack_id LEFT JOIN generic_medicines j ON j.genmed_id=p.product_generic
                                                                  
WHERE j.genmed_name like concat('%',prdname,'%') and p.product_status = 1 and p.product_online = 1 and p.product_publish=1 and s.stockin_expiry >= CURRENT_DATE() order by s.stockin_expiry asc) as x group by x.product_id;
END IF;
END$$

CREATE  PROCEDURE `hourlySalesAnalysisByStores` (IN `storeid` INT, IN `fdate` DATE)   BEGIN

SELECT s.store_id,s.store_code,s.store_name FROM stores_tbl s WHERE s.store_status=1;

    SELECT 
        DATE(b.bill_crtdon) AS bill_date,
        CASE
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '07:01' AND '08:00' THEN '07:01 to 08:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '08:01' AND '09:00' THEN '08:01 to 09:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '09:01' AND '10:00' THEN '09:01 to 10:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '10:01' AND '11:00' THEN '10:01 to 11:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '11:01' AND '12:00' THEN '11:01 to 12:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '12:01' AND '13:00' THEN '12:01 to 13:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '13:01' AND '14:00' THEN '13:01 to 14:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '14:01' AND '15:00' THEN '14:01 to 15:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '15:01' AND '16:00' THEN '15:01 to 16:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '16:01' AND '17:00' THEN '16:01 to 17:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '17:01' AND '18:00' THEN '17:01 to 18:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '18:01' AND '19:00' THEN '18:01 to 19:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '19:01' AND '20:00' THEN '19:01 to 20:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '20:01' AND '21:00' THEN '20:01 to 21:00'
            WHEN DATE_FORMAT(b.bill_crtdon, '%H:%i') BETWEEN '21:01' AND '22:00' THEN '21:01 to 22:00'
        END AS time_interval,
        COUNT(b.bill_id) AS total_bills,
        SUM(b.bill_netpay) AS total_amount,ss.store_code,ss.store_name,ss.store_id
    FROM bills_table b
   /* LEFT JOIN bill_items bt ON bt.billit_id = b.bill_id */
    LEFT JOIN stores_tbl ss ON ss.store_id=b.bill_store
    WHERE 
        b.bill_store = storeid 
        AND b.bill_date = fdate
    GROUP BY bill_date, time_interval
    ORDER BY bill_date, time_interval;

END$$

CREATE  PROCEDURE `inlineSaveForHomeMenuOffers` (IN `ids` INT, IN `datalist` INT, IN `content` VARCHAR(225))   BEGIN

IF datalist=1 THEN

UPDATE home_menu_offer SET 	menu_caption=content WHERE menu_id=ids;
 ELSEIF datalist=2 THEN
UPDATE home_menu_offer SET 	menu_discount=content WHERE menu_id=ids;

ELSE
UPDATE home_menu_offer SET 	menu_disctype=content WHERE menu_id=ids;

END IF;
END$$

CREATE  PROCEDURE `inlineSaveForHomeSlider` (IN `ids` INT, IN `content` VARCHAR(225))   BEGIN


UPDATE tbl_homepageslier SET slider_sort=content WHERE slider_id=ids;
 
END$$

CREATE  PROCEDURE `inlineSaveForIsssueandSolution` (IN `inline_id` INT, IN `datalist` INT, IN `content` TEXT)   BEGIN

IF datalist=1 THEN
UPDATE tbl_help_desk_reason SET reason_issue=content WHERE 	reason_id=inline_id;

ELSE 
UPDATE tbl_help_desk_reason SET reason_help=content WHERE 	reason_id=inline_id;
END IF ;
END$$

CREATE  PROCEDURE `inlineUpdateStoreIntend` (IN `intendid` INT, IN `item` INT, IN `quantity` INT, IN `adminid` INT, IN `flag` INT)   BEGIN
	DECLARE success INT DEFAULT 0; 
    
	IF flag = 0 THEN
		UPDATE intend_details SET intdet_quantity = quantity, intdet_updby = adminid  
    	WHERE intdet_id = intendid AND intdet_item = item;
        SET success = 1;
    ELSEIF flag = 1 THEN /* cancel intend */
    	UPDATE intends_tbl SET intend_status = 0 
        WHERE intend_id = intendid AND intend_apprvedby = 0;
        IF (SELECT intend_status FROM intends_tbl WHERE intend_id = intendid) = 0 THEN
        	SET success = 1;
            UPDATE intend_details SET intdet_status = 0 
            WHERE intdet_id = intendid /* AND intdet_item = item 
        		AND intdet_allotted = 0 */ AND intdet_status = 1;
        END IF;
    ELSEIF flag = 2 THEN /* cancel intend item */
    	DELETE FROM intend_details 
        WHERE intdet_id = intendid AND intdet_item = item 
        	AND intdet_allotted = 0 AND intdet_status = 1;
        IF ROW_COUNT() > 0 THEN
        	UPDATE intends_tbl SET intend_items = intend_items - 1 
            WHERE intend_id = intendid;
            SET success = 1;
        END IF;
    END IF;
    SELECT success as response;
END$$

CREATE  PROCEDURE `inlUpdateAdviceStatus` (IN `advid` INT, IN `advice` TEXT, IN `adstatus` INT, IN `flag` INT, IN `admin` INT)   BEGIN
	IF flag = 1 THEN
		UPDATE advices_table SET advice_content = advice, advice_updby = admin 
    	WHERE advice_id = advid;
    ELSE
    	UPDATE advices_table SET advice_status = adstatus, advice_updby = admin 
    	WHERE advice_id = advid;
    END IF;
END$$

CREATE  PROCEDURE `inlUpdateBrandnameStatus` (IN `brandid` INT, IN `brand` VARCHAR(100), IN `bstatus` INT, IN `flag` INT, IN `admin` INT)   BEGIN
	IF flag = 1 THEN
		UPDATE brands_tbl SET brand_name = brand, brand_updby = admin 
    	WHERE brand_id = brandid;
    ELSE
    	UPDATE brands_tbl SET brand_status = bstatus, brand_updby = admin  
    	WHERE brand_id = brandid;
    END IF;
END$$

CREATE  PROCEDURE `inlUpdateDrugclassStatus` (IN `drgclsid` INT, IN `drgclass` VARCHAR(150), IN `dstatus` INT, IN `flag` INT, IN `admin` INT)   BEGIN
	DECLARE isStatus INT DEFAULT 1;
    DECLARE pcount INT DEFAULT 0;
    
    IF flag = 1 THEN
    	UPDATE drug_classifications SET
    	drugclass_name = drgclass, drugclass_updby = admin 
    	WHERE drugclass_id = drgclsid;
    ELSE
        IF dstatus = 0 THEN
            SELECT COUNT(drugclass_id) INTO pcount 
            FROM drug_classifications k 
            WHERE k.drugclass_parent = drgclsid;
            IF pcount = 0 THEN
                SET isStatus = 0;
            END IF;
        END IF;
		UPDATE drug_classifications SET
    	drugclass_status = isStatus, drugclass_updby = admin 
    	WHERE drugclass_id = drgclsid;
    END IF;
END$$

CREATE  PROCEDURE `inlUpdateFaqStatus` (IN `faqid` INT, IN `faq` VARCHAR(255), IN `answer` TEXT, IN `fstatus` INT, IN `flag` INT, IN `admin` INT)   BEGIN
	IF flag = 1 THEN
		UPDATE faq_table SET faq_question = faq, faq_updby = admin 
    	WHERE faq_id = faqid;
    ELSEIF flag = 2 THEN
		UPDATE faq_table SET faq_answer = answer, faq_updby = admin 
    	WHERE faq_id = faqid;
    ELSE
    	UPDATE faq_table SET faq_status = fstatus, faq_updby = admin  
    	WHERE faq_id = faqid;
    END IF;
END$$

CREATE  PROCEDURE `inlUpdateGenericStatus` (IN `genmedid` INT, IN `medicine` VARCHAR(100), IN `mstatus` INT, IN `flag` INT, IN `admin` INT)   BEGIN
	IF flag = 1 THEN
		UPDATE generic_medicines SET genmed_name = medicine, genmed_updby = admin 
    	WHERE genmed_id = genmedid;
    ELSE
    	UPDATE generic_medicines SET genmed_status = mstatus, genmed_updby = admin  
    	WHERE genmed_id = genmedid;
    END IF;
END$$

CREATE  PROCEDURE `inlUpdateIngredStatus` (IN `ingrid` INT, IN `ingred` VARCHAR(100), IN `istatus` INT, IN `flag` INT, IN `admin` INT)   BEGIN
	IF flag = 1 THEN
		UPDATE ingredients_tbl SET ingred_name = ingred, ingred_updby = admin 
    	WHERE brand_id = brandid;
    ELSE
    	UPDATE ingredients_tbl SET ingred_status = istatus, ingred_updby = admin  
    	WHERE brand_id = brandid;
    END IF;
END$$

CREATE  PROCEDURE `inlUpdateListing` (IN `program` INT, IN `listing` INT, IN `keyval` INT, IN `newval` VARCHAR(200), IN `adminid` INT)   BEGIN
	/* listing 1: name, 2:contact person, 3:phone, 4:mobile, 5:email, 6:whatsapp, 7:code */
    if listing = 1 THEN
    	CASE program 
        	WHEN 10 THEN
            	UPDATE generic_medicines SET genmed_name = newval, genmed_updby = adminid  
                WHERE genmed_id = keyval;
            WHEN 11 THEN
            	UPDATE manufacturers_tbl SET manuf_name = newval, manuf_updby = adminid 
                WHERE manuf_id = keyval;
            WHEN 12 THEN
            	UPDATE brands_tbl SET brand_name = newval, brand_updby = adminid 
                WHERE brand_id = keyval;
            WHEN 13 THEN
            	UPDATE stockists_tbl SET stockist_name = newval, stockist_updby = adminid 
                WHERE stockist_id = keyval;
            WHEN 14 THEN
            	UPDATE distributors_tbl SET distri_name = newval, distri_updby = adminid 
                WHERE distri_id = keyval;
            WHEN 15 THEN
            	UPDATE dealers_tbl SET dealer_name = newval, dealer_updby = adminid 
                WHERE dealer_id = keyval;
            WHEN 16 THEN
            	UPDATE ingredients_tbl SET ingred_name = newval, ingred_updby = adminid 
                WHERE ingred_id = keyval;
            WHEN 17 THEN
            	UPDATE drug_classifications SET drugclass_name = newval, drugclass_updby = adminid 
                WHERE drugclass_id = keyval;
            WHEN 18 THEN
            	UPDATE products_tbl SET product_name = newval, product_updby = adminid 
                WHERE product_id = keyval;
            WHEN 20 THEN
            	UPDATE stores_tbl SET store_name = newval, store_updby = adminid 
                WHERE store_id = keyval;
            WHEN 21 THEN
            	UPDATE delivery_areas SET delarea_location = newval, delarea_updby = adminid 
                WHERE delarea_id = keyval;
        END CASE;
    ELSEIF listing = 2 THEN
    	CASE program 
            WHEN 11 THEN
            	UPDATE manufacturers_tbl SET manuf_contact = newval, manuf_updby = adminid 
                WHERE manuf_id = keyval;
            WHEN 13 THEN
            	UPDATE stockists_tbl SET stockist_contact = newval, stockist_updby = adminid 
                WHERE stockist_id = keyval;
            WHEN 14 THEN
            	UPDATE distributors_tbl SET distri_contact = newval, distri_updby = adminid 
                WHERE distri_id = keyval;
            WHEN 15 THEN
            	UPDATE dealers_tbl SET dealer_contact = newval, dealer_updby = adminid 
                WHERE dealer_id = keyval;
            WHEN 20 THEN
            	UPDATE stores_tbl SET store_contact = newval, store_updby = adminid 
                WHERE store_id = keyval;
        END CASE;
    ELSEIF listing = 3 THEN
    	CASE program 
            WHEN 11 THEN
            	UPDATE manufacturers_tbl SET manuf_contactno = newval, manuf_updby = adminid 
                WHERE manuf_id = keyval;
            WHEN 13 THEN
            	UPDATE stockists_tbl SET stockist_contactno = newval, stockist_updby = adminid 
                WHERE stockist_id = keyval;
            WHEN 14 THEN
            	UPDATE distributors_tbl SET distri_contactno = newval, distri_updby = adminid 
                WHERE distri_id = keyval;
            WHEN 15 THEN
            	UPDATE dealers_tbl SET dealer_contactno = newval, dealer_updby = adminid 
                WHERE dealer_id = keyval;
            WHEN 20 THEN
            	UPDATE stores_tbl SET store_contactno = newval, store_updby = adminid 
                WHERE store_id = keyval;
        END CASE;
    ELSEIF listing = 4 THEN
    	CASE program 
            WHEN 11 THEN
            	UPDATE manufacturers_tbl SET manuf_contactcell = newval, manuf_updby = adminid 
                WHERE manuf_id = keyval;
            WHEN 13 THEN
            	UPDATE stockists_tbl SET stockist_contactcell = newval, stockist_updby = adminid 
                WHERE stockist_id = keyval;
            WHEN 14 THEN
            	UPDATE distributors_tbl SET distri_contactcell = newval, distri_updby = adminid 
                WHERE distri_id = keyval;
            WHEN 15 THEN
            	UPDATE dealers_tbl SET dealer_contactcell = newval, dealer_updby = adminid 
                WHERE dealer_id = keyval;
            WHEN 20 THEN
            	UPDATE stores_tbl SET store_contactcell = newval, store_updby = adminid 
                WHERE store_id = keyval;
        END CASE;
    ELSEIF listing = 5 THEN
    	CASE program 
            WHEN 11 THEN
            	UPDATE manufacturers_tbl SET manuf_contactemail = newval, manuf_updby = adminid 
                WHERE manuf_id = keyval;
            WHEN 13 THEN
            	UPDATE stockists_tbl SET stockist_contactemail = newval, stockist_updby = adminid 
                WHERE stockist_id = keyval;
            WHEN 14 THEN
            	UPDATE distributors_tbl SET distri_contactemail = newval, distri_updby = adminid 
                WHERE distri_id = keyval;
            WHEN 15 THEN
            	UPDATE dealers_tbl SET dealer_contactemail = newval, dealer_updby = adminid 
                WHERE dealer_id = keyval;
            WHEN 20 THEN
            	UPDATE stores_tbl SET store_contactemail = newval, store_updby = adminid 
                WHERE store_id = keyval;
    	END CASE;
    ELSEIF listing = 6 THEN
    	CASE program 
            WHEN 11 THEN
            	UPDATE manufacturers_tbl SET manuf_whatsapp = newval, manuf_updby = adminid 
                WHERE manuf_id = keyval;
            WHEN 13 THEN
            	UPDATE stockists_tbl SET stockist_whatsapp = newval, stockist_updby = adminid 
                WHERE stockist_id = keyval;
            WHEN 14 THEN
            	UPDATE distributors_tbl SET distri_whatsapp = newval, distri_updby = adminid 
                WHERE distri_id = keyval;
            WHEN 15 THEN
            	UPDATE dealers_tbl SET dealer_whatsapp = newval, dealer_updby = adminid 
                WHERE dealer_id = keyval;
            WHEN 20 THEN
            	UPDATE stores_tbl SET store_contactwapp = newval, store_updby = adminid 
                WHERE store_id = keyval;
        END CASE;
    ELSEIF listing = 7 THEN
    	UPDATE stores_tbl SET store_code = newval, store_updby = adminid 
        WHERE store_id = keyval;
    END IF;
    
END$$

CREATE  PROCEDURE `inlUpdateMesureUnitName` (IN `prdclid` INT, IN `measure` VARCHAR(50), IN `shrt` VARCHAR(50), IN `adminid` INT)   BEGIN
	IF TRIM(measure) <> '' THEN
		UPDATE measure_units 
    	SET measunit_name = measure, measunit_updby = adminid 
    	WHERE measunit_id = prdclid;
    ELSEIF TRIM(shrt) <> '' THEN
		UPDATE measure_units 
    	SET measunit_shortname= shrt, measunit_updby = adminid 
    	WHERE measunit_id = prdclid;
   	END IF;
END$$

CREATE  PROCEDURE `inlUpdatePackingName` (IN `prdclid` INT, IN `packing` VARCHAR(50), IN `adminid` INT)   BEGIN
	IF trim(packing) <> '' THEN
		UPDATE packing_tbl 
    	SET packing_type = packing, packing_updby = adminid 
    	WHERE packing_id = prdclid;
    END IF;
END$$

CREATE  PROCEDURE `inlUpdateProdcuClassName` (IN `prdclid` INT, IN `prdcls` VARCHAR(100), IN `adminid` INT)   BEGIN
	UPDATE product_classes 
    SET prodclass_name = prdcls, prodclass_updby = adminid 
    WHERE prodclass_id = prdclid;
END$$

CREATE  PROCEDURE `inlUpdateStockPrice` (IN `stkid` INT, IN `msp` DECIMAL(9,2), IN `mrp` DECIMAL(9,2), IN `discount` DECIMAL(5,2))   BEGIN
	DECLARE newprice DECIMAL(9,2) DEFAULT 0;

    IF discount > 0 THEN
    	SELECT (x.strstk_mrp * (100 - discount)/100) INTO newprice  
        FROM storestock_pricing x WHERE x.strstk_id = stkid;
        
    	UPDATE storestock_pricing 
    	SET strstk_msp = newprice, strstk_discount = discount  
        WHERE strstk_id = stkid;
    
	ELSEIF msp > 0 THEN
		UPDATE storestock_pricing 
    	SET strstk_msp = msp, strstk_discount = 0 
        WHERE strstk_id = stkid AND strstk_mrp >= msp;
   
   ELSEIF discount = 0 THEN
    	UPDATE storestock_pricing 
    	SET strstk_msp = strstk_mrp, strstk_discount = 0 
        WHERE strstk_id = stkid;
    END IF;
END$$

CREATE  PROCEDURE `inlUpdateStockPromotion` (IN `stkid` INT, IN `flag` INT, IN `datefrom` DATE, IN `dateto` DATE, IN `statusval` INT)   BEGIN
	IF statusval = 0 THEN
    	SET datefrom = '0000-00-00';
        SET dateto = '0000-00-00';
    END IF;
    
	IF flag = 1 THEN /* deal of day */
    	UPDATE storestock_pricing  
        SET strstk_dealofday = statusval, strstk_dealfrom = datefrom, strstk_dealto = dateto
        WHERE strstk_id = stkid;
    ELSEIF flag = 2 THEN  /* offer */
    	UPDATE storestock_pricing 
        SET strstk_offer = statusval, strstk_offerfrom = datefrom, strstk_offerto = dateto
        WHERE strstk_id = stkid;
    END IF;
END$$

CREATE  PROCEDURE `insertUserCredentials` (IN `phone` VARCHAR(50), IN `pass` VARCHAR(50), IN `flag` INT, IN `email` VARCHAR(200))   BEGIN
declare ids,counts int;
IF flag=2 THEN
IF EXISTS (SELECT 1 FROM customers_tbl c WHERE c.customer_phone = phone  and c.customer_type=0 )THEN
UPDATE customers_tbl c  SET c.customer_type=1 ,c.customer_password=pass, c.customer_email=email WHERE c.customer_phone=phone;
SELECT c.customer_id as ids FROM customers_tbl c WHERE c.customer_phone=phone;
ELSEIF EXISTS (SELECT 1 FROM customers_tbl c WHERE (c.customer_phone = phone or c.customer_email=email ) and c.customer_type=1 )THEN
SELECT "exists";
ELSE
INSERT INTO customers_tbl (customer_phone,customer_password,customer_type,customer_email) 
        VALUES (phone,pass,1,email);
        SET ids = LAST_INSERT_ID();
         SELECT ids;
        END IF;

END IF;
END$$

CREATE  PROCEDURE `insert_products_and_packing` ()   BEGIN
     -- Step 0: Temporary staging table
    DROP TEMPORARY TABLE IF EXISTS tmp_products;
    CREATE TEMPORARY TABLE tmp_products AS
    SELECT 
        a.product_name,
        a.product_manufacturer,
        CASE 
            WHEN COUNT(DISTINCT a2.product_manufacturer) > 1
            THEN CONCAT(a.product_name, ' (', a.product_manufacturer, ')')
            ELSE a.product_name
        END AS final_product_name,
        MAX(a.product_generic) AS product_generic,
        MAX(a.product_highlights) AS product_highlights,
        MAX(a.product_information) AS product_information,
        MAX(a.product_working) AS product_working,
        MAX(a.product_benefits) AS product_benefits,
        MAX(a.product_usage) AS product_usage,
        MAX(a.product_precautions) AS product_precautions,
        MAX(a.product_warnings) AS product_warnings,
        MAX(a.product_sideffects) AS product_sideffects,
        MAX(a.product_interactions) AS product_interactions,
        MAX(a.product_pcontents) AS product_pcontents
    FROM addtest a
    JOIN addtest a2 ON a2.product_name = a.product_name
    GROUP BY a.product_name, a.product_manufacturer;

    -- Step 1: Insert products (unique product+manufacturer combination)
    INSERT INTO products_tbl(
        product_name,
        product_generic,
        product_manufacturer,
        product_highlights,
        product_information,
        product_working,
        product_benefits,
        product_usage,
        product_precautions,
        product_warnings,
        product_sideffects,
        product_interactions,
        product_pcontent
    )
    SELECT 
        t.final_product_name,
        g.genmed_id,
        m.manuf_id,
        t.product_highlights,
        t.product_information,
        t.product_working,
        t.product_benefits,
        t.product_usage,
        t.product_precautions,
        t.product_warnings,
        t.product_sideffects,
        t.product_interactions,
        p.pharma_id
    FROM tmp_products t
    LEFT JOIN manufacturers_tbl m ON m.manuf_name = t.product_manufacturer
    LEFT JOIN pharmacologicalcontent_tbl p ON p.pharma_name = t.product_pcontents
    LEFT JOIN generic_medicines g ON g.genmed_name = t.product_generic
    ON DUPLICATE KEY UPDATE 
        product_name = VALUES(product_name),
        product_manufacturer = VALUES(product_manufacturer);

    -- Step 2: Insert packings
    INSERT INTO product_packing (
        prodpack_product,
        prodpack_package,
        prodpack_quantity,
        prodpack_unit
    )
    SELECT 
        pr.product_id,
        b.packing_id,
        a.qty,
        mu.measunit_id
    FROM addtest a
    JOIN tmp_products t 
        ON a.product_name = t.product_name 
       AND a.product_manufacturer = t.product_manufacturer
    JOIN products_tbl pr 
        ON pr.product_name = t.final_product_name
    LEFT JOIN packing_tbl b 
        ON b.packing_type = a.package
    LEFT JOIN measure_units mu 
        ON mu.measunit_shortname = a.unit;

END$$

CREATE  PROCEDURE `intendApproveStatusFromStores` (IN `intend_ids` INT, IN `statusval` INT)   BEGIN
DECLARE intends,methods,items,qty INT DEFAULT 0;
 SELECT i.intdallocit_intend,i.intdallocit_method,i.intdallocit_item ,i.intdallocit_quantity INTO intends,methods, items,qty FROM intend_allocation_items i WHERE i.intdallocit_id=intend_ids;
 #update intend_allocation_items table
 UPDATE intend_allocation_items SET intdallocit_aprvstatus=statusval,intdallocit_status=2,intdallocit_quantity=(intdallocit_quantity-qty),intdallocit_source=0 WHERE intdallocit_id=intend_ids;
  #update intend_details table
 UPDATE intend_details SET intdet_allotted=(intdet_allotted-qty),intdet_status=1 WHERE 	intdet_id=intends AND intdet_item=items;
  #update intends table
 UPDATE intends_tbl SET intend_apprvedby=0,	intend_status=1 WHERE intend_id =intends;
END$$

CREATE  PROCEDURE `intendFromstoreReports` (IN `dates` DATE)   BEGIN

SELECT i.intend_id,i.intend_number,i.intend_date,s.store_code AS fromcode,s.store_name as fromname,ss.store_code as tocode,ss.store_name as toname,fnGetProductFromPack(d.intdet_item, 0) AS item ,p.product_display, i.intend_notes AS remark,d.intdet_quantity,m.manuf_name,m.manuf_code , pp.prodpack_quantity,u.measunit_name,u.measunit_shortname ,pt.packing_type FROM intends_tbl i
LEFT JOIN intend_details d ON d.intdet_id=i.intend_id
LEFT JOIN stores_tbl s ON s.store_id=i.intend_from
LEFT JOIN stores_tbl ss ON ss.store_id=i.intend_to
LEFT JOIN products_tbl p ON p.product_id=d.intdet_product
LEFT JOIN manufacturers_tbl m ON m.manuf_id=p.product_manufacturer
LEFT JOIN product_packing pp ON pp.prodpack_id=d.intdet_item
LEFT JOIN measure_units u ON u.measunit_id=pp.prodpack_unit
LEFT JOIN packing_tbl pt ON pt.packing_id=pp.prodpack_package
WHERE i.intend_date=dates;
END$$

CREATE  PROCEDURE `listAddonInvoices` ()   BEGIN
	SELECT x.invoice_id, x.invoice_number, fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) AS vendor ,(SELECT COUNT(*) FROM invoice_details y WHERE y.invdet_invoice = x.invoice_id AND y.invdet_delstatus <10) AS invitems, x.invoice_payby, x.invoice_delstatus, x.invoice_status,x.invoice_paystatus,
   (SELECT GROUP_CONCAT( DISTINCT(s.store_name) SEPARATOR ',') FROM invoice_details y LEFT JOIN stores_tbl s ON s.store_id = y.invdet_delivered  WHERE y.invdet_invoice = x.invoice_id and s.store_id = x.invoice_delstore) AS delat
   FROM invoices_tbl x
    LEFT JOIN invoice_details y ON  y.invdet_invoice=x.invoice_id
    LEFT JOIN stock_inwards s ON s.stockin_invref =y.invdet_id
    WHERE s.stockin_short >0
    GROUP BY x.invoice_id;
END$$

CREATE  PROCEDURE `listBrands` ()   BEGIN
	/* List brands */
   /* SELECT x.brand_id, x.brand_name, m.manuf_name, x.brand_logo, x.brand_status, x.brand_publish 
    FROM brands_tbl x
    LEFT JOIN manufacturers_tbl m ON m.manuf_id = x.brand_owner
    ORDER BY x.brand_name;
    */
    SELECT x.brand_id, x.brand_name, GROUP_CONCAT(m.manuf_name) AS manuf_name, x.brand_logo, x.brand_status, x.brand_publish 
    FROM brands_tbl x JOIN brand_manufacturer_tbl t ON t.brnd_id=x.brand_id
    LEFT JOIN manufacturers_tbl m ON m.manuf_id = t.brndmanu_id WHERE x.brand_status=1 GROUP BY t.brnd_id
    ORDER BY x.brand_name;
    /* Manufacturers for add/edit brand */
    SELECT y.manuf_id, y.manuf_name
    FROM manufacturers_tbl y
    WHERE y.manuf_status = 1 
    ORDER BY y.manuf_name;
    
END$$

CREATE  PROCEDURE `listBrandswithLimit` (IN `offsets` INT, IN `limits` INT)   BEGIN
	/* List brands */
    SELECT x.brand_id, x.brand_name, m.manuf_name, x.brand_logo, x.brand_status, x.brand_publish 
    FROM brands_tbl x
    LEFT JOIN manufacturers_tbl m ON m.manuf_id = x.brand_owner WHERE x.brand_status=1 and x.brand_publish =1
    ORDER BY x.brand_name LIMIT offsets,limits;
    
    /* Manufacturers for add/edit brand */
    SELECT y.manuf_id, y.manuf_name
    FROM manufacturers_tbl y
    WHERE y.manuf_status = 1 
    ORDER BY y.manuf_name;
    
    SELECT count(*) AS TotalBrand
    FROM brands_tbl x 
    LEFT JOIN manufacturers_tbl m ON m.manuf_id = x.brand_owner WHERE x.brand_status=1 and x.brand_publish =1;
    
    
END$$

CREATE  PROCEDURE `listCouriers` ()   BEGIN
	SELECT x.courier_id, x.courier_type, x.courier_staffid, x.courier_name, x.courier_mobile, x.courier_contact, x.courier_address, x.courier_status, x.courier_phones, x.courier_whatsapp, x.courier_email 
    FROM couriers_tbl x 
    ORDER BY x.courier_name;
END$$

CREATE  PROCEDURE `listDealers` ()   BEGIN
	SELECT x.dealer_id, x.dealer_name, x.dealer_contact, x.dealer_contactno, x.dealer_contactcell, x.dealer_whatsapp, x.dealer_status 
    FROM dealers_tbl x 
    ORDER BY x.dealer_name;
END$$

CREATE  PROCEDURE `listDistributors` ()   BEGIN
	SELECT x.distri_id, x.distri_name, x.distri_contact, x.distri_contactno, x.distri_contactcell, x.distri_whatsapp, x.distri_status 
    FROM distributors_tbl x
    ORDER BY x.distri_name;
END$$

CREATE  PROCEDURE `listDrugClasses` ()   BEGIN
SELECT
  x.drugclass_id   AS id,
  x.drugclass_name AS dname,
  x.drugclass_parent AS dparent,
  x.drugclass_counter AS cntr,
  x.drugclass_seq  AS seq,
  x.drugclass_status AS dstatus,
  y.drugclass_name AS theparent
FROM drug_classifications x
LEFT JOIN drug_classifications y
  ON y.drugclass_id = x.drugclass_parent
ORDER BY
  -- top-level bucket (e.g., 10)
  CAST(SUBSTRING_INDEX(x.drugclass_seq, '_', 1) AS UNSIGNED),

  -- group by the second-level parent id so a parent (e.g., id=138)
  -- and all its children (seq LIKE '...138') stay together:
  CASE
    WHEN (LENGTH(x.drugclass_seq) - LENGTH(REPLACE(x.drugclass_seq,'',''))) = 0
      THEN x.drugclass_id                                -- top level (e.g., 10)
    WHEN (LENGTH(x.drugclass_seq) - LENGTH(REPLACE(x.drugclass_seq,'',''))) = 1
      THEN x.drugclass_id                                -- second level (e.g., 138)
    ELSE CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(x.drugclass_seq,'',3),'_',-1) AS UNSIGNED)
                                                        -- third level: use parent id (e.g., 138)
  END,

  -- parent row first, then its children
  CASE
    WHEN (LENGTH(x.drugclass_seq) - LENGTH(REPLACE(x.drugclass_seq,'_',''))) = 1 THEN 0
    ELSE 1
  END,

  -- tiebreaker among siblings/children
  x.drugclass_id;
    SELECT k.drugclass_id, k.drugclass_name
    FROM drug_classifications k 
    WHERE k.drugclass_parent = 0 AND k.drugclass_status = 1 
    ORDER BY k.drugclass_name;
END$$

CREATE  PROCEDURE `listDrugClasses_temp` ()   BEGIN
	DECLARE parents, secparents TEXT DEFAULT '';
    
	DROP TEMPORARY TABLE IF EXISTS temp_drugparent;
    DROP TEMPORARY TABLE IF EXISTS temp_second;
    DROP TEMPORARY TABLE IF EXISTS temp_third;
    
	CREATE TEMPORARY TABLE IF NOT EXISTS temp_drugparent AS (SELECT dc.drugclass_id AS id, dc.drugclass_name as dname, 0 as counter, dc.drugclass_id AS seq, dc.drugclass_parent as parent, dc.drugclass_status AS dstatus FROM drug_classifications dc WHERE dc.drugclass_parent = 0 /*AND dc.drugclass_status = 1*/);
    SELECT GROUP_CONCAT(id) INTO parents FROM temp_drugparent;
      
    CREATE TEMPORARY TABLE IF NOT EXISTS temp_second AS (SELECT ds.drugclass_id as id, ds.drugclass_name AS dname, 1 AS counter, concat(ds.drugclass_parent, '_', ds.drugclass_parent) AS seq, ds.drugclass_parent AS parent, ds.drugclass_status AS dstatus FROM drug_classifications ds WHERE find_in_set(ds.drugclass_parent, parents) /*AND ds.drugclass_status = 1*/);
    SELECT GROUP_CONCAT(id) INTO secparents FROM temp_second;
    
    CREATE TEMPORARY TABLE IF NOT EXISTS temp_third AS (SELECT dt.drugclass_id as id, dt.drugclass_name AS dname, 2 AS counter, concat((SELECT parent FROM temp_second WHERE id = dt.drugclass_parent), '_', (SELECT parent FROM temp_second WHERE id = dt.drugclass_parent), '_', dt.drugclass_parent) AS seq, dt.drugclass_parent AS parent, dt.drugclass_status AS dstatus FROM drug_classifications dt WHERE find_in_set(dt.drugclass_parent, secparents) /*AND dt.drugclass_status = 1*/);
    
    #SELECT * FROM temp_drugparent ORDER BY seq;
    #SELECT * FROM temp_second ORDER BY seq;
    #SELECT * FROM temp_third ORDER BY seq;
    SELECT id, dname, 0 as dparent, counter, seq, dstatus, '' AS theparent FROM temp_drugparent 
    UNION SELECT id, dname, ts.parent, counter, seq, dstatus, q.drugclass_name FROM temp_second ts LEFT JOIN drug_classifications q ON q.drugclass_id = ts.parent
    UNION SELECT id, dname, tt.parent, counter, seq, dstatus, z.drugclass_name FROM temp_third  tt LEFT JOIN drug_classifications z ON z.drugclass_id = tt.parent
    ORDER BY seq, dname;
    
    DROP TEMPORARY TABLE IF EXISTS temp_drugparent;
    DROP TEMPORARY TABLE IF EXISTS temp_second;
    DROP TEMPORARY TABLE IF EXISTS temp_third;
END$$

CREATE  PROCEDURE `listGenericMedicines` ()   BEGIN
	SELECT x.genmed_id, x.genmed_name, x.genmed_uses, x.genmed_working, x.genmed_sideffects, x.genmed_remarks, x.genmed_status
    FROM generic_medicines x 
    ORDER BY x.genmed_name;
END$$

CREATE  PROCEDURE `listingOfAdvertisements` (IN `flag` INT)   BEGIN
	IF flag=1 THEN
    SELECT a.advt_id,a.advt_type,a.advt_title,a.advt_owner,a.advt_datefrom,a.advt_dateto,a.advt_products,pp.product_name, a.advt_maincategories, p.prodclass_name,a.advt_subcategories,a.advt_catgory,a.advt_image,a.advt_linkedurl,
    a.advt_publish,a.advt_status FROM advertisements_tbl a
    LEFT JOIN product_classes p ON p.prodclass_id=a.advt_maincategories
    LEFT JOIN products_tbl pp ON pp.product_id=a.advt_products WHERE a.advt_brand = 0
    ORDER BY a.advt_crtdon DESC;
    ELSEIF flag=2 THEN
    SELECT a.advt_id,a.advt_type,a.advt_title,a.advt_brand,b.brand_name, a.advt_datefrom,a.advt_dateto,a.advt_image,a.advt_linkedurl,
    a.advt_publish,a.advt_status FROM advertisements_tbl a
    LEFT JOIN brands_tbl b ON b.brand_id=a.advt_brand
    WHERE a.advt_brand > 0
    ORDER BY a.advt_crtdon DESC;
    END IF ;
    SELECT b.brand_id,b.brand_name,b.brand_status,b.brand_publish  FROM brands_tbl b WHERE b.brand_status > 0 AND b.brand_publish > 0 ;
END$$

CREATE  PROCEDURE `listingOfPromotions` ()   BEGIN
	
    SELECT P.promo_id, P.promo_type ,pp.promotype_name,P.promo_title,P.promo_account,P.promo_discountamt,P.promo_discountpc,P.promo_max,P.promo_count,P.promo_datefrom,P.promo_dateto,P.promo_status,P.promo_publish,P.promo_highlights FROM promotions_tbl P
    LEFT JOIN promotiontypes_tbl pp ON pp.promotype_id=P.promo_type
    ORDER BY P.promo_crtdon DESC;
END$$

CREATE  PROCEDURE `listingQuickorderData` (IN `letter` VARCHAR(200))   BEGIN
    -- Initialize row number variable
    SET @row_number := 0;

    SELECT 
        x.product_id,
        x.product_name,
        x.product_display,
        x.product_featured,
        x.product_popular,
        x.prodpack_id,
        x.prodpack_quantity,
        x.prodpack_maxstock,
        x.prodpack_minstock,
        x.packing_type,
        x.measunit_name,
        x.measunit_shortname,
        x.strstk_mrp,
        x.strstk_msp,
        x.stockin_batch,
        x.stockin_expiry,
        x.stock,
        x.strstk_stack,
        x.product_imageurl,
        x.strstk_discount,
        x.strstk_id
    FROM (
        SELECT 
            (@row_number := @row_number + 1) AS virtual_id,
            p.product_id,
            p.product_name,
            p.product_display,
            p.product_featured,
            p.product_popular,
            r.prodpack_id,
            r.prodpack_quantity,
            r.prodpack_maxstock,
            r.prodpack_minstock,
            t.packing_type,
            m.measunit_name,
            m.measunit_shortname,
            e.strstk_mrp,
            e.strstk_msp,
            s.stockin_batch,
            s.stockin_expiry,
            (e.strstk_stock - e.strstk_reserved) AS stock,
            e.strstk_stack,
            (
                SELECT g.prodgal_url
                FROM product_gallery g
                WHERE g.prodgal_prodpack = r.prodpack_id
                  AND g.prodgal_placedat = 1
                  AND g.prodgal_medium = 1
                  AND g.prodgal_publish = 1
                  AND g.prodgal_status = 1
                ORDER BY g.prodgal_serial ASC
                LIMIT 1
            ) AS product_imageurl,
            e.strstk_discount,
            e.strstk_id
        FROM 
            products_tbl p
            JOIN product_packing r ON r.prodpack_product = p.product_id
            JOIN packing_tbl t ON t.packing_id = r.prodpack_package
            JOIN measure_units m ON m.measunit_id = r.prodpack_unit
            JOIN stock_inwards s ON s.stockin_item = r.prodpack_id
            JOIN storestock_pricing e ON e.strstk_item = r.prodpack_id
        WHERE 
            /*e.strstk_offer = 1
            AND*/
        p.product_status = 1
            AND p.product_online = 1
            AND p.product_publish = 1
            AND p.product_name LIKE CONCAT(letter, '%')
            AND s.stockin_expiry >= CURRENT_DATE()
            AND (e.strstk_stock - e.strstk_reserved) > 0
        ORDER BY 
            s.stockin_expiry ASC,
            e.strstk_discount DESC,
            (e.strstk_stock - e.strstk_reserved) DESC
    ) AS x
    GROUP BY x.product_id;
    
END$$

CREATE  PROCEDURE `listIngredients` ()   BEGIN
	SELECT x.ingred_id, x.ingred_name, p.ingredtype_type, p.ingredtype_status,x.ingred_status
    FROM ingredients_tbl x
    LEFT JOIN ingredient_types p ON p.ingredtype_id = x.ingred_type        
   
    ORDER BY ingred_name  ;
    
    SELECT q.ingredtype_id, q.ingredtype_type 
    FROM ingredient_types q 
    WHERE q.ingredtype_status = 1;
END$$

CREATE  PROCEDURE `listIntendApprovals` (IN `flag` INT, IN `storeid` INT, IN `optionval` INT)   BEGIN
IF storeid > 1 THEN
	IF flag = 1 THEN
		if optionval=0 then
			SELECT x.intdallocit_id, x.intdallocit_intend, x.intdallocit_item, fnGetProductFromPack(x.intdallocit_item, 0) AS package, x.intdallocit_source,  y.intend_from, st.store_name AS tostore, sf.store_name AS fromstore, d.intdet_quantity AS requested, x.intdallocit_quantity AS allotted, fnGetStoreStock(x.intdallocit_source, x.intdallocit_item) as available, x.intdallocit_ordstatus, x.intdallocit_status,x.intdallocit_ordrqty
			FROM intend_allocation_items x
			LEFT JOIN intends_tbl y ON y.intend_id = x.intdallocit_intend
			LEFT JOIN intend_details d ON d.intdet_id = x.intdallocit_intend AND x.intdallocit_item = d.intdet_item
			LEFT JOIN stores_tbl sf ON sf.store_id = x.intdallocit_source
			LEFT JOIN stores_tbl st ON st.store_id = y.intend_from
			WHERE x.intdallocit_ordstatus = 0 AND x.intdallocit_status = 1 AND d.intdet_status = 5  AND y.intend_status = 5 AND x.intdallocit_source=storeid
			AND x.intdallocit_method = 1
			GROUP BY x.intdallocit_id
			ORDER BY x.intdallocit_item;
		elseif optionval=1 then
			SELECT x.intdallocit_id, x.intdallocit_intend, x.intdallocit_item, fnGetProductFromPack(x.intdallocit_item, 0) AS package, x.intdallocit_source,  y.intend_from, st.store_name AS tostore, sf.store_name AS fromstore, d.intdet_quantity AS requested, x.intdallocit_quantity AS allotted, fnGetStoreStock(x.intdallocit_source, x.intdallocit_item) as available, x.intdallocit_ordstatus, x.intdallocit_status,x.intdallocit_ordrqty
			FROM intend_allocation_items x
			LEFT JOIN intends_tbl y ON y.intend_id = x.intdallocit_intend
			LEFT JOIN intend_details d ON d.intdet_id = x.intdallocit_intend AND x.intdallocit_item = d.intdet_item
			LEFT JOIN stores_tbl sf ON sf.store_id = x.intdallocit_source
			LEFT JOIN stores_tbl st ON st.store_id = y.intend_from
			WHERE x.intdallocit_ordstatus = 1 AND x.intdallocit_status = 5 AND d.intdet_status = 5  AND y.intend_status = 5 AND x.intdallocit_source=storeid
			AND x.intdallocit_method = 1
			GROUP BY x.intdallocit_id
			ORDER BY x.intdallocit_item;
		end if;
	ELSE
		SELECT x.intdallocit_id, x.intdallocit_intend, x.intdallocit_item, fnGetProductFromPack(x.intdallocit_item, 0) AS package, x.intdallocit_source, x.intdallocit_type, fnGetVendorName(x.intdallocit_type, x.intdallocit_source) AS supplier, y.intend_from, st.store_name AS tostore, d.intdet_quantity AS requested, x.intdallocit_quantity AS allotted,x.intdallocit_ordrprice, x.intdallocit_vendsup
		FROM intend_allocation_items x
		LEFT JOIN intends_tbl y ON y.intend_id = x.intdallocit_intend
		LEFT JOIN stores_tbl st ON st.store_id = y.intend_from
		LEFT JOIN intend_details d ON d.intdet_id = x.intdallocit_intend AND x.intdallocit_item = d.intdet_item
		WHERE x.intdallocit_method = 2 and x.intdallocit_ordstatus = 0 AND x.intdallocit_status = 1 AND d.intdet_status = 5  AND y.intend_status = 5 AND y.intend_from=storeid GROUP BY x.intdallocit_id
		ORDER BY x.intdallocit_source, x.intdallocit_type, x.intdallocit_item;
	END IF;
 ELSE
  	
    IF flag = 1 THEN
		if optionval=0 then
			SELECT x.intdallocit_id, x.intdallocit_intend, x.intdallocit_item, fnGetProductFromPack(x.intdallocit_item, 0) AS package, x.intdallocit_source,  y.intend_from, st.store_name AS tostore, sf.store_name AS fromstore, d.intdet_quantity AS requested, x.intdallocit_quantity AS allotted, fnGetStoreStock(x.intdallocit_source, x.intdallocit_item) as available, x.intdallocit_ordstatus, x.intdallocit_status,x.intdallocit_ordrqty
			FROM intend_allocation_items x
			LEFT JOIN intends_tbl y ON y.intend_id = x.intdallocit_intend
			LEFT JOIN intend_details d ON d.intdet_id = x.intdallocit_intend AND x.intdallocit_item = d.intdet_item
			LEFT JOIN stores_tbl sf ON sf.store_id = x.intdallocit_source
			LEFT JOIN stores_tbl st ON st.store_id = y.intend_from
			WHERE x.intdallocit_ordstatus = 0 AND x.intdallocit_status = 1 AND d.intdet_status = 5  AND y.intend_status = 5
			AND x.intdallocit_method = 1
			GROUP BY x.intdallocit_id
			ORDER BY x.intdallocit_item;
		elseif optionval=1 then
			SELECT x.intdallocit_id, x.intdallocit_intend, x.intdallocit_item, fnGetProductFromPack(x.intdallocit_item, 0) AS package, x.intdallocit_source,  y.intend_from, st.store_name AS tostore, sf.store_name AS fromstore, d.intdet_quantity AS requested, x.intdallocit_quantity AS allotted, fnGetStoreStock(x.intdallocit_source, x.intdallocit_item) as available, x.intdallocit_ordstatus, x.intdallocit_status,x.intdallocit_ordrqty
			FROM intend_allocation_items x
			LEFT JOIN intends_tbl y ON y.intend_id = x.intdallocit_intend
			LEFT JOIN intend_details d ON d.intdet_id = x.intdallocit_intend AND x.intdallocit_item = d.intdet_item
			LEFT JOIN stores_tbl sf ON sf.store_id = x.intdallocit_source
			LEFT JOIN stores_tbl st ON st.store_id = y.intend_from
			WHERE x.intdallocit_ordstatus = 1 AND x.intdallocit_status = 5 AND d.intdet_status = 5  AND y.intend_status = 5
			AND x.intdallocit_method = 1
			GROUP BY x.intdallocit_id
			ORDER BY x.intdallocit_item;
		end if;
    ELSE
        SELECT x.intdallocit_id, x.intdallocit_intend, x.intdallocit_item, fnGetProductFromPack(x.intdallocit_item, 0) AS package, x.intdallocit_source, x.intdallocit_type, fnGetVendorName(x.intdallocit_type, x.intdallocit_source) AS supplier, y.intend_from, st.store_name AS tostore, d.intdet_quantity AS requested, x.intdallocit_quantity AS allotted,x.intdallocit_ordrprice, x.intdallocit_vendsup
        FROM intend_allocation_items x
        LEFT JOIN intends_tbl y ON y.intend_id = x.intdallocit_intend
        LEFT JOIN stores_tbl st ON st.store_id = y.intend_from
        LEFT JOIN intend_details d ON d.intdet_id = x.intdallocit_intend AND x.intdallocit_item = d.intdet_item
        WHERE x.intdallocit_method = 2 and x.intdallocit_ordstatus = 0 AND x.intdallocit_status = 1 AND d.intdet_status = 5  AND y.intend_status = 5 GROUP BY x.intdallocit_id
        ORDER BY x.intdallocit_source, x.intdallocit_type, x.intdallocit_item;
	END IF;
 END IF;
END$$

CREATE  PROCEDURE `listInvoices` (IN `tempval` INT, IN `startdate` DATE, IN `endDate` DATE)   BEGIN
	IF tempval=1 THEN
   		 SELECT x.invoice_id, x.invoice_number, x.invoice_dated, fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) AS vendor, x.invoice_amount, (SELECT COUNT(*) FROM invoice_details y WHERE y.invdet_invoice = x.invoice_id) AS invitems,  x.invoice_payby, x.invoice_delstatus, x.invoice_status,x.invoice_paystatus,
   /* (SELECT DISTINCT(s.store_name) FROM invoice_details d LEFT JOIN purchase_orders p ON p.purchord_id = d.invdet_porder LEFT JOIN stores_tbl s ON s.store_id = p.purchord_deliverat WHERE d.invdet_invoice = x.invoice_id) AS delat*/
  (SELECT DISTINCT(s.store_name) FROM invoice_details d  LEFT JOIN stores_tbl s ON s.store_id = x.invoice_delstore WHERE d.invdet_invoice = x.invoice_id) AS delat,  (SELECT DISTINCT(s.store_id) FROM invoice_details d LEFT JOIN purchase_orders p ON p.purchord_id = d.invdet_porder LEFT JOIN stores_tbl s ON s.store_id = p.purchord_deliverat WHERE d.invdet_invoice = x.invoice_id) AS delat_id
    FROM invoices_tbl x
    WHERE  x.invoice_dated BETWEEN startdate AND endDate
    ORDER BY x.invoice_dated;
  ELSEIF tempval=2 THEN
  	 SELECT x.invoice_id, x.invoice_number, x.invoice_dated, fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) AS vendor, x.invoice_amount, (SELECT COUNT(*) FROM invoice_details y WHERE y.invdet_invoice = x.invoice_id) AS invitems,  x.invoice_payby, x.invoice_delstatus, x.invoice_status,x.invoice_paystatus,
    /*(SELECT DISTINCT(s.store_name) FROM invoice_details d LEFT JOIN purchase_orders p ON p.purchord_id = d.invdet_porder LEFT JOIN stores_tbl s ON s.store_id = p.purchord_deliverat WHERE d.invdet_invoice = x.invoice_id) AS delat*/
   (SELECT DISTINCT(s.store_name) FROM invoice_details d  LEFT JOIN stores_tbl s ON s.store_id = x.invoice_delstore WHERE d.invdet_invoice = x.invoice_id) AS delat,  (SELECT DISTINCT(s.store_id) FROM invoice_details d LEFT JOIN purchase_orders p ON p.purchord_id = d.invdet_porder LEFT JOIN stores_tbl s ON s.store_id = p.purchord_deliverat WHERE d.invdet_invoice = x.invoice_id) AS delat_id
    FROM invoices_tbl x
    WHERE (x.invoice_dated BETWEEN startdate AND endDate) AND (x.invoice_delstatus<10)
    ORDER BY x.invoice_dated;
    ELSEIF tempval=3 THEN
    	 SELECT x.invoice_id, x.invoice_number, x.invoice_dated, fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) AS vendor, x.invoice_amount, (SELECT COUNT(*) FROM invoice_details y WHERE y.invdet_invoice = x.invoice_id) AS invitems,  x.invoice_payby, x.invoice_delstatus, x.invoice_status,x.invoice_paystatus,
   /* (SELECT DISTINCT(s.store_name) FROM invoice_details d LEFT JOIN purchase_orders p ON p.purchord_id = d.invdet_porder LEFT JOIN stores_tbl s ON s.store_id = p.purchord_deliverat WHERE d.invdet_invoice = x.invoice_id) AS delat*/
   (SELECT DISTINCT(s.store_name) FROM invoice_details d  LEFT JOIN stores_tbl s ON s.store_id = x.invoice_delstore WHERE d.invdet_invoice = x.invoice_id) AS delat,  (SELECT DISTINCT(s.store_id) FROM invoice_details d LEFT JOIN purchase_orders p ON p.purchord_id = d.invdet_porder LEFT JOIN stores_tbl s ON s.store_id = p.purchord_deliverat WHERE d.invdet_invoice = x.invoice_id) AS delat_id
    FROM invoices_tbl x
    WHERE (x.invoice_dated BETWEEN startdate AND endDate) AND (x.invoice_delstatus=10)
    ORDER BY x.invoice_dated;
    ELSE
/*SELECT x.invoice_id, x.invoice_number, x.invoice_dated, fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) AS vendor, x.invoice_amount, (SELECT COUNT(*) FROM invoice_details y WHERE y.invdet_invoice = x.invoice_id) AS invitems,  x.invoice_payby, x.invoice_delstatus, x.invoice_status,x.invoice_paystatus,
    (SELECT DISTINCT(s.store_name) FROM invoice_details d LEFT JOIN purchase_orders p ON p.purchord_id = d.invdet_porder LEFT JOIN stores_tbl s ON s.store_id = p.purchord_deliverat WHERE d.invdet_invoice = x.invoice_id) AS delat,  (SELECT DISTINCT(s.store_id) FROM invoice_details d LEFT JOIN purchase_orders p ON p.purchord_id = d.invdet_porder LEFT JOIN stores_tbl s ON s.store_id = p.purchord_deliverat WHERE d.invdet_invoice = x.invoice_id) AS delat_id
    FROM invoices_tbl x
    WHERE (x.invoice_status BETWEEN 1 AND 10) OR x.invoice_paystatus > 0 OR (x.invoice_delstatus BETWEEN 1 AND 10)
    ORDER BY x.invoice_crtdon;*/
    SELECT x.invoice_id, x.invoice_number, x.invoice_dated, fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) AS vendor, x.invoice_amount, (SELECT COUNT(*) FROM invoice_details y WHERE y.invdet_invoice = x.invoice_id) AS invitems,
  x.invoice_payby, x.invoice_delstatus, x.invoice_status, x.invoice_paystatus,s.store_name AS delat,s.store_id AS delat_id
FROM invoices_tbl x
LEFT JOIN invoice_details d ON d.invdet_invoice = x.invoice_id
/*LEFT JOIN purchase_orders p ON p.purchord_id = d.invdet_porder
LEFT JOIN stores_tbl s ON s.store_id = p.purchord_deliverat */
LEFT JOIN  stores_tbl s ON s.store_id=x.invoice_delstore
WHERE (x.invoice_status BETWEEN 1 AND 10) OR x.invoice_paystatus > 0 OR (x.invoice_delstatus BETWEEN 1 AND 10) GROUP BY x.invoice_id ORDER BY x.invoice_crtdon DESC;
END IF;
END$$

CREATE  PROCEDURE `listLocations` ()   BEGIN
	SELECT delarea_id, delarea_location, delarea_pincode, delarea_status 
    FROM delivery_areas 
    GROUP BY delarea_pincode, delarea_location 
    ORDER BY delarea_pincode, delarea_location;
END$$

CREATE  PROCEDURE `listManufacturers` ()   BEGIN
	SELECT manuf_id, manuf_name, manuf_contact, manuf_contactno, manuf_status
    FROM manufacturers_tbl 
    ORDER BY manuf_name;
END$$

CREATE  PROCEDURE `listOfCustomerOrders` (IN `branchid` INT, IN `frmdate` DATE, IN `todate` DATE)   BEGIN
IF branchid=1 THEN
SELECT o.order_id,o.order_customer,o.order_orderid,DATE( o.order_date) AS dates,o.order_trackid,o.order_remarks,o.order_delivery,d.delivery_to,
CONCAT(d.delivery_house,',' ,d.delivery_street ,',' ,d.delivery_landmark ,',' ,d.delivery_city ,',' ,d.delivery_state, '-', d.delivery_pin ,'. Mob:' ,d.delivery_phone)AS address ,o.order_status,(SELECT COUNT(*) FROM order_details s WHERE s.ordet_order=od.ordet_order) AS totalItem,(SELECT SUM(CASE WHEN s.ordet_status = 0 THEN 1 ELSE 0 END) AS cancel_item FROM order_details s WHERE s.ordet_order=od.ordet_order) AS cancelItem,o.order_prescription,r.return_status FROM orders_tbl o 
JOIN delivery_address d  ON d.delivery_user=o.order_customer and d.delivery_id=o.order_deliverId JOIN order_details od on od.ordet_order=o.order_id LEFT JOIN order_return_status_history r ON r.order_id=o.order_id
WHERE o.order_status>=0 AND o.order_quick=0 AND  DATE(o.order_date) BETWEEN frmdate AND todate GROUP by od.ordet_order ORDER BY o.order_date DESC;
/*SELECT o.order_id,o.order_customer,o.order_orderid,DATE( o.order_date) AS dates,o.order_trackid,o.order_remarks,o.order_delivery,d.delivery_to,
CONCAT(d.delivery_house,',' ,d.delivery_street ,',' ,d.delivery_landmark ,',' ,d.delivery_city ,',' ,d.delivery_state, '-', d.delivery_pin ,'. Mob:' ,d.delivery_phone)AS address ,o.order_status FROM orders_tbl o
JOIN delivery_address d  ON d.delivery_user=o.order_customer and d.delivery_id=o.order_deliverId
WHERE o.order_status>=0 AND o.order_date BETWEEN frmdate AND todate  ORDER BY o.order_date DESC;*/
END IF;
END$$

CREATE  PROCEDURE `listOfCustomerQuickOrders` (IN `branchid` INT, IN `frmdate` DATE, IN `todate` DATE)   BEGIN
IF branchid=1 THEN
SELECT o.order_id,o.order_customer,o.order_orderid,DATE( o.order_date) AS dates,o.order_trackid,o.order_remarks,o.order_delivery,d.delivery_to,o.order_quick_status,
CONCAT(d.delivery_house,',' ,d.delivery_street ,',' ,d.delivery_landmark ,',' ,d.delivery_city ,',' ,d.delivery_state, '-', d.delivery_pin ,'. Mob:' ,d.delivery_phone)AS address ,o.order_status,o.order_prescription FROM orders_tbl o 
JOIN delivery_address d  ON d.delivery_user=o.order_customer and d.delivery_id=o.order_deliverId 
WHERE o.order_status>=0 AND o.order_quick=1 AND  DATE(o.order_date) BETWEEN frmdate AND todate  ORDER BY o.order_date DESC;
/*SELECT o.order_id,o.order_customer,o.order_orderid,DATE( o.order_date) AS dates,o.order_trackid,o.order_remarks,o.order_delivery,d.delivery_to,
CONCAT(d.delivery_house,',' ,d.delivery_street ,',' ,d.delivery_landmark ,',' ,d.delivery_city ,',' ,d.delivery_state, '-', d.delivery_pin ,'. Mob:' ,d.delivery_phone)AS address ,o.order_status FROM orders_tbl o
JOIN delivery_address d  ON d.delivery_user=o.order_customer and d.delivery_id=o.order_deliverId
WHERE o.order_status>=0 AND o.order_date BETWEEN frmdate AND todate  ORDER BY o.order_date DESC;*/
END IF;
END$$

CREATE  PROCEDURE `listOfCustomerReturnOrders` (IN `branchid` INT, IN `frmdate` DATE, IN `todate` DATE)   BEGIN
IF branchid=1 THEN
SELECT o.order_id,o.order_customer,o.order_orderid,DATE( o.order_date) AS dates,o.order_trackid,o.order_remarks,o.order_delivery,d.delivery_to,
CONCAT(d.delivery_house,',' ,d.delivery_street ,',' ,d.delivery_landmark ,',' ,d.delivery_city ,',' ,d.delivery_state, '-', d.delivery_pin ,'. Mob:' ,d.delivery_phone)AS address ,o.order_status,(SELECT COUNT(*) FROM order_details s WHERE s.ordet_order=od.ordet_order) AS totalItem,(SELECT SUM(CASE WHEN s.ordet_status = 0 THEN 1 ELSE 0 END) AS cancel_item FROM order_details s WHERE s.ordet_order=od.ordet_order) AS cancelItem,o.order_prescription,r.return_status,r.status_date,r.approved_date,r.pickup_date,r.refund_date,ss.return_reason FROM orders_tbl o 
JOIN delivery_address d  ON d.delivery_user=o.order_customer and d.delivery_id=o.order_deliverId JOIN order_details od on od.ordet_order=o.order_id LEFT JOIN order_return_status_history r ON r.order_id=o.order_id JOIN returnreason_tbl ss ON ss.return_id=r.return_reason
WHERE o.order_status=2 AND  DATE(o.order_date) BETWEEN frmdate AND todate GROUP by od.ordet_order ORDER BY o.order_date DESC;
/*SELECT o.order_id,o.order_customer,o.order_orderid,DATE( o.order_date) AS dates,o.order_trackid,o.order_remarks,o.order_delivery,d.delivery_to,
CONCAT(d.delivery_house,',' ,d.delivery_street ,',' ,d.delivery_landmark ,',' ,d.delivery_city ,',' ,d.delivery_state, '-', d.delivery_pin ,'. Mob:' ,d.delivery_phone)AS address ,o.order_status FROM orders_tbl o
JOIN delivery_address d  ON d.delivery_user=o.order_customer and d.delivery_id=o.order_deliverId
WHERE o.order_status>=0 AND o.order_date BETWEEN frmdate AND todate  ORDER BY o.order_date DESC;*/
END IF;
END$$

CREATE  PROCEDURE `listOfItemsInPackets` (IN `packid` INT)   BEGIN
SELECT t.transpack_id,t.transpack_refer,t.transpack_deliverby,t.transpack_deliveron,t.transpack_status,t.transpack_notes FROM transfer_packets t WHERE t.transpack_id=packid;
   SELECT c.courier_id,c.courier_name,c.courier_contact,c.courier_mobile FROM couriers_tbl c WHERE c.courier_status=1 ORDER BY c.courier_name ASC;
		SELECT t.transferpack_packet,tr.transpack_packid, t.transferpack_item,t.transferpack_orditem as strstk_id,fnGetProductFromPack(t.transferpack_item, 0) AS packitem ,t.transferpack_status, t.transferpack_qty,t.transferpack_recieved,tr.transpack_deliverby, tr.transpack_from,tr.transpack_to,st.store_name AS sourcestore,sd.store_name AS destnstore ,tr.transpack_notes ,t.store_stack,sg.storage_label FROM transferpack_items t
    LEFT JOIN  transfer_packets tr ON tr.transpack_id=t.transferpack_packet
    LEFT JOIN  stores_tbl st ON st.store_id=tr.transpack_from
     LEFT JOIN  stores_tbl sd ON sd.store_id=tr.transpack_to
     LEFT JOIN storage_tbl sg ON sg.storage_id=t.store_stack
     WHERE t.transferpack_status>=5 AND t.transferpack_packet=packid ;
     #stack listing
     SELECT s.storage_id,s.storage_label,s.storage_type,s.storage_status FROM storage_tbl s WHERE s.storage_status=1;
END$$

CREATE  PROCEDURE `listOfOrders` ()   BEGIN  
	SELECT o.order_id, o.order_orderid ,o.order_date, c.customer_name ,o.order_subtotal,o.order_salestax, o.order_trackid,cc.customer_name AS order_paidby ,CONCAT(a.addr_door,',',a.addr_street,',',a.addr_city,',',a.addr_state,'-',a.addr_pin,', Phone:',a.addr_phone)AS shipping_adr ,o.order_trackid,o.orders_shipped ,o.order_delivery FROM orders_tbl o 
    LEFT JOIN customers_tbl c ON c.customer_id  = o.order_customer
    LEFT JOIN customers_tbl cc on cc.customer_id=o.order_paidby 
    LEFT JOIN address_tbl a ON a.addr_id=o.order_shipping
  
   	ORDER BY o.order_date;

END$$

CREATE  PROCEDURE `listProductGallery` (IN `packid` INT)   BEGIN
	SELECT x.prodpack_product, p.product_name, p.product_display, 
    x.prodpack_package, q.packing_type 
    FROM product_packing x 
    LEFT JOIN products_tbl p ON p.product_id = x.prodpack_product 
    LEFT JOIN packing_tbl q ON q.packing_id = x.prodpack_package 
    WHERE x.prodpack_id = packid;
    
	SELECT prodgal_id, prodgal_prodpack, prodgal_url, prodgal_placedat, prodgal_medium, prodgal_heading, prodgal_title, prodgal_alt, prodgal_serial, prodgal_publish, prodgal_status 
    FROM product_gallery 
    WHERE prodgal_prodpack = packid 
    ORDER BY prodgal_serial;
END$$

CREATE  PROCEDURE `listProducts` (IN `catid` INT, IN `offsets` INT, IN `limits` INT)   BEGIN
	SELECT x.prodclass_id AS id, x.prodclass_name AS pclname, x.prodclass_parent AS parent, x.prodclass_serial AS serial, x.prodclass_status AS pstatus, x.prodclass_counter AS cntr, x.prodclass_seq AS seq
    FROM product_classes x 
    WHERE x.prodclass_seq <> ''
    ORDER BY seq, cntr, serial; 
    
	IF catid = 0 THEN
    	SELECT x.product_id, x.product_name, x.product_display, x.product_maincategory, x.product_subcategory, x.product_category, x.product_brand, b.brand_name, x.product_status, x.product_publish, y.prodclass_name  AS maincat, z.prodclass_name AS subcat, k.prodclass_name AS category, m.manuf_name
        FROM products_tbl x 
        LEFT JOIN product_classes y ON y.prodclass_id = x.product_maincategory 
        LEFT JOIN product_classes z ON z.prodclass_id = x.product_subcategory 
        LEFT JOIN product_classes k ON k.prodclass_id = x.product_category 
        LEFT JOIN brands_tbl b ON b.brand_id = x.product_brand 
        LEFT JOIN manufacturers_tbl m on m.manuf_id=x.product_manufacturer
      /*  GROUP BY x.product_maincategory, x.product_subcategory, x.product_category 
     */   ORDER BY x.product_name LIMIT offsets ,limits;
     
     SELECT COUNT(*) as totalRecords
        FROM products_tbl x 
        LEFT JOIN product_classes y ON y.prodclass_id = x.product_maincategory 
        LEFT JOIN product_classes z ON z.prodclass_id = x.product_subcategory 
        LEFT JOIN product_classes k ON k.prodclass_id = x.product_category 
        LEFT JOIN brands_tbl b ON b.brand_id = x.product_brand 
        LEFT JOIN manufacturers_tbl m on m.manuf_id=x.product_manufacturer
      /*  GROUP BY x.product_maincategory, x.product_subcategory, x.product_category 
     */   ORDER BY x.product_name;
     
    ELSE
    	SELECT x.product_id, x.product_name, x.product_display, x.product_maincategory, x.product_subcategory, x.product_category, x.product_brand, b.brand_name, x.product_status, x.product_publish, y.prodclass_name  AS maincat, z.prodclass_name AS subcat, k.prodclass_name AS category,m.manuf_name
        FROM products_tbl x 
        LEFT JOIN product_classes y ON y.prodclass_id = x.product_maincategory 
        LEFT JOIN product_classes z ON z.prodclass_id = x.product_subcategory 
        LEFT JOIN product_classes k ON k.prodclass_id = x.product_category 
        LEFT JOIN brands_tbl b ON b.brand_id = x.product_brand
        LEFT JOIN manufacturers_tbl m on m.manuf_id=x.product_manufacturer
        WHERE x.product_maincategory = catid OR x.product_subcategory = catid OR x.product_category = catid 
        /*GROUP BY x.product_maincategory, x.product_subcategory, x.product_category */
        ORDER BY x.product_name LIMIT offsets ,limits;
        
        SELECT COUNT(*) as totalRecords
        FROM products_tbl x 
        LEFT JOIN product_classes y ON y.prodclass_id = x.product_maincategory 
        LEFT JOIN product_classes z ON z.prodclass_id = x.product_subcategory 
        LEFT JOIN product_classes k ON k.prodclass_id = x.product_category 
        LEFT JOIN brands_tbl b ON b.brand_id = x.product_brand 
        LEFT JOIN manufacturers_tbl m on m.manuf_id=x.product_manufacturer
        
      /*  GROUP BY x.product_maincategory, x.product_subcategory, x.product_category 
     */   ORDER BY x.product_name;
    END IF;
END$$

CREATE  PROCEDURE `listProductsForProductsEntry` (IN `ids` INT, IN `dates` DATE)   BEGIN
	/*SELECT x.prodclass_id AS id, x.prodclass_name AS pclname, x.prodclass_parent AS parent, x.prodclass_serial AS serial, x.prodclass_status AS pstatus, x.prodclass_counter AS cntr, x.prodclass_seq AS seq
    FROM product_classes x 
    WHERE x.prodclass_seq <> ''
    ORDER BY seq, cntr, serial; 
    */
 IF ids=222 OR ids=223 THEN
    	SELECT x.product_id, x.product_name, x.product_display, x.product_maincategory, x.product_subcategory, x.product_category, x.product_brand, b.brand_name, x.product_status, x.product_publish, y.prodclass_name  AS maincat, z.prodclass_name AS subcat, k.prodclass_name AS category ,x.assigned_for,x.product_entry_status,m.manuf_name
        FROM products_entry_tbl x 
        LEFT JOIN product_classes y ON y.prodclass_id = x.product_maincategory 
        LEFT JOIN product_classes z ON z.prodclass_id = x.product_subcategory 
        LEFT JOIN product_classes k ON k.prodclass_id = x.product_category 
        LEFT JOIN manufacturers_tbl m on m.manuf_id=x.product_manufacturer
        LEFT JOIN brands_tbl b ON b.brand_id = x.product_brand WHERE x.assigned_for=ids AND x.assigned_date=dates ORDER BY x.product_name;
 
 ELSE
 SELECT x.product_id, x.product_name, x.product_display, x.product_maincategory, x.product_subcategory, x.product_category, x.product_brand, b.brand_name, x.product_status, x.product_publish, y.prodclass_name  AS maincat, z.prodclass_name AS subcat, k.prodclass_name AS category ,x.assigned_for,x.product_entry_status,m.manuf_name
        FROM products_entry_tbl x 
        LEFT JOIN product_classes y ON y.prodclass_id = x.product_maincategory 
        LEFT JOIN product_classes z ON z.prodclass_id = x.product_subcategory 
        LEFT JOIN product_classes k ON k.prodclass_id = x.product_category 
        LEFT JOIN manufacturers_tbl m on m.manuf_id=x.product_manufacturer
        LEFT JOIN brands_tbl b ON b.brand_id = x.product_brand WHERE x.assigned_date=dates  ORDER BY x.product_name;
        
        END IF;
        
END$$

CREATE  PROCEDURE `listPurchaseOrders` (IN `temVal` INT, IN `fromDate` DATE, IN `toDate` DATE)  COMMENT 'purchase orders where supply is pending' BEGIN
SELECT store_id, store_type, store_name, store_license
    FROM stores_tbl WHERE store_status = 1
    UNION SELECT 0, 0, 0, 0
    ORDER BY store_type, store_name;
    IF temVal=1 THEN
	SELECT x.purchord_id, x.purchord_ref, x.purchord_date,  fnGetVendorName(x.purchord_vendtype, x.purchord_vendor) AS vendor, x.purchord_amount, (SELECT COUNT(*) FROM purchase_details y WHERE y.podetail_order = x.purchord_id) AS orditems, x.purchord_supply, x.purchord_preprdby, x.purchord_aprvdby, x.purchord_issuedby, x.purchord_status, x.purchord_deliverby, x.purchord_deliverat, s.store_name
    FROM purchase_orders x
    LEFT JOIN stores_tbl s ON s.store_id = x.purchord_deliverat
    WHERE x.purchord_date BETWEEN fromDate AND toDate
    /*ORDER BY x.purchord_crtdon;*/
    ORDER BY x.purchord_date DESC;
    ELSEIF temVal=2 THEN
    	SELECT x.purchord_id, x.purchord_ref, x.purchord_date,  fnGetVendorName(x.purchord_vendtype, x.purchord_vendor) AS vendor, x.purchord_amount, (SELECT COUNT(*) FROM purchase_details y WHERE y.podetail_order = x.purchord_id) AS orditems, x.purchord_supply, x.purchord_preprdby, x.purchord_aprvdby, x.purchord_issuedby, x.purchord_status, x.purchord_deliverby, x.purchord_deliverat, s.store_name
    FROM purchase_orders x
    LEFT JOIN stores_tbl s ON s.store_id = x.purchord_deliverat
    WHERE(x.purchord_date BETWEEN fromDate AND toDate) AND x.purchord_status=1
    /*ORDER BY x.purchord_crtdon;*/
    ORDER BY x.purchord_date DESC;
    ELSEIF temVal=3 THEN
    	SELECT x.purchord_id, x.purchord_ref, x.purchord_date,  fnGetVendorName(x.purchord_vendtype, x.purchord_vendor) AS vendor, x.purchord_amount, (SELECT COUNT(*) FROM purchase_details y WHERE y.podetail_order = x.purchord_id) AS orditems, x.purchord_supply, x.purchord_preprdby, x.purchord_aprvdby, x.purchord_issuedby, x.purchord_status, x.purchord_deliverby, x.purchord_deliverat, s.store_name
    FROM purchase_orders x
    LEFT JOIN stores_tbl s ON s.store_id = x.purchord_deliverat
    WHERE(x.purchord_date BETWEEN fromDate AND toDate) AND ( x.purchord_status = 5 OR  x.purchord_status = 10)
    /*ORDER BY x.purchord_crtdon;*/
    ORDER BY x.purchord_date DESC;
     ELSEIF temVal=4 THEN
    	SELECT x.purchord_id, x.purchord_ref, x.purchord_date,  fnGetVendorName(x.purchord_vendtype, x.purchord_vendor) AS vendor, x.purchord_amount, (SELECT COUNT(*) FROM purchase_details y WHERE y.podetail_order = x.purchord_id) AS orditems, x.purchord_supply, x.purchord_preprdby, x.purchord_aprvdby, x.purchord_issuedby, x.purchord_status, x.purchord_deliverby, x.purchord_deliverat, s.store_name
    FROM purchase_orders x
    LEFT JOIN stores_tbl s ON s.store_id = x.purchord_deliverat
    WHERE(x.purchord_date BETWEEN fromDate AND toDate) AND x.purchord_status=15
    /*ORDER BY x.purchord_crtdon;*/
    ORDER BY x.purchord_date DESC;
   ELSE
   	SELECT x.purchord_id, x.purchord_ref, x.purchord_date,  fnGetVendorName(x.purchord_vendtype, x.purchord_vendor) AS vendor, x.purchord_amount, (SELECT COUNT(*) FROM purchase_details y WHERE y.podetail_order = x.purchord_id) AS orditems, x.purchord_supply, x.purchord_preprdby, x.purchord_aprvdby, x.purchord_issuedby, x.purchord_status, x.purchord_deliverby, x.purchord_deliverat, s.store_name
    FROM purchase_orders x
    LEFT JOIN stores_tbl s ON s.store_id = x.purchord_deliverat
    WHERE x.purchord_supply < 10 AND x.purchord_status > 0
    ORDER BY x.purchord_crtdon DESC;
 
 END IF;

END$$

CREATE  PROCEDURE `listreturnItemsDeliveries` (IN `courierid` INT)   BEGIN
DECLARE cur_id INT DEFAULT 0;
    IF courierid>0 THEN
     SELECT courier_id INTO cur_id FROM couriers_tbl WHERE courier_staffid=courierid;
SELECT GROUP_CONCAT(p.return_id) AS return_ids,pp.returnbill_id,pp.returnbill_number,pp.returnbill_dated,pp.returnbill_vendertype,pp.returnbill_vendor,pp.returnbill_amt,pp.returnbill_subamt,pp.returnbill_difnce,s.store_name,s.store_id 
    ,pp.returnbill_status,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,c.courier_name, p.courier_cltdon,p.return_delon ,p.returncltn_status, SUM(CASE WHEN p.returncltn_status = 1 THEN 1 ELSE 0 END) AS returncltn_status_1_count,
            SUM(CASE WHEN p.returncltn_status = 0 THEN 1 ELSE 0 END) AS returncltn_status_0_count,SUM(CASE WHEN p.returncltn_status = 5 THEN 1 ELSE 0 END) AS returncltn_status_5_count,p.return_delon ,COUNT(p.return_item)AS itemcount  FROM purchasereturn_details p
    LEFT JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
    LEFT JOIN stores_tbl s ON s.store_id=p.return_store
    LEFT JOIN couriers_tbl c ON c.courier_id=p.return_courier
    WHERE pp.returnbill_status>0 AND p.return_courier=cur_id GROUP BY p.return_billnum,p.return_store  ORDER BY p.courier_cltdon DESC ;
    
    ELSE
    SELECT GROUP_CONCAT(p.return_id) AS return_ids,pp.returnbill_id,pp.returnbill_number,pp.returnbill_dated,pp.returnbill_vendertype,pp.returnbill_vendor,pp.returnbill_amt,pp.returnbill_subamt,pp.returnbill_difnce,s.store_name,s.store_id 
    ,pp.returnbill_status,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,c.courier_name, p.courier_cltdon,p.return_delon,p.returncltn_status, SUM(CASE WHEN p.returncltn_status = 1 THEN 1 ELSE 0 END) AS returncltn_status_1_count,
            SUM(CASE WHEN p.returncltn_status = 0 THEN 1 ELSE 0 END) AS returncltn_status_0_count ,SUM(CASE WHEN p.returncltn_status = 5 THEN 1 ELSE 0 END) AS returncltn_status_5_count, COUNT(p.return_item)AS itemcount FROM purchasereturn_details p
    LEFT JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
    LEFT JOIN stores_tbl s ON s.store_id=p.return_store
    LEFT JOIN couriers_tbl c ON c.courier_id=p.return_courier
    WHERE p.return_courier>0  GROUP BY p.return_billnum,p.return_store ORDER BY p.courier_cltdon DESC ;
    
    END IF;
END$$

CREATE  PROCEDURE `listStockInwardInvoices` (IN `storeid` INT)   BEGIN
	IF storeid > 1 THEN
    	SELECT x.invoice_id, x.invoice_number, x.invoice_dated, fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) AS vendor, (SELECT COUNT(*) FROM invoice_details y WHERE y.invdet_invoice = x.invoice_id) AS invitems, x.invoice_delstatus, x.invoice_status, x.invoice_delstore,
    	(SELECT GROUP_CONCAT( DISTINCT(s.store_name) SEPARATOR ',') FROM invoice_details y LEFT JOIN stores_tbl s ON s.store_id = y.invdet_delivered  WHERE y.invdet_invoice = x.invoice_id and s.store_id = x.invoice_delstore) AS delvat
    FROM invoices_tbl x
    WHERE (x.invoice_status IN(1,5) OR x.invoice_delstatus < 10 )AND x.invoice_status!=0 AND x.invoice_delstore=storeid
    ORDER BY x.invoice_crtdon DESC;
    ELSE
    	SELECT x.invoice_id, x.invoice_number, x.invoice_dated, fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) AS vendor, (SELECT COUNT(*) FROM invoice_details y WHERE y.invdet_invoice = x.invoice_id) AS invitems, x.invoice_delstatus, x.invoice_status,
    	/*(SELECT GROUP_CONCAT( DISTINCT(s.store_name) SEPARATOR ',') FROM invoice_details y LEFT JOIN purchase_orders p ON p.purchord_id = y.invdet_porder LEFT JOIN stores_tbl s ON s.store_id = p.purchord_deliverat WHERE y.invdet_invoice = x.invoice_id) AS delvat */
        (SELECT GROUP_CONCAT( DISTINCT(s.store_name) SEPARATOR ',') FROM invoice_details y LEFT JOIN stores_tbl s ON s.store_id = y.invdet_delivered  WHERE y.invdet_invoice = x.invoice_id and s.store_id = x.invoice_delstore) AS delvat
    FROM invoices_tbl x
    WHERE x.invoice_status IN(1,5) OR x.invoice_delstatus < 10 and x.invoice_status!=0
    ORDER BY x.invoice_crtdon DESC;
   END IF;
END$$

CREATE  PROCEDURE `listStockists` ()   BEGIN
	SELECT stockist_id, stockist_name, stockist_contact, stockist_contactno, stockist_contactcell, stockist_whatsapp, stockist_status
    FROM stockists_tbl  
    ORDER BY stockist_name;
END$$

CREATE  PROCEDURE `listStockTransferOrders` (IN `storeid` INT)   BEGIN
	IF storeid > 1 THEN
   		SELECT x.stocktrans_id, x.stocktrans_order, x.stocktrans_date,
        x.stocktrans_strfrom, s.store_name AS storefrom, x.stocktrans_strto, t.store_name AS storeto,
        x.stocktrans_items, x.stocktrans_packing, x.stocktrans_delivery, x.stocktrans_status,
        (SELECT COUNT(*) FROM transfer_packets p WHERE p.transpack_refer = x.stocktrans_id) AS packets,(SELECT COUNT(*) FROM stocktransfer_details WHERE stockorder_refer=x.stocktrans_id GROUP BY stockorder_refer)as itemscount
    	FROM stock_transfers x
        LEFT JOIN stores_tbl s ON s.store_id = x.stocktrans_strfrom
        LEFT JOIN stores_tbl t ON t.store_id = x.stocktrans_strto
    	WHERE x.stocktrans_status = 1 AND x.stocktrans_strfrom=storeid order by x.stocktrans_crtdon DESC;
    ELSE
        SELECT x.stocktrans_id, x.stocktrans_order, x.stocktrans_date,
        x.stocktrans_strfrom, s.store_name AS storefrom, x.stocktrans_strto, t.store_name AS storeto,
        x.stocktrans_items, x.stocktrans_packing, x.stocktrans_delivery, x.stocktrans_status,
        (SELECT COUNT(*) FROM transfer_packets p WHERE p.transpack_refer = x.stocktrans_id) AS packets,(SELECT COUNT(*) FROM stocktransfer_details WHERE stockorder_refer=x.stocktrans_id GROUP BY stockorder_refer)as itemscount
    	FROM stock_transfers x
        LEFT JOIN stores_tbl s ON s.store_id = x.stocktrans_strfrom
        LEFT JOIN stores_tbl t ON t.store_id = x.stocktrans_strto
    	WHERE x.stocktrans_status = 1 order by x.stocktrans_crtdon DESC;
    END IF;
END$$

CREATE  PROCEDURE `listStorage` ()   BEGIN
SELECT s.storage_id, s.storage_label, s.storage_type, t.strgtype_type, s.storage_remarks, s.storage_temperature, s.storage_humidity, s.storage_security, s.storage_status, s.storage_volume, s.storage_size, s.storage_load FROM storage_tbl s LEFT JOIN storage_types t ON t.strgtype_id = s.storage_type;
END$$

CREATE  PROCEDURE `listStoreIntends` (IN `storeid` INT)   BEGIN
	SELECT s.store_id, s.store_code, s.store_name
    FROM stores_tbl s WHERE s.store_status = 1 ORDER BY s.store_name;
    IF storeid > 1 THEN
    	SELECT x.intend_id, x.intend_number, x.intend_date, x.intend_from, sf.store_name AS storefrom, x.intend_to, st.store_name AS storeto, x.intend_items, x.intend_delstatus, x.intend_status,x.intend_preprdby,x.intend_updby,x.intend_crtdon,x.intend_updon,(select u.user_staffname from users_tbl u WHERE u.user_id = x.intend_preprdby) as prepdbyname ,(select u.user_staffname from users_tbl u WHERE u.user_id = x.intend_updby) as updtdbyname,(select u.user_staffname from users_tbl u WHERE u.user_id = x.intend_apprvedby) as aprvdbyname
    	FROM intends_tbl x
        LEFT JOIN stores_tbl sf ON sf.store_id = x.intend_from
        LEFT JOIN stores_tbl st ON st.store_id = x.intend_to
    	WHERE  x.intend_from = storeid AND x.intend_status IN(1,5) ORDER BY x.intend_crtdon DESC;
    ELSE
		SELECT x.intend_id, x.intend_number, x.intend_date, x.intend_from, sf.store_name AS storefrom, x.intend_to, st.store_name AS storeto, x.intend_items, x.intend_delstatus, x.intend_status,x.intend_preprdby,x.intend_updby,x.intend_crtdon,x.intend_updon,(select u.user_staffname from users_tbl u WHERE u.user_id = x.intend_preprdby) as prepdbyname,(select u.user_staffname from users_tbl u WHERE u.user_id = x.intend_updby) as updtdbyname,(select u.user_staffname from users_tbl u WHERE u.user_id = x.intend_apprvedby) as aprvdbyname
    	FROM intends_tbl x
        LEFT JOIN stores_tbl sf ON sf.store_id = x.intend_from
        LEFT JOIN stores_tbl st ON st.store_id = x.intend_to
    	WHERE x.intend_status IN(1,5) ORDER BY x.intend_crtdon DESC;
    END IF;
END$$

CREATE  PROCEDURE `listStoreIntendsForApprovals` ()   BEGIN
	SELECT x.intend_id, x.intend_number, x.intend_date, x.intend_from, frst.store_name AS fromstore, x.intend_to, tost.store_name AS tostore, x.intend_items, x.intend_apprvedby, x.intend_procdby, x.intend_status 
    FROM intends_tbl x 
    LEFT JOIN stores_tbl frst ON frst.store_id = x.intend_from 
    LEFT JOIN stores_tbl tost ON tost.store_id = x.intend_to 
    WHERE x.intend_status = 1 
    ORDER BY x.intend_date;
END$$

CREATE  PROCEDURE `listStoreItemreceived` (IN `storeid` INT, IN `opnval` INT, IN `fromdate` VARCHAR(225), IN `todate` VARCHAR(225))   BEGIN
	SELECT s.store_id,s.store_code,s.store_name  FROM stores_tbl s WHERE s.store_status=1 ORDER BY s.store_name;
    
    IF storeid > 1 THEN
      IF opnval=1 THEN
    	SELECT t.transpack_id,t.transpack_packid,t.transpack_from,st.store_name AS sourcestore,sf.store_name AS receivedstore ,t.transpack_to ,t.transpack_status,t.transpack_deliverby,t.transpack_receiveby,t.transpack_receiveon,c.courier_name ,u.user_staffname FROM transfer_packets t 
            LEFT JOIN  stores_tbl st ON st.store_id=t.transpack_from
            LEFT JOIN stores_tbl sf ON sf.store_id=t.transpack_to
            LEFT JOIN couriers_tbl c ON c.courier_id=t.transpack_deliverby
            LEFT JOIN users_tbl u ON u.user_id=t.transpack_receiveby
            WHERE t.transpack_status =10 AND t.transpack_to=storeid ORDER BY t.transpack_receiveon DESC;
     ELSE
    	SELECT t.transpack_id,t.transpack_packid,t.transpack_from,st.store_name AS sourcestore,sf.store_name AS receivedstore , t.transpack_to , t.transpack_status,t.transpack_deliverby,t.transpack_receiveby,t.transpack_receiveon,c.courier_name ,u.user_staffname FROM transfer_packets t 
        LEFT JOIN  stores_tbl st ON st.store_id=t.transpack_from
        LEFT JOIN couriers_tbl c ON c.courier_id=t.transpack_deliverby
        LEFT JOIN stores_tbl sf ON sf.store_id=t.transpack_to
        LEFT JOIN users_tbl u ON u.user_id=t.transpack_receiveby
        WHERE t.transpack_to=storeid AND t.transpack_status >1 AND t.transpack_status <10;
     END IF;  
   ELSE
   
    IF opnval=1 THEN
    	SELECT t.transpack_id,t.transpack_packid,t.transpack_from,st.store_name AS sourcestore,sf.store_name AS receivedstore ,t.transpack_to ,t.transpack_status,t.transpack_deliverby,t.transpack_receiveby,t.transpack_receiveon,c.courier_name ,u.user_staffname FROM transfer_packets t 
            LEFT JOIN  stores_tbl st ON st.store_id=t.transpack_from
            LEFT JOIN stores_tbl sf ON sf.store_id=t.transpack_to
            LEFT JOIN couriers_tbl c ON c.courier_id=t.transpack_deliverby
           LEFT JOIN users_tbl u ON u.user_id=t.transpack_receiveby
            WHERE t.transpack_status =10 ORDER BY t.transpack_receiveon DESC;
     ELSE       
    	 SELECT t.transpack_id,t.transpack_packid,t.transpack_from,st.store_name AS sourcestore,sf.store_name AS receivedstore ,t.transpack_to ,t.transpack_status,t.transpack_deliverby,t.transpack_receiveby,t.transpack_receiveon,c.courier_name ,u.user_staffname FROM transfer_packets t 
            LEFT JOIN  stores_tbl st ON st.store_id=t.transpack_from
            LEFT JOIN stores_tbl sf ON sf.store_id=t.transpack_to
            LEFT JOIN couriers_tbl c ON c.courier_id=t.transpack_deliverby
            LEFT JOIN users_tbl u ON u.user_id=t.transpack_receiveby
            WHERE t.transpack_status >1 AND t.transpack_status <10;
	END IF;
    END IF;
END$$

CREATE  PROCEDURE `listStores` ()   BEGIN
	SELECT x.store_id, x.store_type, x.store_location, x.store_code, s.storetype_name, x.store_name, x.store_contact, x.store_contactno, x.store_contactcell, x.store_contactwapp, x.store_status  
    FROM stores_tbl x 
    LEFT JOIN store_types s ON s.storetype_id = x.store_type 
    /*GROUP BY x.store_type*/
    ORDER BY x.store_crtdon ASC;
END$$

CREATE  PROCEDURE `listVendorSupplies` (IN `stype` INT, IN `supplier` INT)   BEGIN
	IF stype = 1 THEN   /* Stockists */ 
     
    	SELECT x.stockistprod_product AS pid, p.product_name, p.product_display, 'Stockist' AS suppliertype 
        FROM stockist_products x 
        LEFT JOIN products_tbl p ON p.product_id = x.stockistprod_product 
        WHERE x.stockistprod_stockist = supplier AND x.stockistprod_status = 1 
        ORDER BY p.product_display;
    ELSEIF stype = 2 THEN  /* Distributors */
   
    	SELECT d.distriprod_product AS pid, p.product_name, p.product_display, 'Distributor' AS suppliertype 
        FROM distributor_products d 
        LEFT JOIN products_tbl p ON p.product_id = d.distriprod_product 
        WHERE d.distriprod_distributor = supplier AND d.distriprod_status = 1
        ORDER BY p.product_display;
    ELSE
    
    	SELECT q.dealerprod_product AS pid, p.product_name, p.product_display, 'Dealer' AS suppliertype 
        FROM dealer_products q 
        LEFT JOIN products_tbl p ON p.product_id = q.dealerprod_product 
        WHERE q.dealerprod_dealer = supplier AND q.dealerprod_status = 1
        ORDER BY p.product_display;
    END IF;
    
    SELECT v.vendsup_id, v.vendsup_product, p.product_name, p.product_display, 
    v.vendsup_packing, u.packing_type, v.vendsup_price, v.vendsup_minqty, v.vendsup_maxqty, v.vendsup_eoq, v.vendsup_deliver, 
    v.vendsup_notes, v.vendsup_status, fnGetProductFromPack(v.vendsup_packing, 0) AS package, CONCAT(u.packing_type, ' ', k.prodpack_quantity, ' ', m.measunit_shortname) AS boxunit,k.prodpack_quantity 
    FROM vendor_supplies v
    LEFT JOIN products_tbl p ON p.product_id = v.vendsup_product 
    LEFT JOIN product_packing k ON k.prodpack_id = v.vendsup_packing
    LEFT JOIN packing_tbl u ON u.packing_id = k.prodpack_package  
    LEFT JOIN measure_units m ON m.measunit_id = k.prodpack_unit 
    WHERE v.vendsup_vendor = supplier AND v.vendsup_type = stype AND v.vendsup_status = 1 
    ORDER BY product_display;
END$$

CREATE  PROCEDURE `loadtoken` (IN `user_id` INT)   BEGIN
DECLARE counts int;
SELECT COUNT(*) into counts FROM customers_tbl c WHERE c.customer_id=user_id;
IF(counts=1)THEN
SELECT c.customer_type  as type,c.customer_phone as cusphone FROM customers_tbl c WHERE c.customer_id=user_id;
ELSE 
SELECT "" as type;
END IF;
END$$

CREATE  PROCEDURE `nonMovingItemsByStores` (IN `storeid` INT, IN `fdate` DATE, IN `todate` DATE)   BEGIN

SELECT s.store_id,s.store_code,s.store_name FROM stores_tbl s WHERE s.store_status=1;

 SELECT  s.storestock_item,MAX(bl.bill_date)AS last_date,fnGetProductFromPack(s.storestock_item, 0) AS item,i.invdet_item,i.invdet_ptr,it.invoice_number,it.invoice_dated,(s.storestock_available-s.storestock_reserved)AS stock,s.storestock_store,st.store_name,st.store_code,pt.product_name,m.manuf_code,m.manuf_name FROM storestock_master s JOIN bill_items bb on bb.billit_item=s.storestock_item
 JOIN bills_table bl on bl.bill_id=bb.billit_id JOIN stores_tbl st ON st.store_id=s.storestock_store
 JOIN product_packing p ON p.prodpack_id=s.storestock_item
 JOIN products_tbl pt ON pt.product_id=p.prodpack_product
 JOIN manufacturers_tbl m ON m.manuf_id=pt.product_manufacturer
 JOIN invoice_details i ON i.invdet_batch=bb.billit_batch
 JOIN invoices_tbl it ON it.invoice_id=i.invdet_invoice
 WHERE s.storestock_item NOT IN (SELECT bs.billit_item FROM bill_items bs JOIN bills_table b ON b.bill_id=bs.billit_id JOIN storestock_master ss ON ss.storestock_store=b.bill_store
 WHERE date(b.bill_date) BETWEEN fdate and todate ) AND date(bl.bill_date)<=todate and  bl.bill_store=s.storestock_store GROUP by s.storestock_item ORDER BY bl.bill_date DESC;
 

END$$

CREATE  PROCEDURE `purchaseBillReportBystores` ()   BEGIN
/*SELECT i.invoice_id,i.invoice_dated,CONCAT(DATE_FORMAT(i.invoice_crtdon, '%H.%i'), ' to ', DATE_FORMAT(DATE_ADD(i.invoice_crtdon, INTERVAL 1 HOUR), '%H.%i')) AS hour_interval,
     i.invoice_number,i.invoice_delstore,s.store_name,i.invoice_crtdon ,date(i.invoice_crtdon)as dates ,time(i.invoice_crtdon)as times FROM invoices_tbl i
LEFT JOIN stores_tbl s ON s.store_id=i.invoice_delstore
WHERE i.invoice_status>0 ORDER BY hour_interval,s.store_name ;*/
SELECT 
    DATE_FORMAT(i.invoice_crtdon, '%d-%m') AS date,
    CONCAT(DATE_FORMAT(i.invoice_crtdon, '%H'), '.00 to ', DATE_FORMAT(DATE_ADD(i.invoice_crtdon, INTERVAL 1 HOUR), '%H'), '.00') AS hour_interval,
    COUNT(i.invoice_id) AS invoice_count, SUM(i.invoice_amount) AS invoice_amount , i.invoice_delstore,GROUP_CONCAT(i.invoice_id), s.store_name,s.store_code
FROM 
    invoices_tbl i
LEFT JOIN 
    stores_tbl s ON s.store_id = i.invoice_delstore
WHERE 
    i.invoice_status > 0 
GROUP BY 
    s.store_name,DATE_FORMAT(i.invoice_crtdon, '%d-%m'),
    DATE_FORMAT(i.invoice_crtdon, '%H')
ORDER BY 
   /* s.store_name,DATE_FORMAT(i.invoice_crtdon, '%d-%m'),
    DATE_FORMAT(i.invoice_crtdon, '%H');*/
     STR_TO_DATE(DATE_FORMAT(i.invoice_crtdon, '%d-%m'), '%d-%m') ASC,
        DATE_FORMAT(i.invoice_crtdon, '%H') ASC;
END$$

CREATE  PROCEDURE `purchasePerformanceReport` (IN `storeid` INT, IN `fdate` DATE, IN `todate` DATE)   BEGIN

SELECT s.store_id,s.store_code,s.store_name  FROM stores_tbl s WHERE s.store_status=1;

IF storeid > 1 THEN
	IF fdate IS NOT NULL AND todate IS NOT NULL THEN
        SELECT i.invdet_id,i.invdet_item,fnGetProductFromPack(i.invdet_item, 0) AS item ,fnGetVendorName(v.invoice_vendertype, v.invoice_vendor) AS vendor,v.invoice_number,v.invoice_dated,i.invdet_qty, v.invoice_amount,i.invdet_mrp,i.invdet_ptr ,s.store_id,s.store_code,s.store_name  FROM invoice_details i
        LEFT JOIN invoices_tbl v ON v.invoice_id=i.invdet_invoice
        LEFT JOIN stores_tbl s ON s.store_id=i.invdet_delivered  WHERE i.invdet_delivered=storeid AND v.invoice_dated BETWEEN fdate AND todate ORDER BY v.invoice_dated DESC ;
   /* ELSE 
     SELECT i.invdet_id,i.invdet_item,fnGetProductFromPack(i.invdet_item, 0) AS item ,fnGetVendorName(v.invoice_vendertype, v.invoice_vendor) AS vendor,v.invoice_number,v.invoice_dated,i.invdet_qty, v.invoice_amount,i.invdet_mrp,i.invdet_ptr ,s.store_id,s.store_code,s.store_name  FROM invoice_details i
        LEFT JOIN invoices_tbl v ON v.invoice_id=i.invdet_invoice
        LEFT JOIN stores_tbl s ON s.store_id=i.invdet_delivered  WHERE i.invdet_delivered=storeid ORDER BY v.invoice_dated DESC ;*/
  END IF;

/*ELSE
SELECT i.invdet_id,i.invdet_item,fnGetProductFromPack(i.invdet_item, 0) AS item ,fnGetVendorName(v.invoice_vendertype, v.invoice_vendor) AS vendor,v.invoice_number,v.invoice_dated,v.invoice_amount,i.invdet_qty, i.invdet_mrp,i.invdet_ptr ,s.store_id,s.store_code,s.store_name  FROM invoice_details i
LEFT JOIN invoices_tbl v ON v.invoice_id=i.invdet_invoice
LEFT JOIN stores_tbl s ON s.store_id=i.invdet_delivered ;*/
END IF ;
END$$

CREATE  PROCEDURE `purchaseReturnbillReports` (IN `storeid` INT, IN `fdate` DATE, IN `todate` DATE)   BEGIN
SELECT store_id,store_type,store_code,store_name FROM stores_tbl  WHERE store_status=1;
IF storeid>1 THEN
	IF fdate!="" AND todate!="" THEN
 SELECT p.returnbill_id,p.returnbill_number,p.returnbill_dated,fnGetVendorName(p.returnbill_vendertype,p.returnbill_vendor) AS vendor,fnGetProductFromPack(pd.return_item, 0) AS item ,s.store_id,s.store_code,s.store_name,i.invoice_number,pd.returnitem_subtotal ,pd.return_remark,u.user_staffname FROM purchasereturn_tbl p
 LEFT JOIN purchasereturn_details pd ON pd.return_billnum=p.returnbill_id
 LEFT JOIN stores_tbl s ON s.store_id=pd.return_store
 LEFT JOIN invoices_tbl i ON i.invoice_id=pd.return_invoice
 LEFT JOIN users_tbl u ON u.user_id=pd.return_crtdby
 WHERE pd.return_store=storeid AND pd.returncltn_status=5 AND pd.return_billdate BETWEEN fdate AND todate;
 END IF;
 END IF;

END$$

CREATE  PROCEDURE `purchaseReturnItems` (IN `billno` VARCHAR(255), IN `billdate` DATE, IN `ventype` INT, IN `venid` INT, IN `toatlamt` DECIMAL(10,2), IN `subtotal` DECIMAL(10,2), IN `diffnce` DECIMAL(10,2), IN `returndetails` TEXT, IN `adminid` INT)   BEGIN
DECLARE reids, resp ,sknrd_id,checkid,stk_dm INT DEFAULT 0;
SELECT user_id INTO checkid FROM users_tbl WHERE user_checkid=adminid;
IF( SELECT COUNT(*) FROM purchasereturn_tbl WHERE returnbill_number = trim(billno) ) = 0 THEN
		INSERT INTO purchasereturn_tbl(returnbill_number, returnbill_dated,returnbill_vendertype, returnbill_vendor,returnbill_amt,returnbill_subamt ,returnbill_difnce,returnbill_crtdby,returnbill_crtdon)
    	VALUES(billno,billdate,ventype,venid,toatlamt,subtotal,diffnce,checkid,CURRENT_TIMESTAMP());
    	SET reids = LAST_INSERT_ID();
    	SET resp = reids;
    	IF reids > 0 THEN
    		SET @text := TRIM(BOTH '##' FROM returndetails);
  			SET @strLen := 0;
  			SET @i := 1;
  			WHILE @strLen < LENGTH(@text) DO
    			SET @str := SUBSTRING_INDEX(@text, '##', @i);
    			SET @strLen := LENGTH(@str);
    			SET @i := @i + 1;
     			SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
        		SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 			SET @strGLen := 0;
     			SET @Gi := 1;
     			SET @icols := 1;
     			WHILE @strGLen < LENGTH(@GRAPE) DO
		        	SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
                	SET @strGLen := LENGTH(@Gstr);
                	SET @Gi := @Gi + 1;
                	IF @icols = 1 THEN
                   		SET @billno := SUBSTRING_INDEX(@Gstr, '|', -1);
                	ELSEIF @icols = 2 THEN
                    	SET @billdate := SUBSTRING_INDEX(@Gstr, '|', -1);
                	ELSEIF @icols = 3 THEN
                    	SET @batch := SUBSTRING_INDEX(@Gstr, '|', -1);
                	ELSEIF @icols = 4 THEN
                    	SET @invid := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 5 THEN
                    	SET @item := SUBSTRING_INDEX(@Gstr, '|', -1);
                	ELSEIF @icols = 6 THEN
                    	SET @vendtype := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 7 THEN
                    	SET @vendor := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 8 THEN
                    	SET @storeid := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 9 THEN
                    	SET @orgqty := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 10 THEN
                    	SET @retunqty := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 11 THEN
                    	SET @expiry := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 12 THEN
                    	SET @subtotal := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 13 THEN
                    	SET @strstkid := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSE
                    	SET @reason := SUBSTRING_INDEX(@Gstr, '|', -1);
                	END IF;
        			SET @icols := @icols + 1;
     			END WHILE;
     			INSERT INTO purchasereturn_details(return_stcknid,return_billnum,return_billdate,return_invoice,return_item,returnitem_batch,	item_qty,returnitem_qty,returnitem_expiry,returnitem_subtotal,return_remark,return_store,return_crtdby, return_crtdon)
            	VALUES(@strstkid,reids, @billdate, @invid, @item, @batch, @orgqty, @retunqty, @expiry,@subtotal, @reason, @storeid,checkid,CURRENT_TIMESTAMP());
                SELECT strstk_refer INTO sknrd_id FROM storestock_pricing WHERE strstk_id = @strstkid;
                SELECT stockin_damaged  INTO stk_dm FROM stock_inwards WHERE stockin_id = sknrd_id;

           IF @reason='damage' THEN
                SET @rm:=@retunqty-stk_dm;
                	UPDATE stock_inwards SET stockin_damaged=@retunqty-(stk_dm+@rm) , stockin_reserved=(stockin_reserved+ @retunqty) WHERE stockin_id=sknrd_id;
                END IF;
                UPDATE storestock_pricing SET strstk_reserved=(strstk_reserved+ @retunqty) WHERE strstk_id=@strstkid ;
                UPDATE storestock_master SET storestock_reserved=(storestock_reserved+ @retunqty) WHERE storestock_item=@item AND storestock_store=@storeid;
  			END WHILE;
            END IF;
    END IF;
END$$

CREATE  PROCEDURE `purchaseReturnPreviousData` (IN `branchid` INT, IN `item` INT, IN `storeid` INT, IN `vendortype` INT, IN `vendor` INT, IN `fromdate` DATE, IN `todate` DATE)   BEGIN
IF branchid>1 THEN
IF item>0 THEN
SELECT p.return_item ,fnGetProductFromPack(p.return_item, 0) AS invitem ,p.returnitem_batch,p.returnitem_qty,p.returnitem_expiry,pp.returnbill_number,pp.returnbill_dated, p.return_store,pp.returnbill_id ,s.store_code,s.store_name,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,u.user_staffname,p.return_remark FROM purchasereturn_details p
JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
JOIN stores_tbl s ON s.store_id=p.return_store
JOIN users_tbl u ON u.user_id=pp.returnbill_crtdby
WHERE p.return_item=item AND p.returncltn_status=5 AND p.return_store=branchid AND p.return_billdate BETWEEN fromdate AND todate ORDER BY pp.returnbill_dated DESC;
ELSEIF storeid>1 THEN
    SELECT p.return_item ,fnGetProductFromPack(p.return_item, 0) AS invitem ,p.returnitem_batch,p.returnitem_qty,p.returnitem_expiry,pp.returnbill_number,pp.returnbill_dated, p.return_store,pp.returnbill_id , s.store_code,s.store_name,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,u.user_staffname,p.return_remark FROM purchasereturn_details p
    JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
    JOIN stores_tbl s ON s.store_id=p.return_store
    JOIN users_tbl u ON u.user_id=pp.returnbill_crtdby
    WHERE p.return_store=storeid AND p.returncltn_status=5 AND p.return_billdate BETWEEN fromdate AND todate ORDER BY pp.returnbill_dated DESC;
ELSEIF vendortype>0 AND vendor>0 THEN
SELECT p.return_item ,fnGetProductFromPack(p.return_item, 0) AS invitem ,p.returnitem_batch,p.returnitem_qty,p.returnitem_expiry,pp.returnbill_number,pp.returnbill_dated, p.return_store, pp.returnbill_id ,s.store_code,s.store_name,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,u.user_staffname,p.return_remark FROM purchasereturn_details p
    JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
    JOIN stores_tbl s ON s.store_id=p.return_store
    JOIN users_tbl u ON u.user_id=pp.returnbill_crtdby
    WHERE pp.returnbill_vendertype=vendortype AND pp.returnbill_vendor=vendor AND p.returncltn_status=5 AND p.return_store=branchid AND p.return_billdate BETWEEN fromdate AND todate ORDER BY pp.returnbill_dated DESC;
    ELSE
    SELECT p.return_item ,fnGetProductFromPack(p.return_item, 0) AS invitem ,p.returnitem_batch,p.returnitem_qty,p.returnitem_expiry,pp.returnbill_number,pp.returnbill_dated, p.return_store, pp.returnbill_id ,s.store_code,s.store_name,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,u.user_staffname,p.return_remark FROM purchasereturn_details p
    JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
    JOIN stores_tbl s ON s.store_id=p.return_store
    JOIN users_tbl u ON u.user_id=pp.returnbill_crtdby
    WHERE p.return_store=branchid AND p.returncltn_status=5 AND p.return_billdate BETWEEN fromdate AND todate ORDER BY pp.returnbill_dated DESC;
END IF;
ELSE
IF item>0 THEN
SELECT p.return_item ,fnGetProductFromPack(p.return_item, 0) AS invitem ,p.returnitem_batch,p.returnitem_qty,p.returnitem_expiry,pp.returnbill_number,pp.returnbill_dated, p.return_store, pp.returnbill_id ,s.store_code,s.store_name,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,u.user_staffname,p.return_remark FROM purchasereturn_details p
JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
JOIN stores_tbl s ON s.store_id=p.return_store
JOIN users_tbl u ON u.user_id=pp.returnbill_crtdby
WHERE p.return_item=item AND p.returncltn_status=5 AND p.return_billdate BETWEEN fromdate AND todate ORDER BY pp.returnbill_dated DESC;
ELSEIF storeid>1 THEN
    SELECT p.return_item ,fnGetProductFromPack(p.return_item, 0) AS invitem ,p.returnitem_batch,p.returnitem_qty,p.returnitem_expiry,pp.returnbill_number,pp.returnbill_dated, p.return_store, pp.returnbill_id ,s.store_code,s.store_name,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,u.user_staffname,p.return_remark FROM purchasereturn_details p
    JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
    JOIN stores_tbl s ON s.store_id=p.return_store
    JOIN users_tbl u ON u.user_id=pp.returnbill_crtdby
    WHERE p.return_store=storeid AND p.returncltn_status=5 AND p.return_billdate BETWEEN fromdate AND todate ORDER BY pp.returnbill_dated DESC;
ELSEIF vendortype>0 AND vendor>0 THEN
SELECT p.return_item ,fnGetProductFromPack(p.return_item, 0) AS invitem ,p.returnitem_batch,p.returnitem_qty,p.returnitem_expiry,pp.returnbill_number,pp.returnbill_dated, p.return_store, pp.returnbill_id ,s.store_code,s.store_name,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,u.user_staffname,p.return_remark FROM purchasereturn_details p
    JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
    JOIN stores_tbl s ON s.store_id=p.return_store
    JOIN users_tbl u ON u.user_id=pp.returnbill_crtdby
    WHERE pp.returnbill_vendertype=vendortype AND pp.returnbill_vendor=vendor AND p.returncltn_status=5 AND p.return_billdate BETWEEN fromdate AND todate ORDER BY pp.returnbill_dated DESC;
    ELSE
    SELECT p.return_item ,fnGetProductFromPack(p.return_item, 0) AS invitem ,p.returnitem_batch,p.returnitem_qty,p.returnitem_expiry,pp.returnbill_number,pp.returnbill_dated, p.return_store, pp.returnbill_id ,s.store_code,s.store_name,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,u.user_staffname,p.return_remark FROM purchasereturn_details p
    JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
    JOIN stores_tbl s ON s.store_id=p.return_store
    JOIN users_tbl u ON u.user_id=pp.returnbill_crtdby
    WHERE   p.returncltn_status=5 AND p.return_billdate BETWEEN fromdate AND todate ORDER BY pp.returnbill_dated DESC;
END IF;
END IF;
END$$

CREATE  PROCEDURE `quickAddBrand` (IN `brand` VARCHAR(200), IN `manufacturer` INT, IN `admin` INT)   BEGIN
	DECLARE brid INT DEFAULT 0;
	if TRIM(brand) <> '' AND manufacturer > 0 THEN
    	INSERT INTO `brands_tbl`(`brand_name`, `brand_owner`, `brand_crtdby` ) 
    	VALUES (brand, manufacturer, admin);
        SET brid = LAST_INSERT_ID();
    END IF;
    SELECT brid;
END$$

CREATE  PROCEDURE `quickAddBrandNew` (IN `brand` VARCHAR(200), IN `manufacturer` INT, IN `admin` INT)   BEGIN
	DECLARE brid INT DEFAULT 0;
	if TRIM(brand) <> '' AND manufacturer > 0 THEN
    if EXISTS (SELECT 1 FROM brands_tbl b WHERE b.brand_name=brand)THEN 
    SELECT  MIN(brand_id) INTO brid FROM brands_tbl WHERE brand_name=brand GROUP BY brand_name HAVING COUNT(*) >= 1;	
        INSERT IGNORE INTO `brand_manufacturer_tbl`( `brnd_id`, `brndmanu_id`) VALUES (brid,manufacturer);
        ELSE
        INSERT INTO `brands_tbl`(`brand_name`, `brand_owner`, `brand_crtdby` ) 
    	VALUES (brand, manufacturer, admin);
        SET brid = LAST_INSERT_ID();
        
        INSERT IGNORE INTO `brand_manufacturer_tbl`( `brnd_id`, `brndmanu_id`) VALUES (brid,manufacturer);
        END IF;
    END IF;
    SELECT brid;
END$$

CREATE  PROCEDURE `quickAddDrugClass` (IN `drgclass` VARCHAR(150), IN `parent` INT, IN `subclass` INT, IN `adminid` INT)   BEGIN
	DECLARE did, sclass INT DEFAULT 0;
	
    IF subclass > 0 THEN
    	SET sclass = subclass;
    ELSEIF parent > 0 THEN
    	SET sclass = parent;
    ELSE
    	SET sclass = 0;
    END IF;
    
    INSERT INTO drug_classifications 
    ( drugclass_name, drugclass_parent, drugclass_crtdby) 
    VALUES(drgclass, sclass, adminid);
    
    SET did = LAST_INSERT_ID();
    
    SELECT did;
END$$

CREATE  PROCEDURE `quickAddIngredient` (IN `ingred` VARCHAR(200), IN `itype` INT, IN `admin` INT)   BEGIN
	DECLARE brid INT DEFAULT 0;
	if TRIM(ingred) <> '' THEN
    	INSERT INTO ingredients_tbl (ingred_name, ingred_type, ingred_crtdby ) 
    	VALUES (ingred, itype, admin);
        SET brid = LAST_INSERT_ID();
    END IF; 
    SELECT brid;
END$$

CREATE  PROCEDURE `quickAddLocation` (IN `location` VARCHAR(100), IN `pin` VARCHAR(10), IN `adminid` INT)   BEGIN
	DECLARE lid INT DEFAULT 0;
	if TRIM(location) <> '' AND TRIM(pin) <> '' THEN
    	INSERT INTO delivery_areas( delarea_location, delarea_pincode, delarea_crtdby ) 
        VALUES( location, pin, adminid);
        SET lid = LAST_INSERT_ID();
    END IF;
    SELECT lid;
END$$

CREATE  PROCEDURE `quickAddManufacturer` (IN `manfname` VARCHAR(100), IN `admin` INT)   BEGIN
	INSERT INTO manufacturers_tbl (manuf_name, manuf_crtdby) 
    VALUES(manfname, admin);
    SELECT last_insert_id() as id;
END$$

CREATE  PROCEDURE `quickAddMedicine` (IN `medicine` VARCHAR(255), IN `adminid` INT)   BEGIN
	DECLARE medid INT DEFAULT 0;
	if TRIM(medicine) <> '' THEN
    	INSERT INTO generic_medicines( genmed_name, genmed_crtdby )
        VALUES( medicine, adminid);
        
        SET medid = LAST_INSERT_ID();
    END IF;
    SELECT medid;
END$$

CREATE  PROCEDURE `removeAdvice` (IN `adviceid` INT)   BEGIN
	DELETE FROM advices_table WHERE advice_id = adviceid;
    ALTER TABLE advices_table AUTO_INCREMENT = 1;
END$$

CREATE  PROCEDURE `removeCourierDelievry` (IN `courierid` INT, IN `flag` INT, IN `item` INT)   BEGIN
	select 1;
END$$

CREATE  PROCEDURE `removeDealerProduct` (IN `dealerid` INT, IN `product` INT, IN `adminid` INT)   BEGIN
	UPDATE dealer_products    
    SET dealerprod_status = 0, dealerprod_updby = adminid 
    WHERE dealerprod_dealer = dealerid AND dealerprod_product = product;
END$$

CREATE  PROCEDURE `removeDealerSubdealer` (IN `dealerid` INT, IN `parentid` INT, IN `admin` INT)   BEGIN
	UPDATE subdealers_tbl s
    SET s.subdealer_status = 0, s.subdealer_updby = admin 
    WHERE s.subdealer_dealer = dealerid AND s.subdealer_parent = parentid;
END$$

CREATE  PROCEDURE `removeDeliveryArea` (IN `storeid` INT, IN `delarea` INT, IN `adminid` INT)   BEGIN
	UPDATE store_delivery 
    SET strdelv_status = 0, strdelv_updby = adminid 
    WHERE strdelv_store = storeid AND strdelv_area = delarea;
END$$

CREATE  PROCEDURE `removeDistributorManufacturer` (IN `distrid` INT, IN `manufid` INT, IN `adminid` INT)   BEGIN
UPDATE distributor_products p INNER JOIN products_tbl q on p.distriprod_product=q.product_id INNER JOIN  distributor_manufacturers m on m.distrimanu_company=q.product_manufacturer SET p.distriprod_status = 0, p.distriprod_updby = adminid WHERE p.distriprod_distributor=distrid and m.distrimanu_company=manufid and q.product_manufacturer=manufid;
 

	UPDATE distributor_manufacturers d
    SET d.distrimanu_status = 0, d.distrimanu_updby = adminid
    WHERE d.distrimanu_distributor = distrid AND d.distrimanu_company = manufid;
END$$

CREATE  PROCEDURE `removeDistributorProduct` (IN `distrid` INT, IN `product` INT, IN `adminid` INT)   BEGIN
	UPDATE distributor_products   
    SET distriprod_status = 0, distriprod_updby = adminid 
    WHERE distriprod_distributor = distrid AND distriprod_product = product;
END$$

CREATE  PROCEDURE `removeFaq` (IN `faqid` INT)   BEGIN
	DELETE FROM faq_table WHERE faq_id = faqid;
    ALTER TABLE faq_table AUTO_INCREMENT = 1;
END$$

CREATE  PROCEDURE `removeInvoiceItem` (IN `invitem` INT)   BEGIN
	DECLARE respcode, invid INT DEFAULT 0;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
    	ROLLBACK;
        SET respcode = 0;
    END;
    
    SELECT x.invdet_invoice INTO invid FROM invoice_details x 
    WHERE x.invdet_id = invitem;
    
    IF (SELECT COUNT(*) FROM invoices_tbl y 
        WHERE y.invoice_id = invid AND y.invoice_status = 1 AND y.invoice_delstatus = 0 AND y.invoice_paystatus = 0) = 1 THEN
        START TRANSACTION;
        	UPDATE invoice_details SET invdet_status = 0 WHERE invdet_id = invitem;
            SET respcode = 1;
        COMMIT;
    END IF;
    SELECT respcode;
END$$

CREATE  PROCEDURE `removeStockistManufacturer` (IN `stkid` INT, IN `manufid` INT, IN `adminid` INT)   BEGIN
 UPDATE stockist_products p INNER JOIN products_tbl q on p.stockistprod_product=q.product_id INNER JOIN stockist_manufacturers m on m.stockmanu_company=q.product_manufacturer SET p.stockistprod_status = 0, p.stockistprod_updby = adminid WHERE p.stockistprod_stockist=stkid and m.stockmanu_company=manufid and q.product_manufacturer=manufid;
 
	UPDATE stockist_manufacturers s
    SET s.stockmanu_status = 0, s.stockmanu_updby = adminid
    WHERE s.stockmanu_stockist = stkid AND s.stockmanu_company = manufid;
    
   
END$$

CREATE  PROCEDURE `removeStockistProduct` (IN `stkid` INT, IN `product` INT, IN `adminid` INT)   BEGIN
	UPDATE stockist_products  
    SET stockistprod_status = 0, stockistprod_updby = adminid 
    WHERE stockistprod_stockist = stkid AND stockistprod_product = product;
END$$

CREATE  PROCEDURE `removeSubdistribution` (IN `distrbid` INT, IN `parent` INT, IN `adminid` INT)   BEGIN
	UPDATE subdistributors_tbl 
    SET subdistri_status = 0, subdistri_updby = adminid 
    WHERE subdistri_distributor = distrbid AND subdistri_parent = parent;
END$$

CREATE  PROCEDURE `returnBillItemsDetailsByStore` (IN `billno` INT, IN `storeid` INT)   BEGIN

SELECT c.courier_id,c.courier_type,c.courier_name,c.courier_mobile,c.courier_contact FROM couriers_tbl c WHERE c.courier_status =1;

SELECT p.returnbill_id,p.returnbill_number,p.returnbill_dated,p.returnbill_vendertype,p.returnbill_vendor,p.returnbill_status,fnGetVendorName(p.returnbill_vendertype,p.returnbill_vendor) AS vendor FROM purchasereturn_tbl p WHERE p.returnbill_id=billno;

SELECT pp.return_id,pp.return_item,fnGetProductFromPack(pp.return_item,0) AS invitem,pp.returnitem_batch,pp.returnitem_qty,pp.returnitem_expiry,pp.return_remark,pp.returnitem_subtotal,pp.return_store,pp.return_courier,pp.courier_cltdon,  pp.returncltn_status,s.store_code,s.store_name,i.invoice_id,i.invoice_number
FROM purchasereturn_details pp
LEFT JOIN stores_tbl s ON s.store_id=pp.return_store
LEFT JOIN invoices_tbl i ON i.invoice_id=pp.return_invoice 
WHERE pp.return_billnum=billno AND pp.return_store=storeid;
END$$

CREATE  PROCEDURE `returnDeliveredItems` (IN `flag` INT, IN `return_ids` TEXT)   BEGIN
    DECLARE front, TempValue, alltracks, billid ,remark TEXT DEFAULT NULL;
    DECLARE frontlen INT DEFAULT NULL;
    DECLARE rids,count_5,count_1,count_0 INT DEFAULT NULL;
    IF flag = 1 THEN
        SET billid = return_ids;
        iterator: LOOP
            IF LENGTH(TRIM(return_ids)) = 0 OR return_ids IS NULL THEN
                LEAVE iterator;
            END IF;
            SET front = SUBSTRING_INDEX(return_ids,',',1);
            SET frontlen = LENGTH(front);
            SET TempValue = TRIM(front);
            #update purchasereturn_details
            UPDATE purchasereturn_details SET returncltn_status=5 , return_delon=CURRENT_TIMESTAMP() WHERE return_id=TempValue;
            #update purchasereturn_tbl
            SELECT 	return_billnum INTO rids FROM purchasereturn_details WHERE 	return_id=TempValue;
            SELECT  COUNT(CASE WHEN returncltn_status = 5 THEN 1 END), COUNT(CASE WHEN returncltn_status = 1 THEN 1 END),COUNT(CASE WHEN returncltn_status = 0 THEN 1 END) INTO count_5, count_1,count_0 FROM purchasereturn_details WHERE return_billnum=rids;
            IF count_5 > 0 AND count_1=0 AND COUNT_0=0 THEN
            	UPDATE purchasereturn_tbl SET returnbill_status=10 WHERE returnbill_id=rids;
            /*ELSEIF count_5 > 0 AND (count_1>0 or count_0>0) THEN
            	UPDATE purchasereturn_tbl SET returnbill_status=5 WHERE returnbill_id=rids;
           */
            END IF;
            SET return_ids = INSERT(return_ids, 1, frontlen + 1, '');
        END LOOP;
    END IF;
END$$

CREATE  PROCEDURE `returnItemsCollections` (IN `storeid` INT)   BEGIN
IF storeid>1 THEN
   SELECT p.return_id ,pp.returnbill_id,pp.returnbill_number,pp.returnbill_dated,pp.returnbill_vendertype,pp.returnbill_vendor,pp.returnbill_amt,pp.returnbill_subamt,pp.returnbill_difnce,s.store_name,s.store_id
    ,pp.returnbill_status,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,c.courier_name, p.courier_cltdon,p.returncltn_status, SUM(CASE WHEN p.returncltn_status = 1 THEN 1 ELSE 0 END) AS returncltn_status_1_count,
            SUM(CASE WHEN p.returncltn_status = 0 THEN 1 ELSE 0 END) AS returncltn_status_0_count ,SUM(CASE WHEN p.returncltn_status = 5 THEN 1 ELSE 0 END) AS returncltn_status_5_count ,COUNT(p.return_item)AS itemcount FROM purchasereturn_details p
    LEFT JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
    LEFT JOIN stores_tbl s ON s.store_id=p.return_store
    LEFT JOIN couriers_tbl c ON c.courier_id=p.return_courier
    WHERE pp.returnbill_status>0 AND p.return_store=storeid GROUP BY p.return_billnum,p.return_store  ORDER BY pp.returnbill_dated DESC ;
    ELSE
    SELECT p.return_id ,pp.returnbill_id,pp.returnbill_number,pp.returnbill_dated,pp.returnbill_vendertype,pp.returnbill_vendor,pp.returnbill_amt,pp.returnbill_subamt,pp.returnbill_difnce,s.store_name,s.store_id
    ,pp.returnbill_status,fnGetVendorName(pp.returnbill_vendertype,pp.returnbill_vendor) AS vendor ,c.courier_name, p.courier_cltdon,p.returncltn_status, SUM(CASE WHEN p.returncltn_status = 1 THEN 1 ELSE 0 END) AS returncltn_status_1_count,
            SUM(CASE WHEN p.returncltn_status = 0 THEN 1 ELSE 0 END) AS returncltn_status_0_count ,SUM(CASE WHEN p.returncltn_status = 5 THEN 1 ELSE 0 END) AS returncltn_status_5_count ,COUNT(p.return_item)AS itemcount FROM purchasereturn_details p
    LEFT JOIN purchasereturn_tbl pp ON pp.returnbill_id=p.return_billnum
    LEFT JOIN stores_tbl s ON s.store_id=p.return_store
    LEFT JOIN couriers_tbl c ON c.courier_id=p.return_courier
    WHERE pp.returnbill_status>0 GROUP BY p.return_billnum,p.return_store  ORDER BY pp.returnbill_dated DESC ;
    END IF;
END$$

CREATE  PROCEDURE `ReturnOrderbyOrderID` (IN `orderId` VARCHAR(255), IN `userid` INT, IN `reason` TEXT)   BEGIN
DECLARE ordid INT DEFAULT 0;
SELECT o.order_id INTO ordid  FROM orders_tbl o JOIN customers_tbl c ON c.customer_id=o.order_customer WHERE o.order_orderid=orderId and o.order_customer=userid;
 UPDATE orders_tbl o SET o.order_status=2  WHERE o.order_orderid=orderId and o.order_customer=userid;
 
 UPDATE order_details o set o.ordet_status=2 WHERE o.ordet_order=ordid;


INSERT INTO `order_return_status_history`( `order_id`, `return_status`, `return_reason`, `status_date`) VALUES (ordid,1,reason,CURRENT_TIMESTAMP);
END$$

CREATE  PROCEDURE `reworkDrugSequence` (IN `drugclass` INT)   BEGIN
	DECLARE parentdrugs, subdrugs TEXT DEFAULT '';
    DECLARE theparent, superparent INT DEFAULT 0;

    IF drugclass > 0 THEN
    	SELECT q.drugclass_parent, z.drugclass_parent INTO theparent, superparent 
        FROM drug_classifications q 
        LEFT JOIN drug_classifications z ON z.drugclass_id = q.drugclass_parent 
        WHERE q.drugclass_id = drugclass;
        #SELECT theparent, superparent;
        IF theparent = 0 THEN
        	UPDATE drug_classifications SET drugclass_counter = 0, drugclass_seq = drugclass_id
    		WHERE drugclass_id = drugclass;
        ELSEIF superparent > 0 THEN
        	UPDATE drug_classifications SET drugclass_counter = 2, 
    		drugclass_seq = CONCAT(superparent, '_', superparent, '_', theparent) 
    		WHERE drugclass_id = drugclass;
        ELSE
        	UPDATE drug_classifications SET drugclass_counter = 1, 
    		drugclass_seq = CONCAT(theparent, '_', theparent) 
    		WHERE drugclass_id = drugclass;
        END IF;
    ELSE
    	UPDATE drug_classifications SET drugclass_counter = 0, drugclass_seq = drugclass_id
    	WHERE drugclass_parent = 0;
		
        SELECT GROUP_CONCAT(x.drugclass_id) INTO parentdrugs 
    	FROM drug_classifications x WHERE x.drugclass_parent = 0;
    
    	UPDATE drug_classifications SET drugclass_counter = 1, 
    	drugclass_seq = CONCAT(drugclass_parent, '_', drugclass_parent) 
    	WHERE FIND_IN_SET(drugclass_parent, parentdrugs);
    
    	SELECT GROUP_CONCAT(z.drugclass_id) INTO subdrugs 
    	FROM drug_classifications z WHERE z.drugclass_counter = 1;
        
    	UPDATE drug_classifications SET drugclass_counter = 2, 
    	drugclass_seq = CONCAT(fnGetDrugclassParent(drugclass_id), '_', fnGetDrugclassParent(drugclass_id), '_', drugclass_parent) 
    	WHERE FIND_IN_SET(drugclass_parent, subdrugs);
    END IF;
END$$

CREATE  PROCEDURE `reworkMenuSequence` (IN `menuid` INT)   BEGIN
	DECLARE mainmenu TEXT DEFAULT '';
    
    UPDATE programs_table_seq SET progr_seq = progr_id
    WHERE progr_parent = 0;
    
    SELECT GROUP_CONCAT(q.progr_id) INTO mainmenu 
    FROM programs_table_seq q WHERE q.progr_parent = 0;
    
    UPDATE programs_table_seq SET 
    progr_seq = CONCAT(progr_parent, '_', progr_id) 
    WHERE FIND_IN_SET(progr_parent, mainmenu);

	SELECT * FROM programs_table_seq;
    
END$$

CREATE  PROCEDURE `reworkProductClassSequence` (IN `prodclass` INT)   BEGIN
	DECLARE parents, subs TEXT DEFAULT '';
    DECLARE theparent, superparent INT DEFAULT 0;
    
    IF prodclass > 0 THEN
    	SELECT q.prodclass_parent, z.prodclass_parent INTO theparent, superparent 
        FROM product_classes q 
        LEFT JOIN product_classes z ON z.prodclass_id = q.prodclass_parent 
        WHERE q.prodclass_id = prodclass;
   		IF theparent = 0 THEN
        	UPDATE product_classes SET prodclass_counter = 0, prodclass_seq = prodclass_id
    		WHERE prodclass_id = prodclass;
        ELSEIF superparent > 0 THEN
        	UPDATE product_classes SET prodclass_counter = 2, 
    		prodclass_seq = CONCAT(superparent, '_', superparent, '_', theparent)
            WHERE prodclass_id = prodclass;
        ELSE
        	UPDATE product_classes SET prodclass_counter = 1, 
    		prodclass_seq = CONCAT(theparent, '_', theparent) 
            WHERE prodclass_id = prodclass;
        END IF;
    ELSE
    	UPDATE product_classes SET prodclass_counter = 0, prodclass_seq = prodclass_id
    	WHERE prodclass_parent = 0;
    
    	SELECT GROUP_CONCAT(x.prodclass_id) INTO parents 
    	FROM product_classes x WHERE x.prodclass_parent = 0;
    
    	UPDATE product_classes SET prodclass_counter = 1, 
    	prodclass_seq = CONCAT(prodclass_parent, '_', prodclass_parent) 
    	WHERE FIND_IN_SET(prodclass_parent, parents);
    
    	SELECT GROUP_CONCAT(z.prodclass_id) INTO subs 
    	FROM product_classes z WHERE z.prodclass_counter = 1;

    	UPDATE product_classes SET prodclass_counter = 2, 
    	prodclass_seq = CONCAT(fnGetProductclassParent(prodclass_id), '_', fnGetProductclassParent(prodclass_id), '_', prodclass_parent) 
    	WHERE FIND_IN_SET(prodclass_parent, subs);
    END IF;
END$$

CREATE  PROCEDURE `SalesReturnItems` (IN `billNo` VARCHAR(100), IN `returndetails` TEXT, IN `taxamt` DECIMAL(10,2), IN `cgst` DECIMAL(10,2), IN `sgst` DECIMAL(10,2), IN `netpay` DECIMAL(10,2), IN `adminid` INT)   BEGIN
DECLARE billid, strids,stkTotal INT DEFAULT 0;
DECLARE lqty DECIMAL(10,2) DEFAULT 0;
DECLARE sqty DECIMAL(10,2) DEFAULT 0;
DECLARE minvalue,stockval DECIMAL(10,0) DEFAULT 0;
DECLARE strstkstore INT DEFAULT 0;


INSERT INTO salesreturn_tbl(salesret_billnum, salesret_Taxamt, salesret_cgst, salesret_sgst, salesret_netpay, salesret_crtdby) VALUES (billNo, taxamt,cgst, sgst, netpay, adminid);

/* Return item details */
  
  SET billid = LAST_INSERT_ID();
    IF billid > 0 THEN
    	SET @text := TRIM(BOTH '##' FROM returndetails);
  SET @strLen := 0;
  SET @i := 1;
  WHILE @strLen < LENGTH(@text) DO
    SET @str := SUBSTRING_INDEX(@text, '##', @i);
    SET @strLen := LENGTH(@str);
    SET @i := @i + 1;
    SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
     SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 SET @strGLen := 0;
     SET @Gi := 1;
     SET @icols := 1;
     WHILE @strGLen < LENGTH(@GRAPE) DO
        SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
        SET @strGLen := LENGTH(@Gstr);
        SET @Gi := @Gi + 1;
        IF @icols=1 THEN
        SET @billno := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols =2 THEN
        SET @itemid := SUBSTRING_INDEX(@Gstr, '|', -1);
       ELSEIF @icols = 3 THEN
        	SET @itemname := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 4 THEN
            SET @hsn := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 5 THEN
            SET @mfr := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 6 THEN
            SET @batch := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 7 THEN
            SET @exp := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 8 THEN
            SET @sch := SUBSTRING_INDEX(@Gstr, '|', -1);
              ELSEIF @icols = 9 THEN
            SET @mrp := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 10 THEN
            SET @discper := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 11 THEN
            SET @rate := SUBSTRING_INDEX(@Gstr, '|', -1);
              ELSEIF @icols = 12 THEN
            SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 13 THEN
            SET @amt := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 14 THEN
            SET @cgst := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 15 THEN
            SET @strstkid := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 16 THEN
            SET @sgst := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 17 THEN
            SET @rtype := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSE
            SET @mode := SUBSTRING_INDEX(@Gstr, '|', -1);
        END IF;
        SET @icols := @icols + 1;
     END WHILE;
     INSERT INTO salesretitem_tbl(ret_billnum,ret_itemid, ret_item, ret_hsn, ret_mfr, ret_batch, ret_expiry, ret_sch, ret_mrp, ret_discount, ret_rate, ret_qty, ret_amount, ret_cgst,  ret_sgst)  VALUES (@billno, @itemid, @itemname, @hsn, @mfr, @batch, @exp, @sch, @mrp, @discper, @rate, @qty, @amt, @cgst, @sgst);
     
     # only for loosereturn tbl --
     select strstk_store into strstkstore from storestock_pricing WHERE strstk_id=@strstkid AND strstk_item=@itemid;
     # --->
     SELECT ss.strstk_refer,ss.strstk_stock INTO strids,stkTotal FROM storestock_pricing ss WHERE ss.strstk_id= @strstkid;
    
    IF @mode='Strip' THEN
    
    SELECT LsQty_lqty, LsQty_sqty INTO lqty, sqty FROM looseitemqty_tbl WHERE LsQty_refer = strids AND LsQty_batch=@batch;
       
       
       if @rtype=1  THEN
       
       set stockval=stkTotal + FLOOR(@qty / lqty);
       set minvalue= @qty-((stockval-stkTotal)*lqty);
        
        UPDATE storestock_pricing SET strstk_stock=stockval WHERE strstk_id=@strstkid AND strstk_item=@itemid;
    UPDATE storestock_master SET storestock_available=stockval WHERE storestock_item=@itemid AND storestock_store=strstkstore;
            UPDATE bills_table b SET b.bill_status=0 WHERE b.bill_no=@billno;

            UPDATE looseitreturn_tbl SET LsQty_sqty = LsQty_sqty + minvalue WHERE LsQty_refer = strids AND LsQty_batch=@batch;

       ELSE
     UPDATE looseitreturn_tbl SET LsQty_sqty = LsQty_sqty + @qty WHERE LsQty_refer = strids AND LsQty_batch=@batch;

       END IF;
     
    ELSE
    
    UPDATE storestock_pricing SET strstk_stock=(strstk_stock+@qty) WHERE strstk_id=@strstkid AND strstk_item=@itemid;
    UPDATE storestock_master SET storestock_available=(storestock_available+@qty) WHERE storestock_item=@itemid AND storestock_store=strstkstore;
    
            UPDATE bills_table b SET b.bill_status=0 WHERE b.bill_no=@billno;

    END IF;
    
    # COMMIT;
	
  END WHILE;
  END IF;
  
SELECT sa.salesret_id, sa.salesret_billnum,sa.salesret_Taxamt, sa.salesret_cgst, sa.salesret_sgst, sa.salesret_netpay, st.* FROM salesreturn_tbl sa left JOIN salesretitem_tbl st ON st.ret_billnum = sa.salesret_billnum WHERE sa.salesret_billnum=billNo;
   

SELECT * FROM bills_table b WHERE b.bill_no = billNo; 


END$$

CREATE  PROCEDURE `SalesReturnItemsold` (IN `billNo` VARCHAR(100), IN `returndetails` TEXT, IN `taxamt` DECIMAL(10,2), IN `cgst` DECIMAL(10,2), IN `sgst` DECIMAL(10,2), IN `netpay` DECIMAL(10,2), IN `adminid` INT)   BEGIN
DECLARE billid INT DEFAULT 0;
INSERT INTO salesreturn_tbl(salesret_billnum, salesret_Taxamt, salesret_cgst, salesret_sgst, salesret_netpay, salesret_crtdby) VALUES (billNo, taxamt,cgst, sgst, netpay, adminid);
   /* Return item details */
  SET billid = LAST_INSERT_ID();
    IF billid > 0 THEN
    	SET @text := TRIM(BOTH '##' FROM returndetails);
  SET @strLen := 0;
  SET @i := 1;
  WHILE @strLen < LENGTH(@text) DO
    SET @str := SUBSTRING_INDEX(@text, '##', @i);
    SET @strLen := LENGTH(@str);
    SET @i := @i + 1;
    SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
     SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 SET @strGLen := 0;
     SET @Gi := 1;
     SET @icols := 1;
     WHILE @strGLen < LENGTH(@GRAPE) DO
        SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
        SET @strGLen := LENGTH(@Gstr);
        SET @Gi := @Gi + 1;
        IF @icols=1 THEN
        SET @billno := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols =2 THEN
        SET @itemid := SUBSTRING_INDEX(@Gstr, '|', -1);
       ELSEIF @icols = 3 THEN
        	SET @itemname := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 4 THEN
            SET @hsn := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 5 THEN
            SET @mfr := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 6 THEN
            SET @batch := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 7 THEN
            SET @exp := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 8 THEN
            SET @sch := SUBSTRING_INDEX(@Gstr, '|', -1);
              ELSEIF @icols = 9 THEN
            SET @mrp := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 10 THEN
            SET @discper := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 11 THEN
            SET @rate := SUBSTRING_INDEX(@Gstr, '|', -1);
              ELSEIF @icols = 12 THEN
            SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 13 THEN
            SET @amt := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 14 THEN
            SET @cgst := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 15 THEN
            SET @strstkid := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSE
            SET @sgst := SUBSTRING_INDEX(@Gstr, '|', -1);
        END IF;
        SET @icols := @icols + 1;
     END WHILE;
     INSERT INTO salesretitem_tbl(ret_billnum,ret_itemid, ret_item, ret_hsn, ret_mfr, ret_batch, ret_expiry, ret_sch, ret_mrp, ret_discount, ret_rate, ret_qty, ret_amount, ret_cgst,  ret_sgst)  VALUES (@billno, @itemid, @itemname, @hsn, @mfr, @batch, @exp, @sch, @mrp, @discper, @rate, @qty, @amt, @cgst, @sgst);
	UPDATE storestock_pricing SET strstk_stock= strstk_stock+@qty WHERE strstk_id=@strstkid AND strstk_item=@itemid;
    /*SELECT xx.strstk_store as storeid FROM storestock_pricing xx WHERE xx.strstk_id= @strstkid;*/
    UPDATE storestock_master m SET m.storestock_available = m.storestock_available + @qty WHERE m.storestock_item=@itemid;
    UPDATE bills_table b SET b.bill_status=0 WHERE b.bill_no=@billno;
  END WHILE;
  END IF;
SELECT sa.salesret_id, sa.salesret_billnum, sa.salesret_Taxamt, sa.salesret_cgst, sa.salesret_sgst, sa.salesret_netpay, st.* FROM salesreturn_tbl sa JOIN salesretitem_tbl st ON st.ret_billnum = sa.salesret_billnum WHERE sa.salesret_billnum=billNo;
SELECT * FROM bills_table b WHERE b.bill_no = billNo;
END$$

CREATE  PROCEDURE `SalesReturnItemsTest` (IN `billNo` VARCHAR(100), IN `returndetails` TEXT, IN `taxamt` DECIMAL(10,2), IN `cgst` DECIMAL(10,2), IN `sgst` DECIMAL(10,2), IN `netpay` DECIMAL(10,2), IN `adminid` INT)   BEGIN
    -- ========================
    -- DECLARE VARIABLES
    -- ========================
    DECLARE billid INT DEFAULT 0;
    DECLARE lqty, sqty INT DEFAULT 0;
    DECLARE minvalue DECIMAL(10,2) DEFAULT 0;

    DECLARE str TEXT;
    DECLARE strLen INT DEFAULT 0;
    DECLARE i INT DEFAULT 1;

    DECLARE GRPS TEXT;
    DECLARE GRAPE TEXT;
    DECLARE strGLen INT DEFAULT 0;
    DECLARE Gi INT DEFAULT 1;
    DECLARE icols INT DEFAULT 1;

    DECLARE billnum_local VARCHAR(100);
    DECLARE itemid INT;
    DECLARE itemname VARCHAR(255);
    DECLARE hsn VARCHAR(50);
    DECLARE mfr VARCHAR(50);
    DECLARE batch VARCHAR(50);
    DECLARE exp DATE;
    DECLARE sch VARCHAR(50);
    DECLARE mrp DECIMAL(10,2);
    DECLARE discper DECIMAL(10,2);
    DECLARE rate DECIMAL(10,2);
    DECLARE qty DECIMAL(10,2);
    DECLARE amt DECIMAL(10,2);
    DECLARE cgst_local DECIMAL(10,2);
    DECLARE sgst_local DECIMAL(10,2);
    DECLARE strstkid INT;
    DECLARE Gstr TEXT;

    -- ========================
    -- Disable foreign key checks temporarily
    -- ========================
    SET FOREIGN_KEY_CHECKS = 0;

    -- ========================
    -- Insert into salesreturn_tbl
    -- ========================
    INSERT INTO salesreturn_tbl(
        salesret_billnum, salesret_Taxamt, salesret_cgst, 
        salesret_sgst, salesret_netpay, salesret_crtdby
    ) VALUES (billNo, taxamt, cgst, sgst, netpay, adminid);

    SET billid = LAST_INSERT_ID();

    IF billid > 0 THEN
        -- Clean input
        SET str = TRIM(BOTH '##' FROM returndetails);
        SET strLen = 0;
        SET i = 1;

        -- ========================
        -- Outer loop over 'str'
        -- ========================
        WHILE strLen < LENGTH(str) DO
            SET GRPS = SUBSTRING_INDEX(str, '##', i);
            SET strLen = LENGTH(GRPS);
            SET i = i + 1;

            SET GRAPE = TRIM(BOTH '|' FROM GRPS);
            SET strGLen = 0;
            SET Gi = 1;
            SET icols = 1;

            -- Reset item variables each iteration
            SET billnum_local = NULL;
            SET itemid = NULL;
            SET itemname = NULL;
            SET hsn = NULL;
            SET mfr = NULL;
            SET batch = NULL;
            SET exp = NULL;
            SET sch = NULL;
            SET mrp = NULL;
            SET discper = NULL;
            SET rate = NULL;
            SET qty = NULL;
            SET amt = NULL;
            SET cgst_local = NULL;
            SET sgst_local = NULL;
            SET strstkid = NULL;

            -- ========================
            -- Inner loop over GRAPE columns
            -- ========================
            WHILE strGLen < LENGTH(GRAPE) DO
                SET Gstr = SUBSTRING_INDEX(GRAPE, '|', Gi);
                SET strGLen = LENGTH(Gstr);
                SET Gi = Gi + 1;

                IF icols = 1 THEN
                    SET billnum_local = TRIM(Gstr);
                ELSEIF icols = 2 THEN
                    SET itemid = TRIM(Gstr);
                ELSEIF icols = 3 THEN
                    SET itemname = TRIM(Gstr);
                ELSEIF icols = 4 THEN
                    SET hsn = TRIM(Gstr);
                ELSEIF icols = 5 THEN
                    SET mfr = TRIM(Gstr);
                ELSEIF icols = 6 THEN
                    SET batch = TRIM(Gstr);
                ELSEIF icols = 7 THEN
                    SET exp = TRIM(Gstr);
                ELSEIF icols = 8 THEN
                    SET sch = TRIM(Gstr);
                ELSEIF icols = 9 THEN
                    SET mrp = TRIM(Gstr);
                ELSEIF icols = 10 THEN
                    SET discper = TRIM(Gstr);
                ELSEIF icols = 11 THEN
                    SET rate = TRIM(Gstr);
                ELSEIF icols = 12 THEN
                    SET qty = TRIM(Gstr);
                ELSEIF icols = 13 THEN
                    SET amt = TRIM(Gstr);
                ELSEIF icols = 14 THEN
                    SET cgst_local = TRIM(Gstr);
                ELSEIF icols = 15 THEN
                    SET strstkid = TRIM(Gstr);
                ELSE
                    SET sgst_local = TRIM(Gstr);
                END IF;

                SET icols = icols + 1;
            END WHILE;  -- End inner GRAPE loop

            -- ========================
            -- Insert into salesretitem_tbl
            -- ========================
            INSERT INTO salesretitem_tbl(
                ret_billnum, ret_itemid, ret_item, ret_hsn, ret_mfr, 
                ret_batch, ret_expiry, ret_sch, ret_mrp, ret_discount, 
                ret_rate, ret_qty, ret_amount, ret_cgst, ret_sgst
            ) VALUES (
                billnum_local, itemid, itemname, hsn, mfr,
                batch, exp, sch, mrp, discper,
                rate, qty, amt, cgst_local, sgst_local
            );

            -- ========================
            -- Update loosereturn_tbl
            -- ========================
            UPDATE loosereturn_tbl
            SET loosereturn_qty = loosereturn_qty + qty
            WHERE loosereturn_refer = strstkid AND loosereturn_batch = batch;

            -- Fetch lqty and sqty safely
            SET lqty = (SELECT loosereturn_qty FROM loosereturn_tbl 
                        WHERE loosereturn_refer = strstkid AND loosereturn_batch = batch LIMIT 1);

            SET sqty = (SELECT loosereturn_sqty FROM loosereturn_tbl 
                        WHERE loosereturn_refer = strstkid AND loosereturn_batch = batch LIMIT 1);

            IF lqty <= sqty AND lqty > 0 THEN
                SET minvalue = sqty / lqty;

                UPDATE storestock_pricing
                SET strstk_stock = strstk_stock + qty
                WHERE strstk_id = strstkid AND strstk_item = itemid;

                UPDATE storestock_master
                SET storestock_available = storestock_available + qty
                WHERE storestock_item = itemid;

                UPDATE bills_table
                SET bill_status = 0
                WHERE bill_no = billnum_local;

                UPDATE loosereturn_tbl
                SET loosereturn_sqty = loosereturn_sqty - (lqty * minvalue)
                WHERE loosereturn_refer = strstkid AND loosereturn_batch = batch;
            END IF;

        END WHILE;  -- End outer str loop
    END IF;  -- End billid check

    -- ========================
    -- Re-enable foreign key checks
    -- ========================
    SET FOREIGN_KEY_CHECKS = 1;

    -- ========================
    -- Single SELECT at the end
    -- ========================
    SELECT 
        sa.salesret_id,
        sa.salesret_billnum,
        sa.salesret_Taxamt,
        sa.salesret_cgst,
        sa.salesret_sgst,
        sa.salesret_netpay,
        st.*
    FROM salesreturn_tbl sa
    LEFT JOIN salesretitem_tbl st ON st.ret_billnum = sa.salesret_billnum
    WHERE sa.salesret_billnum = billNo;
    
    SELECT * FROM bills_table b WHERE b.bill_no = billNo; 

END$$

CREATE  PROCEDURE `saveHomedeliveryDatas` (IN `billid` INT, IN `billnumber` VARCHAR(50), IN `storeid` INT, IN `customer` VARCHAR(50), IN `mobile` VARCHAR(50), IN `item` INT, IN `amount` DECIMAL(10,2), IN `adminid` INT)   BEGIN

INSERT INTO homedelivery_tbl(bill_id,bill_no,store_id,customer_name,customer_mob,items,amount,cretaed_by) VALUES(billid,billnumber,storeid,customer,mobile,item,amount,adminid);

END$$

CREATE  PROCEDURE `saveOnlinedeliveryDatas` (IN `oder_id` INT)   BEGIN

UPDATE orders_tbl  SET order_delivery=1,orders_delivered=CURRENT_TIMESTAMP() WHERE order_id=oder_id;


END$$

CREATE  PROCEDURE `saveTheNotices` (IN `notice_id` INT, IN `notice` TEXT, IN `noticeoffer` INT)   BEGIN

UPDATE tbl_notice SET notice_text=notice,notice_offer=noticeoffer WHERE notice_id =notice_id;
 

END$$

CREATE  PROCEDURE `searchProductByName` (IN `search_term` VARCHAR(200))   BEGIN
if search_term!='' then
select x.product_name,x.product_id,x.prodpack_id,x.packing_type,
x.measunit_shortname,x.strstk_mrp,x.strstk_msp,x.stockin_batch,x.strstk_id, x.product_imageurl from (SELECT ( @row_number := @row_number + 1) AS virtual_id,p.product_name,p.product_id,r.prodpack_id,t.packing_type,
m.measunit_shortname,e.strstk_mrp,e.strstk_msp,s.stockin_batch,e.strstk_id,(select g.prodgal_url  from product_gallery g where g.prodgal_prodpack = r.prodpack_id and  g.prodgal_placedat = 1 and g.prodgal_medium = 1 and g.prodgal_publish = 1 and g.prodgal_status = 1 order by g.prodgal_serial asc limit 1) as product_imageurl from products_tbl p join product_packing r on r.prodpack_product = p.product_id join packing_tbl t on t.packing_id = r.prodpack_package join measure_units m on m.measunit_id = r.prodpack_unit  join  stock_inwards s on s.stockin_item = r.prodpack_id join storestock_pricing e on e.strstk_item = r.prodpack_id
       LEFT JOIN brands_tbl b ON p.product_brand = b.brand_id
    LEFT JOIN product_classes pp ON p.product_maincategory = pp.prodclass_id
    LEFT JOIN pharmacologicalcontent_tbl pc ON p.product_pcontent = pc.pharma_id                                                           
WHERE p.product_name like concat(search_term,'%') OR pc.pharma_name LIKE CONCAT('%', search_term, '%') OR
        b.brand_name LIKE CONCAT('%', search_term, '%') OR
        pp.prodclass_name LIKE CONCAT('%', search_term, '%') and p.product_status = 1 and p.product_online = 1 and p.product_publish=1 and s.stockin_expiry >= CURRENT_DATE() and (e.strstk_stock-e.strstk_reserved) > 0 order by s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc) as x group by x.product_id ;
END IF;
END$$

CREATE  PROCEDURE `searchStockPricing` (IN `storeid` INT, IN `prodclass` INT)   BEGIN
	IF storeid > 0 THEN
		SET @storecondn = CONCAT( ' AND x.strstk_store = ', storeid );
    	SET @itemcount = CONCAT( ', (SELECT COUNT(z.strstk_item) FROM storestock_pricing z WHERE z.strstk_item = x.strstk_item AND z.strstk_stock > 0 AND z.strstk_store = ', storeid, ') AS items' );
    ELSE
    	SET @storecondn = '';
        SET @itemcount = CONCAT( ', (SELECT COUNT(z.strstk_item) FROM storestock_pricing z WHERE z.strstk_item = x.strstk_item AND z.strstk_stock > 0 ) AS items' );
    END IF;
    
    IF prodclass > 0 THEN
		SET @prodcondn = CONCAT( ' AND c.prodclass_id = ', prodclass );
    ELSE
    	SET @prodcondn = '';
    END IF;
	
    SET @query1 = 'SELECT DISTINCT p.product_id, p.product_name, p.product_display, p.product_maincategory, c.prodclass_name, 
    x.strstk_item, 1 AS storecount';
    SET @query2 = ', p.product_sale, p.product_online, p.product_featured, 0 AS priced  
    FROM storestock_pricing x 
    LEFT JOIN products_tbl p ON p.product_id = x.strstk_product 
    LEFT JOIN product_classes c ON c.prodclass_id = p.product_maincategory
    WHERE x.strstk_stock > 0 AND x.strstk_status = 1 ';
    
    SET @query3 = ' UNION SELECT 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 
    ORDER BY strstk_item ' ;
    SET @query = CONCAT(@query1, @itemcount, @query2, @storecondn, @prodcondn, @query3);
    PREPARE statement FROM @query;
    EXECUTE statement;
    
    SELECT prodclass_id, prodclass_name
    FROM product_classes x WHERE prodclass_parent = 0 AND prodclass_status = 1 
    ORDER BY prodclass_serial;
    
    SELECT store_id, store_name 
    FROM stores_tbl WHERE store_status = 1 
    ORDER BY store_name;
END$$

CREATE  PROCEDURE `search_products` (IN `search_term` VARCHAR(255))   BEGIN
  SELECT 
    p.*, 
    b.brand_name,
    pp.prodclass_name,
    pc.pharma_name,m.manuf_name
  FROM products_tbl p
  LEFT JOIN brands_tbl b 
    ON p.product_brand = b.brand_id
  LEFT JOIN product_classes pp
    ON p.product_maincategory = pp.prodclass_id
  LEFT JOIN pharmacologicalcontent_tbl pc 
    ON p.product_pcontent = pc.pharma_id
    LEFT JOIN manufacturers_tbl m on m.manuf_id=p.product_manufacturer
  WHERE p.product_name LIKE CONCAT('%', search_term, '%')
     OR p.product_display LIKE CONCAT('%', search_term, '%')
     OR pc.pharma_name LIKE CONCAT('%', search_term, '%')
     OR b.brand_name LIKE CONCAT('%', search_term, '%')
     OR pp.prodclass_name LIKE CONCAT('%', search_term, '%');
       END$$

CREATE  PROCEDURE `staffNameListOfStore` (IN `storeid` INT)   BEGIN
IF storeid>1 THEN
SELECT s.staff_id,s.staff_name,s.staff_branch,u.user_id,u.user_checkid FROM staff_tbl s
LEFT JOIN users_tbl u ON u.user_staffid=s.staff_id
WHERE storeid=s.staff_branch;
ELSE
 SELECT s.staff_id,s.staff_name,s.staff_branch,u.user_id,u.user_checkid FROM staff_tbl s
LEFT JOIN users_tbl u ON u.user_staffid=s.staff_id;
END IF;
END$$

CREATE  PROCEDURE `startQuickOrderwithPrescription` (IN `custmrid` INT, IN `orderno` VARCHAR(20))   BEGIN
DECLARE ordid ,delvid INT DEFAULT 0;

SELECT d.delivery_id into delvid FROM delivery_address d WHERE d.delivery_user=custmrid AND  d.delivery_status=1 AND d.delivery_active=1;
 /* insert into order table Table */
  INSERT INTO orders_tbl(order_customer,order_deliverId,order_orderid,order_prescription,order_quick,order_updby, order_updon) VALUES(custmrid,delvid,orderno,1,1,1,CURRENT_TIMESTAMP);
     SET ordid = LAST_INSERT_ID();    
    SELECT ordid, c.customer_phone as phone FROM customers_tbl c WHERE c.customer_id=custmrid;
END$$

CREATE  PROCEDURE `SupplierWiseItemPurc` (IN `storeid` INT, IN `fromdate` DATE, IN `todate` DATE)   BEGIN
SELECT i.invoice_id, i.invoice_number, i.invoice_vendertype, i.invoice_vendor, i.invoice_vendorgst, i.invoice_delstore, s.store_name, i.invoice_delgst, i.invoice_dated, i.invoice_amount, i.invoice_cgst, i.invoice_sgst, id.invdet_porder, po.purchord_ref, 'Registered' AS gst_type,pp.prodpack_hsn,pp.prodpack_taxgroup, id.invdet_item,fnGetProductFromPack(id.invdet_item, 1) AS item, p.product_manufacturer, m.manuf_name, id.invdet_batch, id.invdet_expiry, id.invdet_qty, id.invdet_mrp, id.invdet_ptr, id.invdet_crtdby, u.user_staffname, 'Non-DC Purchase' as purchase_type FROM invoices_tbl i LEFT JOIN invoice_details id ON id.invdet_invoice=i.invoice_id LEFT JOIN stores_tbl s ON s.store_id= i.invoice_delstore LEFT JOIN purchase_orders po ON po.purchord_id=id.invdet_porder LEFT JOIN product_packing pp ON pp.prodpack_id = id.invdet_item LEFT JOIN products_tbl p ON p.product_id = pp.prodpack_product LEFT JOIN manufacturers_tbl m ON m.manuf_id=p.product_manufacturer LEFT JOIN users_tbl u ON u.user_id=i.invoice_crtdby
WHERE i.invoice_delstore=storeid AND i.invoice_dated BETWEEN fromdate AND todate;
END$$

CREATE  PROCEDURE `testsubdis` (IN `distrbs` VARCHAR(255))   BEGIN
	DECLARE distid INT DEFAULT 0;
    DECLARE front TEXT DEFAULT '';
    DECLARE frontlen INT DEFAULT 0;
    DECLARE tempVal TEXT DEFAULT '';
    
        /* add as sub-distributor if not empty */
        subiterator:
        LOOP
        	IF LENGTH(TRIM(distrbs)) = 0 OR distrbs IS NULL THEN
            	LEAVE subiterator;
            END IF;
            SET front = SUBSTRING_INDEX(distrbs, ',', 1);
            SET frontlen = LENGTH(front);
            SET tempVal = TRIM(front);
            INSERT INTO subdistributors_tbl ( 
                subdistri_distributor, subdistri_parent, subdistri_crtdby ) 
            VALUES (105, tempVal, 19);
            SET distrbs = INSERT(distrbs, 1, frontlen + 1, '');
        END LOOP;
       
END$$

CREATE  PROCEDURE `truncatebulktables` ()   BEGIN
truncate TABLE addoninvoice;
TRUNCATE TABLE brands_tbl;
truncate TABLE intends_tbl;
truncate TABLE intend_allocations;
truncate TABLE intend_allocation_items;
truncate TABLE intend_details;
truncate TABLE invoices_tbl;
truncate TABLE invoice_details;
truncate TABLE invoice_files;
truncate TABLE purchasereturnfiles_tbl;
truncate TABLE purchasereturn_details;
truncate TABLE purchasereturn_tbl;
truncate TABLE purchase_details;
truncate TABLE purchase_orders;
truncate TABLE stocktransfer_details;
truncate TABLE stock_inwards;
truncate TABLE stock_master;
truncate TABLE stock_transfers;
truncate TABLE storestock_master;
truncate TABLE storestock_pricing;
truncate TABLE stockists_tbl;
truncate TABLE stockist_products;
truncate TABLE stockin_expenses;
truncate TABLE transferpack_items;
truncate TABLE transfer_packets;
truncate TABLE salesreturn_tbl;
truncate TABLE salesretitem_tbl;
truncate TABLE bill_items;
truncate TABLE bills_table;
truncate TABLE bills_setup;
truncate TABLE billstock_tbl;
truncate TABLE distributor_products;
truncate TABLE distributor_manufacturers;
truncate TABLE distributors_tbl;
truncate TABLE dealer_products;
truncate TABLE dealers_tbl;
truncate TABLE stockin_expenses;
truncate TABLE vendor_supplies;
truncate TABLE product_packing;
truncate TABLE product_ingredients;
truncate TABLE product_gallery;
            SET FOREIGN_KEY_CHECKS = 1;
END$$

CREATE  PROCEDURE `updateAdvertisments` (IN `advtid` INT, IN `adtype` INT, IN `adtitle` VARCHAR(255), IN `adowner` VARCHAR(255), IN `admaincat` INT, IN `adsubcat` INT, IN `adcat` INT, IN `adprdct` INT, IN `adimage` VARCHAR(255), IN `adurl` TEXT, IN `fromdate` DATE, IN `todate` DATE, IN `adstatus` INT, IN `adpublish` INT, IN `adoffers` INT, IN `adnote` TEXT, IN `homepagestat` INT, IN `maincatstat` INT, IN `subcatstat` INT, IN `catstat` INT, IN `adminid` INT, IN `adbrand` INT)   BEGIN
	
    UPDATE advertisements_tbl SET advt_type=adtype,advt_title=adtitle,advt_owner=adowner,advt_brand=adbrand,advt_datefrom=fromdate,advt_dateto=todate,advt_products=adprdct,advt_maincategories=admaincat,advt_subcategories=adsubcat,advt_catgory=adcat,advt_content=adnote,advt_image=adimage,advt_linkedurl=adurl,advt_publish=adpublish,advt_status=adstatus,advt_offer=adoffers,
   advt_hompagestatus=homepagestat,advt_maincatstatus=maincatstat,advt_subcatstatus=subcatstat,advt_catstatus=catstat, advt_uptdby=adminid,advt_updton=CURRENT_TIMESTAMP()  WHERE advt_id=advtid;
END$$

CREATE  PROCEDURE `updateBrand` (IN `brandid` INT, IN `brand` VARCHAR(100), IN `logo` VARCHAR(255), IN `owner` TEXT, IN `remarks` TEXT, IN `bstatus` INT, IN `publish` INT, IN `adminid` INT)   BEGIN
	IF TRIM(logo) = '' THEN
    	UPDATE brands_tbl 
    	SET brand_name = brand,  
    	brand_remarks = remarks, brand_status = bstatus, 
    	brand_publish = publish, brand_updby = adminid 
    	WHERE brand_id = brandid;
    ELSE
		UPDATE brands_tbl 
    	SET brand_name = brand, brand_logo = logo, 
    	brand_remarks = remarks, brand_status = bstatus, 
    	brand_publish = publish, brand_updby = adminid 
    	WHERE brand_id = brandid;
   	END IF;
  
DELETE FROM `brand_manufacturer_tbl` WHERE `brnd_id`=brandid;

INSERT IGNORE INTO brand_manufacturer_tbl (brnd_id, brndmanu_id)
SELECT brandid, b.manuf_id
FROM manufacturers_tbl b
WHERE FIND_IN_SET(b.manuf_id, owner);
END$$

CREATE  PROCEDURE `updateBrandDuplicate` (IN `brandName` VARCHAR(225), IN `setval` INT)   BEGIN
UPDATE products_tbl p
JOIN brands_tbl b
    ON p.product_brand = b.brand_id
SET p.product_brand = setval
WHERE b.brand_name = brandName
  AND b.brand_id != setval;

UPDATE brands_tbl b SET b.brand_status=0 WHERE b.brand_name = brandName
  AND b.brand_id != setval;

SELECT MIN(brand_id) AS brand_id, brand_name FROM brands_tbl WHERE brand_status = 1 GROUP BY brand_name HAVING COUNT(*) > 1 LIMIT 1;

END$$

CREATE  PROCEDURE `updateBrandDuplicatebyLimit` ()   BEGIN
INSERT IGNORE INTO brand_manufacturer_tbl (brnd_id, brndmanu_id)
SELECT brand_id, brand_owner
FROM brands_tbl
WHERE brand_duplicate = 0
AND brand_name IN (
    SELECT brand_name
    FROM (
        SELECT brand_name
        FROM brands_tbl
        WHERE brand_duplicate = 0
        GROUP BY brand_name
        HAVING COUNT(*) = 1
        ORDER BY brand_name
        LIMIT 10
    ) t
);

UPDATE brands_tbl
SET brand_duplicate = 1
WHERE brand_duplicate = 0
AND brand_name IN (
    SELECT brand_name
    FROM (
        SELECT brand_name
        FROM brands_tbl
        WHERE brand_duplicate = 0
        GROUP BY brand_name
        HAVING COUNT(*) = 1
        ORDER BY brand_name
        LIMIT 10
    ) t
);
END$$

CREATE  PROCEDURE `updateBrandManufactureDuplicate` (IN `brandName` VARCHAR(225), IN `setval` INT)   BEGIN
UPDATE products_tbl p
JOIN brands_tbl b
    ON p.product_brand = b.brand_id
SET p.product_brand = setval
WHERE b.brand_name = brandName
  AND b.brand_id != setval;

UPDATE brands_tbl b SET b.brand_status=0 WHERE b.brand_name = brandName
  AND b.brand_id != setval;
  
  UPDATE brands_tbl b SET b.brand_duplicate=1 WHERE b.brand_name = brandName;
  
INSERT IGNORE INTO brand_manufacturer_tbl (brnd_id, brndmanu_id)
SELECT setval, b.brand_owner
FROM brands_tbl b
WHERE b.brand_name = brandName;

SELECT MIN(brand_id) AS brand_id, brand_name FROM brands_tbl WHERE  brand_duplicate=0 GROUP BY brand_name HAVING COUNT(*) > 1 LIMIT 1;

END$$

CREATE  PROCEDURE `updateBrandofEntryTable` ()   BEGIN
UPDATE products_entry_tbl t1 JOIN products_tbl t2 ON t1.product_id = t2.product_id SET t1.product_brand = t2.product_brand WHERE t1.product_brand <> t2.product_brand AND t1.product_brand!=0 AND t2.product_brand!=0;

SELECT t1.product_id,t1.product_brand,t1.product_name FROM products_entry_tbl t1 WHERE NOT EXISTS ( SELECT 1 FROM products_tbl t2 WHERE t1.product_id = t2.product_id AND t1.product_brand = t2.product_brand AND t2.product_brand!=0 ) and t1.product_brand!=0;
END$$

CREATE  PROCEDURE `updateCourier` (IN `courid` INT, IN `cname` VARCHAR(100), IN `ctype` INT, IN `staffid` INT, IN `mobile` VARCHAR(20), IN `vehicle` VARCHAR(20), IN `regno` VARCHAR(20), IN `contact` VARCHAR(50), IN `address` VARCHAR(255), IN `phones` VARCHAR(50), IN `whatsapp` VARCHAR(20), IN `email` VARCHAR(100), IN `url` VARCHAR(100), IN `gst` VARCHAR(30), IN `tin` VARCHAR(30), IN `notes` TEXT, IN `rates` LONGTEXT, IN `areas` TEXT, IN `collect` TEXT, IN `status` INT, IN `adminid` INT)   BEGIN
	DECLARE success INT DEFAULT 0;

	IF( SELECT COUNT(*) FROM couriers_tbl x 
       	WHERE (x.courier_name = trim(cname) OR x.courier_mobile = trim(mobile)) AND x.courier_id <> courid ) = 0 THEN
    		UPDATE couriers_tbl 
            SET courier_type = ctype, courier_staffid = staffid, courier_name = cname, courier_mobile = mobile, courier_vehicle = vehicle, courier_vehregn = regno, courier_contact = contact, courier_address = address, courier_gst = gst, courier_tin = tin, courier_phones = phones, courier_whatsapp = whatsapp, courier_email = email, courier_url = url, courier_rates = rates, courier_areas = areas, courier_collect = collect, courier_notes = notes, courier_status = status, courier_updby = adminid 
            WHERE courier_id = courid;
            SET success = 1;
	ELSE
    	UPDATE couriers_tbl 
            SET courier_type = ctype, courier_staffid = staffid, courier_vehicle = vehicle, courier_vehregn = regno, courier_contact = contact, courier_address = address, courier_gst = gst, courier_tin = tin, courier_phones = phones, courier_whatsapp = whatsapp, courier_email = email, courier_url = url, courier_rates = rates, courier_areas = areas, courier_collect = collect, courier_notes = notes, courier_status = status, courier_updby = adminid 
            WHERE courier_id = courid;
            SET success = 2;
   	END IF;
    
    SELECT success;
END$$

CREATE  PROCEDURE `updateCourierMovement` (IN `packids` TEXT, IN `flag` INT, IN `courier` INT, IN `notes` TEXT, IN `trnsdata` TEXT)   BEGIN
	DECLARE trackid VARCHAR(20) DEFAULT '';
    DECLARE front, TempValue, alltracks, packets TEXT DEFAULT NULL;
   	DECLARE frontlen INT DEFAULT NULL;
    DECLARE gdnstore INT DEFAULT 0;
	IF flag = 1 THEN   /* Packet collected form the source */
    SET @text := TRIM(BOTH '##' FROM trnsdata);
  		SET @strLen := 0;
  		SET @i := 1;
  		WHILE @strLen < LENGTH(@text) DO
            SET @str := SUBSTRING_INDEX(@text, '##', @i);
            SET @strLen := LENGTH(@str);
            SET @i := @i + 1;
            SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
            SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
            SET @strGLen := 0;
            SET @Gi := 1;
            SET @icols := 1;
    		WHILE @strGLen < LENGTH(@GRAPE) DO
                SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
                SET @strGLen := LENGTH(@Gstr);
                SET @Gi := @Gi + 1;
                IF @icols = 1 THEN
                    SET @strids := SUBSTRING_INDEX(@Gstr, '|', -1); /* store_stock_pricing_id */
                ELSEIF @icols = 2 THEN
                    SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 3 THEN
                    SET @storeid := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSE
                    SET @trnsitems := SUBSTRING_INDEX(@Gstr, '|', -1);
                END IF;
                SET @icols := @icols + 1;
      		END WHILE;
            #update storestock_pricing and storestock_master
            	#update stock at source store
        	UPDATE storestock_pricing
        	SET strstk_transfer = (strstk_transfer + @qty), strstk_reserved = (strstk_reserved - @qty),
            strstk_stock = (strstk_stock - @qty)
        	WHERE strstk_id = @strids;
               #update stock at source store in stockmaster
          UPDATE storestock_master SET storestock_available=(storestock_available- @qty) ,storestock_reserved=(storestock_reserved - @qty) WHERE storestock_store =@storeid AND storestock_item =@trnsitems;
            END WHILE;
    	SET packets = packids;
    	iterator:
			LOOP
				IF LENGTH(TRIM(packids)) = 0 OR packids IS NULL THEN
					LEAVE iterator;
				END IF;
				SET front = SUBSTRING_INDEX(packids,',',1);
				SET frontlen = LENGTH(front);
				SET TempValue = TRIM(front);
    			SELECT CONCAT(sf.store_code, LEFT(MD5(RAND()), 8), st.store_code) INTO trackid
    			FROM transfer_packets p
    			LEFT JOIN stores_tbl sf ON sf.store_id = p.transpack_from
    			LEFT JOIN stores_tbl st ON st.store_id = p.transpack_to
    			WHERE p.transpack_id = TempValue;
    			SELECT transpack_from INTO gdnstore  FROM transfer_packets WHERE  transpack_id = TempValue;
    			UPDATE transfer_packets
        		SET transpack_status = 5, transpack_collectby = courier, transpack_collecton=CURRENT_TIMESTAMP(), transpack_notes = CONCAT(transpack_notes, '<COURNOTES>', notes, '</COURNOTES>'), transpack_trackid = trackid,transpack_gdn=fnCreateGDNnumber(gdnstore)
        		WHERE transpack_id = TempValue;
        		
                SET packids = INSERT(packids, 1, frontlen + 1, '');
                #SET alltracks = CONCAT(alltracks, ',', trackid);
			END LOOP;
        UPDATE transferpack_items
        SET transferpack_status = 5
        WHERE FIND_IN_SET(transferpack_packet, packets); /*IN(packets);*/
        #SELECT alltracks as TRACK;
        SELECT GROUP_CONCAT(tp.transpack_trackid) AS TRACK
        FROM transfer_packets tp WHERE FIND_IN_SET(tp.transpack_id, packets);
    ELSEIF flag = 2 THEN
    	UPDATE transfer_packets
        SET transpack_status = 10, transpack_deliverby = courier, transpack_deliveron = CURRENT_TIMESTAMP(), transpack_notes = CONCAT(transpack_notes, '<DELNOTES>', notes, '</DELNOTES>')
        WHERE FIND_IN_SET(transpack_id, packids);
        UPDATE transferpack_items
        SET transferpack_status = 10
        WHERE FIND_IN_SET(transferpack_packet, packids);
    END IF;
END$$

CREATE  PROCEDURE `updateDealer` (IN `dealerid` INT, IN `dname` VARCHAR(200), IN `address` VARCHAR(255), IN `phones` VARCHAR(200), IN `email` VARCHAR(50), IN `website` VARCHAR(50), IN `contact` VARCHAR(200), IN `contactno` VARCHAR(200), IN `conemail` VARCHAR(50), IN `concell` VARCHAR(50), IN `whatsapp` VARCHAR(50), IN `contactat` VARCHAR(255), IN `regn` VARCHAR(255), IN `gstnum` VARCHAR(50), IN `tin` VARCHAR(50), IN `remarks` TEXT, IN `mstatus` INT, IN `adminid` INT, IN `dealers` VARCHAR(255), IN `products` VARCHAR(255))   BEGIN
    DECLARE front TEXT DEFAULT '';
    DECLARE frontlen INT DEFAULT 0;
    DECLARE tempVal TEXT DEFAULT '';
    
	UPDATE dealers_tbl 
    SET dealer_name = dname, dealer_address = address, dealer_phones = phones, dealer_email = email, dealer_website = website, dealer_contact = contact, dealer_contactno = contactno, dealer_contactemail = conemail, dealer_contactcell = concell, dealer_whatsapp = whatsapp, dealer_contactat = contactat, dealer_regn = regn, dealer_GST = gstnum, dealer_TIN = tin, dealer_remarks = remarks, dealer_status = mstatus, dealer_updby = adminid
	WHERE dealer_id = dealerid;
    
    IF dealerid > 0 THEN
        /* add as sub-dealer if not empty */
        subiterator:
        LOOP
        	IF LENGTH(TRIM(dealers)) = 0 OR dealers IS NULL THEN
            	LEAVE subiterator;
            END IF;
            SET front = SUBSTRING_INDEX(dealers, ',', 1);
            SET frontlen = LENGTH(front);
            SET tempVal = TRIM(front);
            INSERT INTO subdealers_tbl ( 
               	subdealer_dealer, subdealer_parent, subdealer_crtdby ) 
            VALUES (dealerid, tempVal, adminid)
			ON DUPLICATE KEY UPDATE subdealer_status = 1, subdealer_updby = adminid;
            SET dealers = INSERT(dealers, 1, frontlen + 1, '');
        END LOOP;
        
        /* add products if not empty */
        proditerator:
        LOOP
        	IF LENGTH(TRIM(products)) = 0 OR products IS NULL THEN
            	LEAVE proditerator;
            END IF;
            SET front = SUBSTRING_INDEX(products, ',', 1);
            SET frontlen = LENGTH(front);
            SET tempVal = TRIM(front);
            INSERT INTO dealer_products ( 
                dealerprod_dealer, dealerprod_product, dealerprod_crtdby ) 
            VALUES (dealerid, tempVal, adminid)
			ON DUPLICATE KEY UPDATE dealerprod_status = 1, dealerprod_updby = adminid;
            SET products = INSERT(products, 1, frontlen + 1, '');
        END LOOP;
        
    END IF;
END$$

CREATE  PROCEDURE `updateDistributor` (IN `distrid` INT, IN `dname` VARCHAR(200), IN `address` VARCHAR(255), IN `phones` VARCHAR(200), IN `email` VARCHAR(200), IN `website` VARCHAR(50), IN `contact` VARCHAR(200), IN `contactno` VARCHAR(200), IN `conemail` VARCHAR(50), IN `concell` VARCHAR(50), IN `whatsapp` VARCHAR(50), IN `contactat` VARCHAR(255), IN `regn` VARCHAR(255), IN `gstnum` VARCHAR(50), IN `tin` VARCHAR(50), IN `remarks` TEXT, IN `mstatus` INT, IN `adminid` INT, IN `manufs` VARCHAR(255), IN `distrbs` VARCHAR(255), IN `products` VARCHAR(255))   BEGIN
    DECLARE front TEXT DEFAULT '';
    DECLARE frontlen INT DEFAULT 0;
    DECLARE tempVal TEXT DEFAULT '';
    
	UPDATE distributors_tbl  SET
    distri_name = dname, distri_address = address, distri_phones = phones, distri_email = email, distri_website = website, distri_contact = contact, distri_contactno = contactno, distri_contactemail = conemail, distri_contactcell = concell, distri_whatsapp = whatsapp, distri_contactat = contactat, distri_regn = regn, distri_GST = gstnum, distri_TIN = tin, distri_remarks = remarks, distri_status = mstatus, distri_updby = adminid
    WHERE distri_id = distrid;
    
    IF distrid > 0 THEN
    	/* add manufacturers if given */
        iterator:
        LOOP
        	IF LENGTH(TRIM(manufs)) = 0 OR manufs IS NULL THEN
            	LEAVE iterator;
            END IF;
            SET front = SUBSTRING_INDEX(manufs, ',', 1);
            SET frontlen = LENGTH(front);
            SET tempVal = TRIM(front);
            INSERT INTO distributor_manufacturers( 			 						distrimanu_distributor, distrimanu_company, distrimanu_crtdby) 
            VALUES (distrid, tempVal, adminid)
            ON DUPLICATE KEY UPDATE distrimanu_status = 1, distrimanu_updby = adminid;
            SET manufs = INSERT(manufs, 1, frontlen + 1, '');
        END LOOP;
        
        /* add as sub-distributor if not empty */
        subiterator:
        LOOP
        	IF LENGTH(TRIM(distrbs)) = 0 OR distrbs IS NULL THEN
            	LEAVE subiterator;
            END IF;
            SET front = SUBSTRING_INDEX(distrbs, ',', 1);
            SET frontlen = LENGTH(front);
            SET tempVal = TRIM(front);
            INSERT INTO subdistributors_tbl ( 
                subdistri_distributor, subdistri_parent, subdistri_crtdby ) 
            VALUES (distrid, tempVal, adminid)
            ON DUPLICATE KEY UPDATE subdistri_status = 1, subdistri_updby = adminid;
            SET distrbs = INSERT(distrbs, 1, frontlen + 1, '');
        END LOOP;
        
        /* add products if not empty */
        proditerator:
        LOOP
        	IF LENGTH(TRIM(products)) = 0 OR products IS NULL THEN
            	LEAVE proditerator;
            END IF;
            SET front = SUBSTRING_INDEX(products, ',', 1);
            SET frontlen = LENGTH(front);
            SET tempVal = TRIM(front);
            INSERT INTO distributor_products ( 
                distriprod_distributor, distriprod_product, distriprod_crtdby ) 
            VALUES (distrid, tempVal, adminid)
            ON DUPLICATE KEY UPDATE distriprod_status = 1, distriprod_updby = adminid;
            SET products = INSERT(products, 1, frontlen + 1, '');
        END LOOP;
        
    END IF;
END$$

CREATE  PROCEDURE `updateDoctor` (IN `docid` INT, IN `dtype` INT, IN `dname` VARCHAR(100), IN `dregno` VARCHAR(50), IN `dmobile` VARCHAR(50), IN `demail` VARCHAR(50), IN `ddegrees` VARCHAR(255), IN `dhospital` VARCHAR(255), IN `dremarks` VARCHAR(255), IN `dphoto` VARCHAR(100), IN `dsignature` VARCHAR(100), IN `ddatefrom` DATE, IN `davailfrom` TIME, IN `ddateto` DATE, IN `davailto` TIME, IN `docstatus` INT, IN `adminid` INT)   BEGIN
UPDATE doctors_tbl SET doctor_type=dtype, doctor_name=dname, doctor_regno=dregno, doctor_mobile=dmobile, doctor_email=demail, doctor_degrees = ddegrees, doctor_hospital = dhospital, doctor_remarks = dremarks, doctor_photo=dphoto, doctor_signature=	dsignature, doctor_datefrom=ddatefrom, doctor_availfrom=davailfrom, doctor_dateto=ddateto, doctor_availto=davailto, doctor_status=docstatus, doctor_updby=adminid, doctor_updon=CURRENT_TIMESTAMP() WHERE doctor_id = docid;

  
END$$

CREATE  PROCEDURE `updateDrugClassification` (IN `drgclsid` INT, IN `drgclass` VARCHAR(150), IN `parent` INT, IN `uses` TEXT, IN `warning` TEXT, IN `precautions` TEXT, IN `howto` TEXT, IN `dosage` TEXT, IN `misdose` TEXT, IN `overdose` TEXT, IN `avoids` TEXT, IN `sideffects` TEXT, IN `interactions` TEXT, IN `remarks` TEXT, IN `dstatus` INT, IN `adminid` INT)   BEGIN
	DECLARE isStatus INT DEFAULT 1;
    DECLARE pcount INT DEFAULT 0;
    
    IF dstatus = 0 THEN
    	SELECT COUNT(drugclass_id) INTO pcount 
        FROM drug_classifications k 
        WHERE k.drugclass_parent = drgclsid;
        IF pcount = 0 THEN
        	SET isStatus = 0;
        END IF;
    END IF;
    
	UPDATE drug_classifications SET
    drugclass_name = drgclass, drugclass_parent = parent, drugclass_details = remarks, drugclass_uses = uses, drugclass_warnings = warning, drugclass_precautions = precautions, drugclass_procedure = howto, drugclass_dosage = dosage, drugclass_missdose = misdose, drugclass_overdose = overdose, drugclass_avoids = avoids, drugclass_sideffects = sideffects, drugclass_interactions = interactions, drugclass_status = isStatus, drugclass_updby = adminid 
    WHERE drugclass_id = drgclsid;
    
    CALL reworkDrugSequence(drgclsid);
END$$

CREATE  PROCEDURE `updateGalleryItem` (IN `galid` INT, IN `placedat` INT, IN `url` VARCHAR(100), IN `medm` INT, IN `heading` VARCHAR(255), IN `title` VARCHAR(255), IN `alt` VARCHAR(255), IN `descr` VARCHAR(255), IN `serial` INT, IN `publish` INT, IN `gstatus` INT, IN `adminid` INT)   BEGIN
	update product_gallery set prodgal_url = url, prodgal_placedat = placedat, prodgal_medium = medm, prodgal_heading = heading, prodgal_descr = descr, prodgal_title = title, prodgal_alt = alt, prodgal_serial = serial, prodgal_publish = publish, prodgal_status = gstatus, prodgal_updby = adminid WHERE prodgal_id = galid;
END$$

CREATE  PROCEDURE `updateGallerySerial` (IN `series` VARCHAR(255))   BEGIN
	DECLARE _next TEXT DEFAULT NULL;
	DECLARE _nextlen INT DEFAULT NULL;
	DECLARE _value TEXT DEFAULT NULL;
    DECLARE cntr INT DEFAULT 1;
    
    iterator:
	LOOP
    	IF CHAR_LENGTH(TRIM(series)) = 0 OR series IS NULL THEN
    		LEAVE iterator;
  		END IF;
        SET _next = SUBSTRING_INDEX(series, ',', 1);
        SET _nextlen = CHAR_LENGTH(_next);
        SET _value = TRIM(_next);
        UPDATE product_gallery SET prodgal_serial = cntr 
        WHERE prodgal_id = _value;
        SET cntr = cntr + 1;
        SET series = INSERT(series, 1, _nextlen + 1, '');
    END LOOP;
END$$

CREATE  PROCEDURE `updateGenericMedicine` (IN `medid` INT, IN `medicine` VARCHAR(255), IN `uses` TEXT, IN `working` TEXT, IN `sideffects` TEXT, IN `notes` TEXT, IN `mstatus` INT, IN `adminid` INT)   BEGIN
	IF TRIM(medicine) <> '' THEN
    	UPDATE generic_medicines 
        SET genmed_name = medicine, genmed_uses = uses, genmed_working = working, genmed_sideffects = sideffects, genmed_remarks = notes, genmed_status = mstatus, genmed_updby = adminid 
        WHERE genmed_id = medid;
    END IF;
END$$

CREATE  PROCEDURE `updateHomeDelioveryData` (IN `iconval` INT, IN `billid` INT)   BEGIN
IF iconval=1 THEN
UPDATE homedelivery_tbl t SET t.payment_status=1 where t.bill_id =billid;

ELSEIF iconval=2 THEN
UPDATE homedelivery_tbl t SET t.status=1 where t.bill_id =billid ;

END IF ;
END$$

CREATE  PROCEDURE `updateIngredient` (IN `ingrid` INT, IN `ingred` VARCHAR(200), IN `itype` INT, IN `formula` VARCHAR(100), IN `bankid` VARCHAR(20), IN `atccode` VARCHAR(100), IN `isactive` INT, IN `drclass` VARCHAR(100), IN `notes` TEXT, IN `istatus` INT, IN `admin` INT)   BEGIN
	UPDATE ingredients_tbl SET
    ingred_name = ingred, ingred_type = itype, ingred_formula = formula, ingred_drugbankid = bankid, ingred_codes = atccode, ingred_isactive = isactive, ingred_drugclasses = drclass, ingred_notes = notes, ingred_status = istatus, ingred_updby = admin 
    WHERE ingred_id = ingrid;
END$$

CREATE  PROCEDURE `updateInvoice` (IN `invid` INT, IN `invno` VARCHAR(50), IN `invdated` DATE, IN `ventype` INT, IN `venid` INT, IN `total` DECIMAL(10,2), IN `cst` DECIMAL(8,2), IN `gst` DECIMAL(8,2), IN `invdetails` TEXT, IN `notes` TEXT, IN `adminid` INT)   BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
    	ROLLBACK;
    END; 
    
    START TRANSACTION;
	UPDATE invoices_tbl SET invoice_number = invno, invoice_dated = invdated, invoice_vendertype = ventype, invoice_vendor = venid, invoice_amount = total, invoice_cgst = cst, invoice_sgst = gst, invoice_notes = notes, invoice_updby = adminid WHERE invoice_id = invid;

	DELETE FROM invoice_details WHERE invdet_invoice = invid;

	SET @text := TRIM(BOTH '##' FROM invdetails);
	SET @strLen := 0;
	SET @i := 1;
    
	WHILE @strLen < LENGTH(@text) DO
		SET @str := SUBSTRING_INDEX(@text, '##', @i);
		SET @strLen := LENGTH(@str);
		SET @i := @i + 1;
		SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
		SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
		SET @strGLen := 0;
		SET @Gi := 1;
		SET @icols := 1;

		WHILE @strGLen < LENGTH(@GRAPE) DO
			SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
			SET @strGLen := LENGTH(@Gstr);
			SET @Gi := @Gi + 1;
			IF @icols = 1 THEN
				SET @pord := SUBSTRING_INDEX(@Gstr, '|', -1);
			ELSEIF @icols = 2 THEN
				SET @item := SUBSTRING_INDEX(@Gstr, '|', -1);
			ELSEIF @icols = 3 THEN
				SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
			ELSEIF @icols = 4 THEN
				SET @price := SUBSTRING_INDEX(@Gstr, '|', -1);
			ELSEIF @icols = 5 THEN
               	SET @cstpc := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 6 THEN
               	SET @cst := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 7 THEN
               	SET @sstpc := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 8 THEN
               	SET @sst := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 9 THEN
               	SET @delat := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 10 THEN    
              	SET @mrp := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 11 THEN    
               	SET @free := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 12 THEN    
               	SET @hsn := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 13 THEN    
               	SET @ptr := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 14 THEN    
              	SET @taxamt := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 15 THEN    
               	SET @discpc := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 16 THEN    
               	SET @disct := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 17 THEN    
               	SET @batch := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 18 THEN 
               	SET @expiry := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSE
               	SET @schdisc := SUBSTRING_INDEX(@Gstr, '|', -1);
            END IF;
			SET @icols := @icols + 1;
		END WHILE;
		INSERT INTO invoice_details( invdet_invoice, invdet_porder, invdet_item, invdet_qty, invdet_price, invdet_cstpc, invdet_cst, invdet_sstpc, invdet_sst, invdet_delivered, invdet_mrp, invdet_free,invdet_schdisc, invdet_hsn, invdet_ptr, invdet_taxamt, invdet_discpc, invdet_discount, invdet_batch, invdet_expiry ) 
        VALUES( invid, @pord, @item, @qty, @price, @cstpc, @cst, @sstpc, @sst, @delat, @mrp, @free,@schdisc, @hsn, @ptr, @taxamt, @discpc, @disct, @batch, @expiry );
	END WHILE;
 	COMMIT;
END$$

CREATE  PROCEDURE `updateInvoiceItem` (IN `invdetid` INT, IN `invitem` INT, IN `qty` INT, IN `price` DECIMAL(9,2), IN `schdisc` DECIMAL(5,2), IN `cstpc` DECIMAL(5,2), IN `cst` DECIMAL(8,2), IN `sstpc` DECIMAL(5,2), IN `sst` DECIMAL(8,2), IN `delat` INT, IN `mrp` DECIMAL(9,2), IN `frees` INT, IN `hsn` BIGINT, IN `ptr` DECIMAL(9,2), IN `taxamt` DECIMAL(9,2), IN `discpc` DECIMAL(5,2), IN `disct` DECIMAL(9,2), IN `batch` VARCHAR(20), IN `expiry` DATE, IN `adminid` INT)   BEGIN
	UPDATE invoice_details SET invdet_qty = qty, invdet_price = price, invdet_schdisc=schdisc, invdet_cstpc = cstpc, invdet_cst = cst, invdet_sstpc = sstpc, invdet_sst = sst, invdet_delivered = delat, invdet_mrp = mrp, invdet_free = frees, invdet_hsn = hsn, invdet_ptr = ptr, invdet_taxamt = taxamt, invdet_discpc = discpc, invdet_discount = disct, invdet_batch = batch, invdet_expiry = expiry, invdet_updby = adminid
    WHERE invdet_id = invdetid;
END$$

CREATE  PROCEDURE `updateLocation` (IN `locid` INT, IN `location` VARCHAR(100), IN `pin` VARCHAR(10), IN `country` VARCHAR(3), IN `state` VARCHAR(20), IN `district` INT, IN `remarks` TEXT, IN `dstatus` INT, IN `adminid` INT)   BEGIN

	/* IF( SELECT COUNT(*) FROM delivery_areas WHERE TRIM(delarea_location) = TRIM(location) ) = 0 THEN */
		UPDATE delivery_areas SET delarea_location = location, delarea_pincode = pin, delarea_country = country, delarea_province = state, delarea_district = district, delarea_remarks = remarks, delarea_status = dstatus, delarea_updby = adminid WHERE delarea_id = locid;
    /* END IF; */
    
END$$

CREATE  PROCEDURE `updateManufacturer` (IN `manufid` INT, IN `mname` VARCHAR(200), IN `address` VARCHAR(255), IN `phones` VARCHAR(200), IN `email` VARCHAR(50), IN `website` VARCHAR(50), IN `contact` VARCHAR(200), IN `contactno` VARCHAR(200), IN `conemail` VARCHAR(50), IN `concell` VARCHAR(50), IN `whatsapp` VARCHAR(50), IN `contactat` VARCHAR(255), IN `regn` VARCHAR(255), IN `remarks` TEXT, IN `mstatus` INT, IN `adminid` INT, IN `mcodes` VARCHAR(20))   BEGIN
	UPDATE manufacturers_tbl 
    SET manuf_name = mname, manuf_address = address, manuf_phones = phones, manuf_email = email, manuf_website = website, manuf_contact = contact, manuf_contactno = contactno, manuf_contactemail = conemail, manuf_contactcell = concell, manuf_whatsapp = whatsapp, manuf_contactat = contactat, manuf_regn = regn, manuf_remarks = remarks, manuf_status = mstatus, manuf_updby = adminid,manuf_code=mcodes
    WHERE manuf_id = manufid;
END$$

CREATE  PROCEDURE `updateOfOrderDatas` (IN `ord_id` INT, IN `track_id` VARCHAR(30), IN `del_status` INT, IN `finalship` INT, IN `shipped_date` DATETIME, IN `remarks` TEXT, IN `secretid` INT, IN `del_date` DATETIME)   BEGIN
DECLARE adminid int DEFAULT 0;
SELECT u.user_id INTO adminid FROM users_tbl u WHERE u.user_checkid=secretid;
UPDATE orders_tbl SET order_trackid=track_id ,order_delivery=del_status,order_finalshipby=finalship ,orders_shipped=shipped_date ,orders_delivered=del_date,order_remarks=remarks,order_updby=adminid,order_updon=CURRENT_TIMESTAMP() WHERE order_id =ord_id;
END$$

CREATE  PROCEDURE `updateOrderDetailsperItems` (IN `orderid` INT, IN `strstkid` INT, IN `itemsid` INT, IN `delstatus` INT)   BEGIN
UPDATE order_details SET ordet_active=delstatus WHERE ordet_order=orderid AND ordet_producpackid=itemsid AND order_batchid=strstkid ;
IF delstatus=2 THEN
UPDATE order_details SET order_prdate=CURRENT_TIMESTAMP() WHERE ordet_order=orderid AND ordet_producpackid=itemsid AND order_batchid=strstkid ;
ELSEIF delstatus=3 THEN
UPDATE order_details SET order_shipped=CURRENT_TIMESTAMP() WHERE ordet_order=orderid AND ordet_producpackid=itemsid AND order_batchid=strstkid ;
ELSEIF delstatus=4 THEN
UPDATE order_details SET order_delivered=CURRENT_TIMESTAMP() WHERE ordet_order=orderid AND ordet_producpackid=itemsid AND order_batchid=strstkid ;
ELSEIF delstatus=5 THEN
UPDATE order_details SET order_cancelled=CURRENT_TIMESTAMP() WHERE ordet_order=orderid AND ordet_producpackid=itemsid AND order_batchid=strstkid ;
ELSEIF delstatus=6 THEN
UPDATE order_details SET order_refund=CURRENT_TIMESTAMP() WHERE ordet_order=orderid AND ordet_producpackid=itemsid AND order_batchid=strstkid ;
END IF;
END$$

CREATE  PROCEDURE `updatePackingForDataEntry` (IN `ids` INT, IN `type` INT, IN `qty` DECIMAL(10,2), IN `unit` INT, IN `maxqty` INT, IN `minqty` INT, IN `roq` INT, IN `hsn` VARCHAR(10), IN `taxgrp` DECIMAL(5,2))   BEGIN

UPDATE product_packing SET prodpack_package=type,prodpack_quantity=qty,prodpack_unit=unit,prodpack_maxstock=maxqty,prodpack_minstock=minqty,prodpack_roq=roq,prodpack_hsn=hsn, prodpack_taxgroup=taxgrp WHERE prodpack_id=ids;

END$$

CREATE  PROCEDURE `updatePackingSale` (IN `sale` INT, IN `packid` INT, IN `adminid` INT)   BEGIN
UPDATE packing_tbl  SET packing_sale=sale , packing_updby=adminid WHERE packing_id=packid;
END$$

CREATE  PROCEDURE `updateProduct` (IN `pid` INT, IN `pname` VARCHAR(255), IN `display` VARCHAR(255), IN `generic` INT, IN `maincat` INT, IN `subcat` INT, IN `categ` INT, IN `manuf` INT, IN `brand` INT, IN `drugmain` INT, IN `drugsub` INT, IN `drugclass` INT, IN `clasfd` INT, IN `prescrp` INT, IN `highlights` TEXT, IN `inform` TEXT, IN `working` TEXT, IN `howto` TEXT, IN `benefits` TEXT, IN `specs` TEXT, IN `features` TEXT, IN `usge` TEXT, IN `caution` TEXT, IN `warns` TEXT, IN `effects` TEXT, IN `antidot` TEXT, IN `interact` TEXT, IN `publish` INT, IN `sale` INT, IN `onlne` INT, IN `featured` INT, IN `popular` INT, IN `ingreds` TEXT, IN `dossage` VARCHAR(255), IN `taxgrp` INT, IN `schedule_id` INT, IN `pstatus` INT, IN `approved` VARCHAR(200), IN `pcontent` INT, IN `adminid` INT)   BEGIN
   UPDATE products_tbl SET product_name = pname, product_display = display,product_generic = generic, product_maincategory = maincat, product_subcategory = subcat, product_category = categ, product_manufacturer = manuf, product_brand = brand, product_drugmainclass = drugmain, product_drugsubclass = drugsub, product_drugclass = drugclass, product_classified = clasfd, product_prescrption = prescrp, product_highlights = highlights, product_information = inform, product_working = working, product_howto = howto, product_benefits = benefits, product_specifications = specs, product_features = features, product_usage = usge, product_precautions = caution, product_warnings = warns, product_sideffects = effects, product_antidot = antidot, product_interactions = interact, product_publish = publish, product_sale = sale, product_online = onlne, product_featured = featured, product_popular = popular, product_taxgroup = taxgrp, product_updby = adminid, product_status = CASE WHEN approved='45,13,34' THEN 1 ELSE 0 END , product_schedule = schedule_id, product_approve=approved, product_pcontent=pcontent WHERE product_id = pid;
   
   IF pid > 0 THEN
    	SET @text := TRIM(BOTH '##' FROM ingreds);
  SET @strLen := 0;
  SET @i := 1;
  WHILE @strLen < LENGTH(@text) DO
  
    SET @str := SUBSTRING_INDEX(@text, '##', @i);
    SET @strLen := LENGTH(@str);
    SET @i := @i + 1;
    
    SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
    
     SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 SET @strGLen := 0;
     SET @Gi := 1;
     
     SET @icols := 1;
     
     WHILE @strGLen < LENGTH(@GRAPE) DO
     
        SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
        SET @strGLen := LENGTH(@Gstr);
        SET @Gi := @Gi + 1;
     
        IF @icols = 1 THEN
        	SET @ingrd := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 2 THEN
            SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSE
            SET @unt := SUBSTRING_INDEX(@Gstr, '|', -1);
        END IF;
        
        SET @icols := @icols + 1;
        
     END WHILE;

	 INSERT INTO product_ingredients( prodingred_product, prodingred_ingredient, prodingred_quantity, prodingred_unit, prodingred_crtdby ) 
     VALUES( pid, @ingrd, @qty, @unt, adminid )
     ON DUPLICATE KEY UPDATE prodingred_status = 1, prodingred_updby = adminid;
  END WHILE;
  
    /* packaging details */
    SET @text := TRIM(BOTH '##' FROM dossage);
  SET @strLen := 0;
  SET @i := 1;
  WHILE @strLen < LENGTH(@text) DO
  
    SET @str := SUBSTRING_INDEX(@text, '##', @i);
    SET @strLen := LENGTH(@str);
    SET @i := @i + 1;
    
    SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
    
     SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 SET @strGLen := 0;
     SET @Gi := 1;
     
     SET @icols := 1;
     
     WHILE @strGLen < LENGTH(@GRAPE) DO
     
        SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
        SET @strGLen := LENGTH(@Gstr);
        SET @Gi := @Gi + 1;
     
        IF @icols = 1 THEN
        	SET @packid := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 2 THEN
            SET @pqty := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 3 THEN
            SET @punit := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 4 THEN
            SET @stkmin := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 5 THEN
            SET @stkmax := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 6 THEN
            SET @roq := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 7 THEN
            SET @hsn := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSE
            SET @tax := SUBSTRING_INDEX(@Gstr, '|', -1);
        END IF;
        
        SET @icols := @icols + 1;
        
     END WHILE;

	 INSERT INTO product_packing( prodpack_product, prodpack_package, prodpack_quantity, prodpack_unit, prodpack_maxstock, prodpack_minstock, prodpack_roq, prodpack_hsn, prodpack_taxgroup, prodpack_crtdby ) 
     VALUES( pid, @packid, @pqty, @punit, @stkmax, @stkmin, @roq, @hsn, @tax, adminid )
     ON DUPLICATE KEY UPDATE prodpack_status = 1, prodpack_updby = adminid;
  END WHILE;
    
    END IF;
END$$

CREATE  PROCEDURE `updateProductClassDetails` (IN `prclsid` INT, IN `parent` INT, IN `serial` INT, IN `pstatus` INT, IN `adminid` INT, IN `thumb` VARCHAR(100))   BEGIN
	IF trim(thumb) = '' THEN
		UPDATE product_classes 
    	SET prodclass_parent = parent, prodclass_serial = serial, prodclass_status = pstatus, prodclass_updby = adminid 
    	WHERE prodclass_id = prclsid;
   	ELSE
    	UPDATE product_classes 
    	SET prodclass_parent = parent, prodclass_serial = serial, prodclass_status = pstatus, prodclass_updby = adminid, prodclass_thumb = thumb
    	WHERE prodclass_id = prclsid;
    END IF;
    CALL reworkProductClassSequence(prclsid);
END$$

CREATE  PROCEDURE `updateProductClassThumb` (IN `prclsid` INT, IN `adminid` INT, IN `thumb` VARCHAR(100))   BEGIN
	IF trim(thumb) <> '' THEN
		UPDATE product_classes p
    	SET p.prodclass_updby = adminid, p.prodclass_thumb = thumb
    	WHERE p.prodclass_id = prclsid;
    END IF;
END$$

CREATE  PROCEDURE `updateProductEntryDatas` (IN `pid` INT, IN `pname` VARCHAR(255), IN `generic` INT, IN `maincat` INT, IN `subcat` INT, IN `categ` INT, IN `manuf` INT, IN `brand` INT, IN `drugmain` INT, IN `drugsub` INT, IN `drugclass` INT, IN `clasfd` INT, IN `prescrp` INT, IN `highlights` TEXT, IN `inform` TEXT, IN `working` TEXT, IN `howto` TEXT, IN `benefits` TEXT, IN `specs` TEXT, IN `features` TEXT, IN `usge` TEXT, IN `caution` TEXT, IN `warns` TEXT, IN `effects` TEXT, IN `antidot` TEXT, IN `interact` TEXT, IN `ingreds` TEXT, IN `dossage` VARCHAR(255), IN `taxgrp` INT, IN `pcontent` INT, IN `adminid` INT)   BEGIN
   UPDATE products_entry_tbl SET product_name = pname,product_generic = generic, product_maincategory = maincat, product_subcategory = subcat, product_category = categ, product_manufacturer = manuf, product_brand = brand, product_drugmainclass = drugmain, product_drugsubclass = drugsub, product_drugclass = drugclass, product_classified = clasfd, product_prescrption = prescrp, product_highlights = highlights, product_information = inform, product_working = working, product_howto = howto, product_benefits = benefits, product_specifications = specs, product_features = features, product_usage = usge, product_precautions = caution, product_warnings = warns, product_sideffects = effects, product_antidot = antidot, product_interactions = interact, product_taxgroup = taxgrp, product_updby = adminid, product_pcontent=pcontent,product_entry_status=1 WHERE product_id = pid;
   
   INSERT IGNORE INTO `brand_manufacturer_tbl`( `brnd_id`, `brndmanu_id`) VALUES (brand,manuf);
   
   IF pid > 0 THEN
    	SET @text := TRIM(BOTH '##' FROM ingreds);
  SET @strLen := 0;
  SET @i := 1;
  WHILE @strLen < LENGTH(@text) DO
  
    SET @str := SUBSTRING_INDEX(@text, '##', @i);
    SET @strLen := LENGTH(@str);
    SET @i := @i + 1;
    
    SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
    
     SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 SET @strGLen := 0;
     SET @Gi := 1;
     
     SET @icols := 1;
     
     WHILE @strGLen < LENGTH(@GRAPE) DO
     
        SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
        SET @strGLen := LENGTH(@Gstr);
        SET @Gi := @Gi + 1;
     
        IF @icols = 1 THEN
        	SET @ingrd := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 2 THEN
            SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSE
            SET @unt := SUBSTRING_INDEX(@Gstr, '|', -1);
        END IF;
        
        SET @icols := @icols + 1;
        
     END WHILE;

	 INSERT INTO product_ingredients( prodingred_product, prodingred_ingredient, prodingred_quantity, prodingred_unit, prodingred_crtdby ) 
     VALUES( pid, @ingrd, @qty, @unt, adminid )
     ON DUPLICATE KEY UPDATE prodingred_status = 1, prodingred_updby = adminid;
  END WHILE;
  
    /* packaging details */
    SET @text := TRIM(BOTH '##' FROM dossage);
  SET @strLen := 0;
  SET @i := 1;
  WHILE @strLen < LENGTH(@text) DO
  
    SET @str := SUBSTRING_INDEX(@text, '##', @i);
    SET @strLen := LENGTH(@str);
    SET @i := @i + 1;
    
    SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
    
     SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 SET @strGLen := 0;
     SET @Gi := 1;
     
     SET @icols := 1;
     
     WHILE @strGLen < LENGTH(@GRAPE) DO
     
        SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
        SET @strGLen := LENGTH(@Gstr);
        SET @Gi := @Gi + 1;
     
        IF @icols = 1 THEN
        	SET @packid := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 2 THEN
            SET @pqty := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 3 THEN
            SET @punit := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 4 THEN
            SET @stkmin := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 5 THEN
            SET @stkmax := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 6 THEN
            SET @roq := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 7 THEN
            SET @hsn := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSE
            SET @tax := SUBSTRING_INDEX(@Gstr, '|', -1);
        END IF;
        
        SET @icols := @icols + 1;
        
     END WHILE;

	 INSERT INTO product_packing( prodpack_product, prodpack_package, prodpack_quantity, prodpack_unit, prodpack_maxstock, prodpack_minstock, prodpack_roq, prodpack_hsn, prodpack_taxgroup, prodpack_crtdby ) 
     VALUES( pid, @packid, @pqty, @punit, @stkmax, @stkmin, @roq, @hsn, @tax, adminid )
     ON DUPLICATE KEY UPDATE prodpack_status = 1, prodpack_updby = adminid;
  END WHILE;
    
    END IF;
END$$

CREATE  PROCEDURE `updateProgramMenus` (IN `id` INT, IN `menuname` VARCHAR(50), IN `url` VARCHAR(100), IN `icon` VARCHAR(100), IN `serialno` INT, IN `parentid` INT, IN `statusid` INT)   begin

update programs_table p set p.progr_menu = menuname,p.progr_url = url,p.progr_icon = icon, p.progr_serial = serialno,p.progr_parent = parentid,p.progr_status = statusid where p.progr_id = id;

END$$

CREATE  PROCEDURE `updatePromotionDatas` (IN `promoid` INT, IN `promotype` INT, IN `promotitle` VARCHAR(255), IN `promacnt` INT, IN `promodicamnt` DECIMAL(10,0), IN `promodiscper` DECIMAL(10,0), IN `promomax` DECIMAL(10,0), IN `promocount` INT, IN `datefrom` DATE, IN `dateto` DATE, IN `promostatus` INT, IN `publishstatus` INT, IN `promohighlights` INT, IN `adminid` INT)   BEGIN
    UPDATE promotions_tbl SET promo_id=promoid, promo_type=promotype, promo_title=promotitle, promo_account=promacnt, promo_discountamt=promodicamnt,promo_discountpc=promodiscper, promo_max=promomax, promo_count=promocount, promo_datefrom=datefrom, promo_dateto=dateto, promo_status=promostatus, promo_publish=publishstatus, promo_highlights=promohighlights, promo_uptdby=adminid, promo_uptdon=CURRENT_TIMESTAMP() WHERE promo_id=promoid;
END$$

CREATE  PROCEDURE `updatePurchaseOrder` (IN `poid` INT, IN `orderef` VARCHAR(20), IN `ordate` DATE, IN `license` VARCHAR(50), IN `amount` DECIMAL(11,2), IN `ordetails` TEXT, IN `notes` TEXT, IN `approved` INT, IN `issued` INT, IN `pstatus` INT, IN `deliverat` INT, IN `deliverby` DATE, IN `adminid` INT)   BEGIN
	DECLARE aprvd, isud, pitid ,checkid INT DEFAULT 0;
    DECLARE preprdon, aprvdon, issuedon DATE DEFAULT '0000-00-00';
    DECLARE approveddby, issuedby INT DEFAULT 0;
    SELECT x.purchord_aprvdby, x.purchord_issuedby INTO aprvd, isud
    FROM purchase_orders x WHERE x.purchord_id = poid;
    SELECT user_id INTO checkid FROM users_tbl WHERE user_checkid=adminid;
    IF approved = 0 AND issued = 0 THEN
    	SET preprdon = CURDATE();
    ELSE
    	IF approved = 1 THEN
    		SET approveddby = checkid;
        	SET aprvdon = CURDATE();
   	 	END IF;
    	IF issued = 1 THEN
    		SET issuedby = checkid;
        	SET issuedon = CURDATE();
    	END IF;
    END IF;
    IF aprvd = 0 AND approved = 0 THEN /* allow edit order */
    	UPDATE purchase_orders SET purchord_ref = orderef, purchord_date = ordate, purchord_amount = amount, purchord_notes = notes, purchord_preprdby = checkid, purchord_updby = checkid, purchord_preprdon = preprdon, purchord_amount = amount, purchord_status = pstatus, purchord_deliverat = deliverat, purchord_deliverby = deliverby, purchord_license = license
    	WHERE purchord_id = poid;
    ELSEIF aprvd = 0 THEN
    	UPDATE purchase_orders SET purchord_aprvdby = approveddby, purchord_aprvdon = aprvdon, purchord_notes = notes, purchord_updby = checkid
        WHERE purchord_id = poid;
    ELSEIF isud = 0 THEN
    	UPDATE purchase_orders SET purchord_notes = notes, purchord_issuedby = issuedby, purchord_issuedon = issuedon, purchord_updby = adminid, purchord_pdfurl = CONCAT(purchord_ref, '.pdf')
    	WHERE purchord_id = poid;
    ELSE
    	UPDATE purchase_orders SET purchord_notes = notes, purchord_updby = checkid
    	WHERE purchord_id = poid;
    END IF;
    IF aprvd = 0 THEN
    	SET @text := TRIM(BOTH '##' FROM ordetails);
  		SET @strLen := 0;
  		SET @i := 1;
  		WHILE @strLen < LENGTH(@text) DO
    		SET @str := SUBSTRING_INDEX(@text, '##', @i);
    		SET @strLen := LENGTH(@str);
    		SET @i := @i + 1;
     		SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
        	SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 		SET @strGLen := 0;
     		SET @Gi := 1;
     		SET @icols := 1;
     		WHILE @strGLen < LENGTH(@GRAPE) DO
		        SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
                SET @strGLen := LENGTH(@Gstr);
                SET @Gi := @Gi + 1;
                IF @icols = 1 THEN
                    SET @item := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 2 THEN
                    SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSE
                    SET @price := SUBSTRING_INDEX(@Gstr, '|', -1);
                END IF;
        		SET @icols := @icols + 1;
     		END WHILE;
            IF (SELECT COUNT(*) FROM purchase_details WHERE podetail_order = poid AND podetail_item = @item) = 0 THEN
     			INSERT INTO purchase_details( podetail_order, podetail_item, podetail_qty, podetail_price )
            	VALUES( poid, @item, @qty, @price );
            ELSE
            	UPDATE purchase_details SET podetail_qty = @qty, podetail_price = @price
                WHERE podetail_order = poid AND podetail_item = @item;
            END IF;
  		END WHILE;
    END IF;
END$$

CREATE  PROCEDURE `updateReturnBillNo` (IN `bill_id` INT, IN `billvalue` VARCHAR(255))   BEGIN
UPDATE purchasereturn_tbl SET returnbill_number=billvalue WHERE returnbill_id =bill_id;

END$$

CREATE  PROCEDURE `updateReturnItemClcollection` (IN `bill_ids` TEXT, IN `flag` INT, IN `courier` INT, IN `notes` TEXT)   BEGIN
    DECLARE front, TempValue, alltracks, billid ,remark TEXT DEFAULT NULL;
    DECLARE frontlen INT DEFAULT NULL;
    DECLARE done BOOLEAN DEFAULT FALSE;
    DECLARE rtid ,stkid, qty ,store,items ,sknrd_id ,count_1,count_0 INT DEFAULT 0;
    DECLARE returnbillnum INT DEFAULT 0;
    DECLARE emp_cursor CURSOR FOR
        SELECT  return_id, return_stcknid, returnitem_qty, return_billnum, return_item, return_store,return_remark
        FROM purchasereturn_details
        WHERE FIND_IN_SET(return_id, bill_ids);
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    IF flag = 1 THEN
        SET billid = bill_ids;
        iterator: LOOP
            IF LENGTH(TRIM(bill_ids)) = 0 OR bill_ids IS NULL THEN
                LEAVE iterator;
            END IF;
            SET front = SUBSTRING_INDEX(bill_ids,',',1);
            SET frontlen = LENGTH(front);
            SET TempValue = TRIM(front);
            OPEN emp_cursor;
            read_loop: LOOP
                FETCH emp_cursor INTO rtid, stkid, qty, returnbillnum, items, store,remark;
                IF done THEN
                    LEAVE read_loop;
                END IF;
                IF rtid = TempValue THEN
                   /* SELECT rtid, stkid, qty, returnbillnum, items, store;*/
                    -- Update storestock_pricing table
                     UPDATE storestock_pricing SET strstk_reserved = (strstk_reserved - qty), strstk_stock = (strstk_stock - qty), strstk_return = (strstk_return + qty) WHERE strstk_id = stkid;
                       -- Update storestock_master table
                    UPDATE storestock_master SET storestock_available = (storestock_available - qty), storestock_reserved = (storestock_reserved - qty) WHERE storestock_item = items AND storestock_store = store;
                    -- Update purchasereturn_details
                    UPDATE purchasereturn_details SET return_courier = courier, returncltn_status = 1, courier_cltdon = CURRENT_TIMESTAMP() WHERE return_id = rtid;
                         SELECT strstk_refer INTO sknrd_id FROM storestock_pricing WHERE strstk_id = stkid;
                IF remark='damage' THEN
                	UPDATE stock_inwards SET  stockin_reserved=(stockin_reserved - qty) WHERE stockin_id=sknrd_id;
                END IF;
                SELECT  COUNT(CASE WHEN returncltn_status = 1 THEN 1 END) , COUNT(CASE WHEN returncltn_status = 0 THEN 1 END)INTO count_1 ,count_0						FROM purchasereturn_details WHERE return_billnum=returnbillnum;
                    -- Update purchasereturn_tbl
                    IF count_1>0 AND count_0=0 THEN
               UPDATE purchasereturn_tbl SET returnbill_status = 5 WHERE returnbill_id = returnbillnum;
               END IF;
                END IF;
            END LOOP;
            CLOSE emp_cursor;
            SET bill_ids = INSERT(bill_ids, 1, frontlen + 1, '');
            SET done = FALSE;
        END LOOP;
    END IF;
END$$

CREATE  PROCEDURE `updateScheduledDiscountDatas` (IN `discid` INT, IN `dated` DATE, IN `storeid` INT, IN `mainitem` TEXT, IN `freeitem` TEXT, IN `notes` TEXT, IN `disstatus` INT, IN `appvdby` INT, IN `secretid` INT)   BEGIN
DECLARE adminid INT DEFAULT 0;
SELECT user_id INTO adminid FROM users_tbl WHERE user_checkid=secretid ;
IF appvdby=0 THEN
UPDATE schedulediscount_tbl  SET dis_date=dated,dis_store=storeid,dis_mainitem=mainitem,dis_freeitem=freeitem,dis_note=notes,dis_status=disstatus,dis_approvedby=0 WHERE dis_id =discid;
ELSE
UPDATE schedulediscount_tbl  SET dis_date=dated,dis_store=storeid,dis_mainitem=mainitem,dis_freeitem=freeitem,dis_note=notes,dis_status=disstatus,dis_approvedby=adminid,dis_approvedon=CURRENT_TIMESTAMP() WHERE dis_id =discid;
END IF;
END$$

CREATE  PROCEDURE `updateStaff` (IN `id` INT, IN `staffname` VARCHAR(100), IN `staffcode` VARCHAR(100), IN `staffbranch` INT, IN `staffdob` DATE, IN `staffgender` TINYINT, IN `staffmobile` VARCHAR(100), IN `staffemail` VARCHAR(100), IN `staffaddress` TEXT, IN `staffstatus` INT, IN `staffimg` VARCHAR(100), IN `staffsign` VARCHAR(100), IN `adminid` INT, IN `username` VARCHAR(100), IN `passwords` VARCHAR(100), IN `programid` INT, IN `programcontains` TEXT, IN `checkid` VARCHAR(100), IN `usertblid` INT)   begin
UPDATE  staff_tbl s set s.staff_name =staffname, s.staff_code = staffcode, s.staff_branch=staffbranch, s.staff_dob = staffdob, s.staff_gender = staffgender,s.staff_mobile = staffmobile, s.staff_email = staffemail, s.staff_address = staffaddress, s.staff_status = staffstatus, s.staff_image= staffimg, s.staff_signature=staffsign, s.staff_updby = adminid WHERE s.staff_id = id;
if(usertblid = 0)THEN
insert into users_tbl(user_login,user_password,user_staffid,user_staffname,user_programid,user_programcontains,user_checkid,user_crtdby) values(username,passwords,id,staffname,programid,programcontains,checkid,adminid);
ELSE
UPDATE users_tbl u set u.user_login = username, u.user_password = passwords, u.user_programid = programid, u.user_programcontains =  programcontains, u.user_checkid=checkid ,u.user_staffname=staffname WHERE u.user_id = usertblid and u.user_staffid = id;
END IF;
END$$

CREATE  PROCEDURE `updateStockist` (IN `stkid` INT, IN `sname` VARCHAR(200), IN `address` VARCHAR(255), IN `phones` VARCHAR(200), IN `email` VARCHAR(50), IN `website` VARCHAR(50), IN `contact` VARCHAR(200), IN `contactno` VARCHAR(200), IN `conemail` VARCHAR(50), IN `concell` VARCHAR(50), IN `whatsapp` VARCHAR(50), IN `contactat` VARCHAR(255), IN `regn` VARCHAR(255), IN `gstnum` VARCHAR(50), IN `tin` VARCHAR(50), IN `remarks` TEXT, IN `mstatus` INT, IN `adminid` INT, IN `manufs` VARCHAR(255), IN `products` VARCHAR(255))   BEGIN
    DECLARE front TEXT DEFAULT '';
    DECLARE frontlen INT DEFAULT 0;
    DECLARE tempVal TEXT DEFAULT '';
    
	UPDATE stockists_tbl SET
    stockist_name = sname, stockist_address = address, stockist_phones = phones, stockist_email = email, stockist_website = website, stockist_contact = contact, stockist_contactno = contactno, stockist_contactemail = conemail, stockist_contactcell = concell, stockist_whatsapp = whatsapp, stockist_contactat = contactat,   stockist_regn = regn, stockist_gst = gstnum, stockist_tin = tin, stockist_remarks = remarks, stockist_status = mstatus, stockist_updby = adminid 
    WHERE stockist_id = stkid;
    
    IF TRIM(manufs) <> '' THEN
    /* add manufacturers if given */
        iterator:
        LOOP
        	IF LENGTH(TRIM(manufs)) = 0 OR manufs IS NULL THEN
            	LEAVE iterator;
            END IF;
            SET front = SUBSTRING_INDEX(manufs, ',', 1);
            SET frontlen = LENGTH(front);
            SET tempVal = TRIM(front);
            INSERT INTO stockist_manufacturers  (stockmanu_stockist, stockmanu_company , stockmanu_status, stockmanu_crtdby) 
            VALUES (stkid, tempVal,1, adminid)
            ON DUPLICATE KEY UPDATE stockmanu_status = 1, stockmanu_updby = adminid;
            SET manufs = INSERT(manufs, 1, frontlen + 1, '');
        END LOOP;
        /* add products if not empty */
        proditerator:
        LOOP
        	IF LENGTH(TRIM(products)) = 0 OR products IS NULL THEN
            	LEAVE proditerator;
            END IF;
            SET front = SUBSTRING_INDEX(products, ',', 1);
            SET frontlen = LENGTH(front);
            SET tempVal = TRIM(front);
            /*SELECT stkid, tempVal, 1, adminid;*/
            INSERT INTO stockist_products (stockistprod_stockist, stockistprod_product ,stockistprod_status,stockistprod_crtdby) 
            VALUES (stkid, tempVal,1,adminid)
            ON DUPLICATE KEY UPDATE stockistprod_status = 1, stockistprod_updby = adminid;
            SET products = INSERT(products, 1, frontlen + 1, '');
        END LOOP;
    END IF;
END$$

CREATE  PROCEDURE `updateStorage` (IN `strgid` INT, IN `label` VARCHAR(50), IN `type` INT, IN `temp` VARCHAR(50), IN `humidity` VARCHAR(50), IN `secu` VARCHAR(50), IN `volume` INT, IN `size` VARCHAR(50), IN `sload` VARCHAR(50), IN `remarks` TEXT, IN `ststatus` INT, IN `adminid` INT)   BEGIN
UPDATE storage_tbl  SET storage_label = label,storage_type = type, storage_temperature=temp,storage_humidity=humidity,
storage_security=secu, storage_volume=volume, storage_size=size, storage_load=sload, storage_remarks=remarks,storage_status = ststatus,storage_updby=adminid,
storage_updon=CURRENT_TIMESTAMP() WHERE storage_id = strgid;
  END$$

CREATE  PROCEDURE `updateStore` (IN `storeid` INT, IN `stype` INT, IN `sname` VARCHAR(200), IN `address` VARCHAR(255), IN `coords` TEXT, IN `phones` VARCHAR(200), IN `mobile` VARCHAR(50), IN `email` VARCHAR(50), IN `whatsapp` VARCHAR(50), IN `contact` VARCHAR(200), IN `contactno` VARCHAR(200), IN `conemail` VARCHAR(50), IN `concell` VARCHAR(50), IN `conwapp` VARCHAR(50), IN `contactat` VARCHAR(255), IN `regn` VARCHAR(255), IN `gstnum` VARCHAR(50), IN `tin` VARCHAR(50), IN `power` INT, IN `water` INT, IN `remarks` TEXT, IN `dstatus` INT, IN `adminid` INT, IN `delareas` VARCHAR(255), IN `timings` TEXT, IN `scode` VARCHAR(6), IN `license` VARCHAR(50), IN `gstate` INT, IN `pan` VARCHAR(10))   BEGIN
	DECLARE distid INT DEFAULT 0;
    DECLARE front TEXT DEFAULT '';
    DECLARE frontlen INT DEFAULT 0;
    DECLARE tempVal TEXT DEFAULT '';
    
	UPDATE stores_tbl SET 
    store_type = stype, store_name = sname, store_address = address, store_phones = phones, store_mobile = mobile, store_email = email, store_whatsapp = whatsapp, store_contact = contact, store_contactno = contactno, store_contactemail = conemail, store_contactcell = concell, store_contactwapp = conwapp, store_contactat = contactat, store_regn = regn, store_GST = gstnum, store_TIN = tin, store_power = power, store_water = water, store_location = coords, store_remarks = remarks,store_UPDby = adminid, store_status = dstatus, store_code = scode, store_license = license, store_pan = pan, store_taxstate = gstate
    WHERE store_id = storeid;
    	
        /* add/edit delivery areas if not empty */
        iterator:
        LOOP
        	IF LENGTH(TRIM(delareas)) = 0 OR delareas IS NULL THEN
            	LEAVE iterator;
            END IF;
            SET front = SUBSTRING_INDEX(delareas, ',', 1);
            SET frontlen = LENGTH(front);
            SET tempVal = TRIM(front);
            INSERT INTO store_delivery ( 
                strdelv_store, strdelv_area, strdelv_crtdby ) 
            VALUES (storeid, tempVal, adminid)
            ON DUPLICATE KEY UPDATE strdelv_status = 1, strdelv_updby = adminid;
            SET delareas = INSERT(delareas, 1, frontlen + 1, '');
        END LOOP;

		/* remove and update timimgs */
        DELETE FROM store_timings WHERE strtme_store = storeid;
        SET @text := TRIM(BOTH '##' FROM timings);
        SET @strLen := 0;
        SET @i := 1;
        WHILE @strLen < LENGTH(@text) DO
  
            SET @str := SUBSTRING_INDEX(@text, '##', @i);
            SET @strLen := LENGTH(@str);
            SET @i := @i + 1;

            SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);

            SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
            SET @strGLen := 0;
            SET @Gi := 1;
     		SET @icols := 1;
     
     		WHILE @strGLen < LENGTH(@GRAPE) DO
                SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
                SET @strGLen := LENGTH(@Gstr);
                SET @Gi := @Gi + 1;
     
       			IF @icols = 1 THEN
        			SET @day := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 2 THEN
        			SET @sesn := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 3 THEN
        			SET @tfrom := SUBSTRING_INDEX(@Gstr, '|', -1);
        		ELSE
            		SET @tto := SUBSTRING_INDEX(@Gstr, '|', -1);
        		END IF;
        		SET @icols := @icols + 1;
     		END WHILE;
     		
            INSERT INTO store_timings(strtme_store, strtme_day, strtme_session, strtme_from, strtme_to, strtme_crtdby) 
            VALUES( storeid, @day, @sesn,  @tfrom, @tto, adminid );
  		END WHILE;
        
END$$

CREATE  PROCEDURE `updateStoreIntend` (IN `intendid` INT, IN `intend` VARCHAR(50), IN `dated` DATE, IN `tostore` INT, IN `notes` TEXT, IN `ordetails` TEXT, IN `status` INT, IN `adminid` INT)   BEGIN
	DECLARE indstat, apprvd ,checkid INT DEFAULT 0;
    SELECT user_id INTO checkid FROM users_tbl WHERE user_checkid=adminid ;
	SELECT intend_status, intend_apprvedby INTO indstat, apprvd
    FROM intends_tbl WHERE intend_id = intendid;
    IF (indstat = 1 AND apprvd = 0) THEN
      IF status = 0 THEN
      	UPDATE intends_tbl SET intend_updby = checkid, intend_status = 0
        WHERE intend_id = intendid;
      ELSE
		SET @text := TRIM(BOTH '##' FROM ordetails);
  		SET @strLen := 0;
  		SET @i := 1;
  		WHILE @strLen < LENGTH(@text) DO
    		SET @str := SUBSTRING_INDEX(@text, '##', @i);
    		SET @strLen := LENGTH(@str);
    		SET @i := @i + 1;
     		SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
        	SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 		SET @strGLen := 0;
     		SET @Gi := 1;
     		SET @icols := 1;
     		WHILE @strGLen < LENGTH(@GRAPE) DO
		        SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
                SET @strGLen := LENGTH(@Gstr);
                SET @Gi := @Gi + 1;
                IF @icols = 1 THEN
                    SET @product := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 2 THEN
                    SET @item := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 3 THEN
                    SET @hsn := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 4 THEN
                    SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSE
                    SET @stock := SUBSTRING_INDEX(@Gstr, '|', -1);
                END IF;
        		SET @icols := @icols + 1;
     		END WHILE;
     		INSERT INTO intend_details( intdet_id, intdet_item, intdet_product, intdet_hsn, intdet_quantity, intdet_stock )
            VALUES( intendid, @item, @product, @hsn, @qty, @stock )
            ON DUPLICATE KEY UPDATE intdet_quantity = @qty, intdet_hsn = @hsn, intdet_stock = @stock, intdet_updby = checkid;
  		END WHILE;
        UPDATE intends_tbl SET intend_number = intend, intend_date = dated, intend_notes = notes, intend_updby = checkid, intend_status = 1, intend_to = tostore, intend_items = (SELECT COUNT(*) FROM intend_details WHERE intdet_id = intendid)
        WHERE intend_id = intendid;
      END IF;
	END IF;
END$$

CREATE  PROCEDURE `updateStorePricing` (IN `stockid` INT, IN `msp` DECIMAL(9,2), IN `deal` INT, IN `offer` INT, IN `adminid` INT)   BEGIN
	UPDATE storestock_pricing 
    SET strstk_msp = msp, strstk_dealofday = deal, strstk_offer = offer, strstk_updby = adminid 
    WHERE strstk_id = stockid;
END$$

CREATE  PROCEDURE `updateTempIntendOrders` (IN `retid` INT, IN `oids` TEXT)   BEGIN
	UPDATE temp_intendorders SET ordrefer = retid, 
    ordqty = (SELECT SUM(x.stockorder_quantity) 
              FROM stocktransfer_details x 
              LEFT JOIN stock_inwards y ON y.stockin_id = x.stockorder_item 
              WHERE y.stockin_item = item AND x.stockorder_refer = retid) 
    WHERE FIND_IN_SET(id, oids);
END$$

CREATE  PROCEDURE `updateTempIntendPurchaseOrders` (IN `retid` INT, IN `oids` TEXT)   BEGIN
	UPDATE temp_intendorderss SET ordrefer = retid WHERE FIND_IN_SET(id, oids);
END$$

CREATE  PROCEDURE `updateTransferPacket` (IN `packid` INT, IN `items` TEXT, IN `notes` TEXT, IN `adminid` INT)   BEGIN
	/*DECLARE crstatus INT DEFAULT 0;
    SELECT COUNT(*) INTO crstatus FROM transfer_packets x
    WHERE x.transpack_id = packid AND x.transpack_status > 1;
    IF crstatus = 0 THEN
		DELETE FROM transferpack_items WHERE transferpack_packet = packid;
    	SET @text := TRIM(BOTH '##' FROM items);
  		SET @strLen := 0;
  		SET @i := 1;
  		WHILE @strLen < LENGTH(@text) DO
    		SET @str := SUBSTRING_INDEX(@text, '##', @i);
    		SET @strLen := LENGTH(@str);
    		SET @i := @i + 1;
     		SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
        	SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 		SET @strGLen := 0;
     		SET @Gi := 1;
     		SET @icols := 1;
     		WHILE @strGLen < LENGTH(@GRAPE) DO
		        SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
               	SET @strGLen := LENGTH(@Gstr);
               	SET @Gi := @Gi + 1;
               	IF @icols = 1 THEN
               		SET @item := SUBSTRING_INDEX(@Gstr, '|', -1);
               	ELSE
                   	SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
               	END IF;
       			SET @icols := @icols + 1;
    		END WHILE;
    		INSERT INTO transferpack_items( transferpack_packet, transferpack_item, transferpack_qty, transferpack_packby )
           	VALUES( packid, @item, @qty, adminid )
            ON DUPLICATE KEY UPDATE  transferpack_qty = (transferpack_qty + @qty) ;
  		END WHILE;*/
        UPDATE transfer_packets SET transpack_updby = adminid, transpack_notes = notes,
        transpack_items = (SELECT COUNT(*) FROM transferpack_items WHERE transferpack_packet = packid)
        WHERE transpack_id = packid;
   /* ELSE
    	select 'outside';
    END IF;*/
END$$

CREATE  PROCEDURE `updateUser` (IN `id` INT, IN `login` VARCHAR(100), IN `passwords` VARCHAR(100), IN `staffid` INT, IN `staffname` VARCHAR(100), IN `programid` INT, IN `programcontains` TEXT, IN `statuss` INT, IN `adminid` INT)   begin
update users_tbl u set u.user_login = login, u.user_password = passwords, u.user_staffid = staffid, u.user_staffname = staffname,u.user_programid = programid , u.user_programcontains = programcontains, u.user_status = statuss , u.user_updby = adminid where u.user_id = id;

END$$

CREATE  PROCEDURE `updateUserDetailsbyId` (IN `customer_id` INT, IN `customer_name` VARCHAR(255), IN `customer_email` VARCHAR(255), IN `customer_gender` INT, IN `customer_age` INT)   BEGIN
UPDATE customers_tbl c SET c.customer_name=customer_name, c.customer_email=customer_email, c.customer_gender=customer_gender, c.customer_age=customer_age, c.customer_updby=customer_id WHERE c.customer_id=customer_id AND c.customer_type=1;
END$$

CREATE  PROCEDURE `updateUserProgramRoles` (IN `id` INT, IN `rolename` VARCHAR(50), IN `roleprograms` MEDIUMTEXT, IN `adminid` INT)   begin

UPDATE user_program u  set u.usrprog_name = rolename , u.usrprog_programs = roleprograms , u.usrprog_updby = adminid WHERE u.usrprog_id = id;
update users_tbl ut set ut.user_programcontains = roleprograms WHERE ut.user_programid = id;
END$$

CREATE  PROCEDURE `updateVendorSupply` (IN `vensupid` INT, IN `price` DECIMAL(9,2), IN `minq` INT, IN `maxq` INT, IN `eoq` INT, IN `deldays` INT, IN `notes` VARCHAR(255), IN `vstatus` INT, IN `adminid` INT)   BEGIN
	UPDATE vendor_supplies SET vendsup_price = price, vendsup_minqty = minq, vendsup_maxqty = maxq, vendsup_eoq = eoq, vendsup_deliver = deldays, vendsup_notes = notes, vendsup_status = vstatus, vendsup_updby = adminid 
    WHERE vendsup_id = vensupid;
END$$

CREATE  PROCEDURE `updateViewcart` (IN `qty` INT, IN `packid` INT, IN `stockid` INT, IN `prdid` INT)   BEGIN

    DECLARE qtys, strk,TotalStock INT DEFAULT 0;
    DECLARE mrp, msp, disc DOUBLE DEFAULT 0;
    DECLARE strArray TEXT; 
    SELECT e1.strstk_mrp, e1.strstk_msp, e1.strstk_discount, 
           (e1.strstk_stock - e1.strstk_reserved), e1.strstk_id 
    INTO mrp, msp, disc, qtys, strk 
    FROM storestock_pricing e1
    JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer
    WHERE e1.strstk_product = prdid  
      AND e1.strstk_item = packid 
      AND e1.strstk_id = stockid;
      
      /*SELECT GROUP_CONCAT(x.strstk_id) INTO strArray FROM ( SELECT e1.strstk_item, s1.stockin_expiry, e1.strstk_discount AS max_discount, (e1.strstk_stock - e1.strstk_reserved) AS stock_available, e1.strstk_mrp, e1.strstk_msp, e1.strstk_id, e1.strstk_product FROM storestock_pricing e1 JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer WHERE e1.strstk_product = prdid AND (e1.strstk_stock - e1.strstk_reserved) > 0 AND s1.stockin_expiry >= CURRENT_DATE() AND e1.strstk_item = packid ) AS x WHERE x.stock_available > 0 AND x.stockin_expiry >= CURRENT_DATE() AND x.strstk_mrp = CAST(mrp AS DECIMAL(10,2)) AND x.strstk_msp = CAST(msp AS DECIMAL(10,2)) AND x.max_discount = CAST(disc AS DECIMAL(10,2)) GROUP BY x.strstk_item ORDER BY x.stockin_expiry ASC, x.max_discount DESC, x.stock_available DESC;
   */
   SELECT 
    GROUP_CONCAT(
        e1.strstk_id 
        ORDER BY 
            s1.stockin_expiry ASC,
            e1.strstk_discount DESC,
            (e1.strstk_stock - e1.strstk_reserved) ASC
        SEPARATOR ','
    ) INTO strArray
FROM storestock_pricing e1
JOIN stock_inwards s1 
    ON s1.stockin_id = e1.strstk_refer
WHERE e1.strstk_product = prdid
  AND (e1.strstk_stock - e1.strstk_reserved) > 0
  AND s1.stockin_expiry >= CURRENT_DATE()
  AND e1.strstk_item = packid
  AND e1.strstk_mrp = CAST(mrp AS DECIMAL(10,2)) AND e1.strstk_msp = CAST(msp AS DECIMAL(10,2)) AND e1.strstk_discount = CAST(disc AS DECIMAL(10,2));
     
     /* SELECT SUM(x.stock_available) INTO TotalStock
FROM (
    SELECT e1.strstk_item, 
           s1.stockin_expiry, 
           e1.strstk_discount AS max_discount, 
           (e1.strstk_stock - e1.strstk_reserved) AS stock_available, 
           e1.strstk_mrp, 
           e1.strstk_msp, 
           e1.strstk_id, 
           e1.strstk_product 
    FROM storestock_pricing e1 
    JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer 
    WHERE e1.strstk_product = prdid 
      AND (e1.strstk_stock - e1.strstk_reserved) > 0 
      AND s1.stockin_expiry >= CURRENT_DATE() 
      AND e1.strstk_item = packid
) AS x
WHERE x.stock_available > 0 
  AND x.stockin_expiry >= CURRENT_DATE() 
   AND x.strstk_mrp = CAST(mrp AS DECIMAL(10,2)) 
  AND x.strstk_msp = CAST(msp AS DECIMAL(10,2)) 
  AND x.max_discount = CAST(disc AS DECIMAL(10,2))
 GROUP BY x.strstk_product
ORDER BY x.stockin_expiry ASC, x.max_discount DESC, x.stock_available DESC;*/
SELECT 
    SUM(
        (e1.strstk_stock - e1.strstk_reserved)
    ) INTO TotalStock
FROM storestock_pricing e1
JOIN stock_inwards s1 
    ON s1.stockin_id = e1.strstk_refer
WHERE e1.strstk_product = prdid
  AND (e1.strstk_stock - e1.strstk_reserved) > 0
  AND s1.stockin_expiry >= CURRENT_DATE()
  AND e1.strstk_mrp = CAST(mrp AS DECIMAL(10,2)) AND e1.strstk_msp = CAST(msp AS DECIMAL(10,2)) AND e1.strstk_discount = CAST(disc AS DECIMAL(10,2))
  AND e1.strstk_item = packid ORDER BY 
            s1.stockin_expiry ASC,
            e1.strstk_discount DESC,
            (e1.strstk_stock - e1.strstk_reserved) ASC;
      

    IF qty <= TotalStock THEN
        SELECT 0 AS type, totalStock AS TotalStock;
    ELSE
      SELECT 1 AS type, totalStock AS TotalStock;
   SELECT
    product_id,
    product_name,
    product_display,
    prodpack_id,
    prodpack_quantity,
    packing_type,
    measunit_shortname,
    strstk_mrp,
    strstk_msp,
    stockin_batch,
    product_imageurl,
    strstk_discount,
    strstk_id,
    strstk_item,
    Totlval
FROM (
    SELECT
        p.product_id,
        p.product_name,
        p.product_display,
        r.prodpack_id,
        r.prodpack_quantity,
        t.packing_type,
        m.measunit_shortname,
        e.strstk_mrp,
        e.strstk_msp,
        s.stockin_batch,
        (
            SELECT g.prodgal_url
            FROM product_gallery g
            WHERE g.prodgal_prodpack = r.prodpack_id
              AND g.prodgal_placedat = 1
              AND g.prodgal_medium = 1
              AND g.prodgal_publish = 1
              AND g.prodgal_status = 1
            ORDER BY g.prodgal_serial ASC
            LIMIT 1
        ) AS product_imageurl,
        e.strstk_discount,
        e.strstk_id,
        e.strstk_item,
        GetProductTotalQuantity(prdid, e.strstk_item, e.strstk_id) AS Totlval,

        ROW_NUMBER() OVER (
            PARTITION BY e.strstk_item
            ORDER BY
                s.stockin_expiry ASC,
                e.strstk_discount DESC,
                (e.strstk_stock - e.strstk_reserved) DESC
        ) AS rn

    FROM products_tbl p
    JOIN product_packing r 
        ON r.prodpack_product = p.product_id
    JOIN packing_tbl t 
        ON t.packing_id = r.prodpack_package
    JOIN measure_units m 
        ON m.measunit_id = r.prodpack_unit
    JOIN stock_inwards s 
        ON s.stockin_item = r.prodpack_id
    JOIN storestock_pricing e 
        ON e.strstk_item = r.prodpack_id
       AND s.stockin_id = e.strstk_refer

    WHERE p.product_status = 1
      AND p.product_online = 1
      AND p.product_publish = 1
      AND e.strstk_item = packid
      AND (e.strstk_stock - e.strstk_reserved) > 0
      AND s.stockin_expiry >= CURRENT_DATE()
      AND e.strstk_product = prdid
      AND FIND_IN_SET(e.strstk_id, strArray) = 0
) ranked
WHERE rn = 1;
    END IF;
   
END$$

CREATE  PROCEDURE `updateViewcart1` (IN `qty` INT, IN `packid` INT, IN `stockid` INT, IN `prdid` INT)   BEGIN
  DECLARE qtys, strk, balance, stck INT DEFAULT 0;
    DECLARE mrp, msp, disc DOUBLE DEFAULT 0;
    DECLARE strarray, totalstock TEXT DEFAULT ''; -- Initialize empty string

    -- Assign stockid to strarray (Ensure it's a string)
    SET strarray = CAST(stockid AS CHAR);

    -- Fetch initial values
    SELECT e1.strstk_mrp, e1.strstk_msp, e1.strstk_discount, 
           (e1.strstk_stock - e1.strstk_reserved), e1.strstk_id 
    INTO mrp, msp, disc, qtys, strk 
    FROM storestock_pricing e1
    JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer
    WHERE e1.strstk_product = prdid  
      AND e1.strstk_item = packid 
      AND e1.strstk_id = stockid;
     SET totalstock = concat(strk,"|",if (qty>=qtys , qtys, qty ),'#'); 
       -- Calculate initial balance
    SET balance = if(qty>=qtys, ABS(qty - qtys),0);  -- Assuming qty is not declared
-- Process while balance is greater than zero
    while(balance > 0) do

    if EXISTS(SELECT COALESCE(strstk_id, 0), COALESCE(stock_available, 0) 
        /*INTO strk, stck*/
        FROM (
            SELECT e1.strstk_item, 
                   s1.stockin_expiry, 
                   e1.strstk_discount AS max_discount, 
                   (e1.strstk_stock - e1.strstk_reserved) AS stock_available, 
                   e1.strstk_mrp, 
                   e1.strstk_msp, 
                   e1.strstk_id, 
                   e1.strstk_product 
            FROM storestock_pricing e1 
            JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer 
            WHERE e1.strstk_product = prdid 
              AND (e1.strstk_stock - e1.strstk_reserved) > 0 
              AND s1.stockin_expiry >= CURRENT_DATE() 
              AND e1.strstk_item = packid
        ) AS x
        WHERE x.stock_available > 0 
          AND x.stockin_expiry >= CURRENT_DATE() 
          AND x.strstk_mrp = CAST(mrp AS DECIMAL(10,2)) 
          AND x.strstk_msp = CAST(msp AS DECIMAL(10,2)) 
          AND x.max_discount = CAST(disc AS DECIMAL(10,2)) 
          AND FIND_IN_SET(x.strstk_id, strarray) = 0  -- Fix NOT IN issue
        ORDER BY x.stockin_expiry ASC, x.max_discount DESC, x.stock_available DESC 
        LIMIT 1)THEN
         SELECT COALESCE(strstk_id, 0), COALESCE(stock_available, 0) 
         INTO strk, stck 
        FROM (
            SELECT e1.strstk_item, 
                   s1.stockin_expiry, 
                   e1.strstk_discount AS max_discount, 
                   (e1.strstk_stock - e1.strstk_reserved) AS stock_available, 
                   e1.strstk_mrp, 
                   e1.strstk_msp, 
                   e1.strstk_id, 
                   e1.strstk_product 
            FROM storestock_pricing e1 
            JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer 
            WHERE e1.strstk_product = prdid 
              AND (e1.strstk_stock - e1.strstk_reserved) > 0 
              AND s1.stockin_expiry >= CURRENT_DATE() 
              AND e1.strstk_item = packid
        ) AS x
        WHERE x.stock_available > 0 
          AND x.stockin_expiry >= CURRENT_DATE() 
          AND x.strstk_mrp = CAST(mrp AS DECIMAL(10,2)) 
          AND x.strstk_msp = CAST(msp AS DECIMAL(10,2)) 
          AND x.max_discount = CAST(disc AS DECIMAL(10,2)) 
          AND FIND_IN_SET(x.strstk_id, strarray) = 0  -- Fix NOT IN issue
        ORDER BY x.stockin_expiry ASC, x.max_discount DESC, x.stock_available DESC 
        LIMIT 1;
        else 
           SET strk = 0, stck = 0;
    
        end if;
        
        -- Append strk to strarray
      
        if(stck = 0)THEN
         set balance = 0;
        else
            SET strarray = CONCAT(strarray, ',', strk);
            SET totalstock = concat(totalstock,"",strk,"|",if (balance>=stck, stck, ABS(balance) ),"#");
            -- Reduce balance
            SET balance = balance - IFNULL(stck, 0);
        end IF;
    -- Append strk to strarray
     -- Initialize variables
	#SET strk = 0, stck = 0;
    END while;  
    SELECT totalstock;
    
END$$

CREATE  PROCEDURE `uploadInvoiceFile` (IN `invid` INT, IN `invurl` VARCHAR(100), IN `adminid` INT)   BEGIN
	INSERT INTO invoice_files( invfile_invoice, invfile_url, invfile_crtdby )
    VALUES( invid, invurl, adminid);
END$$

CREATE  PROCEDURE `userChangePasswordbyId` (IN `customer_id` INT, IN `old_password` VARCHAR(255), IN `new_password` VARCHAR(255))   BEGIN
IF EXISTS(SELECT 1 FROM customers_tbl c WHERE c.customer_password=old_password and c.customer_id=customer_id AND c.customer_type=1) THEN

UPDATE customers_tbl c SET c.customer_password=new_password, c.customer_updby=customer_id WHERE c.customer_id=customer_id AND c.customer_type=1;
SELECT 1 as statuss;
ELSE
SELECT 0 as statuss;
END IF;
END$$

CREATE  PROCEDURE `verifyuserByTrackID` (IN `orderId` VARCHAR(255), IN `phone` VARCHAR(255))   BEGIN
DECLARE userid,types INT DEFAULT 0;
IF EXISTS(SELECT o.order_orderid FROM delivery_address d JOIN  orders_tbl o ON o.order_deliverId=d.delivery_id AND d.delivery_user=o.order_customer JOIN customers_tbl c ON c.customer_id=o.order_customer WHERE (d.delivery_phone=phone  OR c.customer_phone=phone) AND o.order_orderid=orderId) THEN
SELECT c.customer_type INTO types from customers_tbl c JOIN orders_tbl o ON o.order_customer=c.customer_id WHERE o.order_orderid=orderId;
SELECT c.customer_id INTO userid from customers_tbl c JOIN orders_tbl o ON o.order_customer=c.customer_id WHERE o.order_orderid=orderId;

SELECT userid as userId, types as type ;
ELSE
SELECT null;
END IF;
END$$

--
-- Functions
--
CREATE  FUNCTION `fnCreateGDNnumber` (`storeid` INT) RETURNS VARCHAR(50) CHARSET utf8mb4  BEGIN
	DECLARE nextorder VARCHAR(50) DEFAULT '';
         SELECT CONCAT(
    COALESCE((SELECT y.store_code FROM stores_tbl y WHERE y.store_id = storeid), ''),
    '/',
    'GDN',
    '/',
    (SELECT COUNT(*) +1
     FROM transfer_packets x
     WHERE x.transpack_from = storeid AND x.transpack_gdn != '')
) INTO nextorder;
    	RETURN nextorder;
END$$

CREATE  FUNCTION `fnCreateGRNnumber` (`storeid` INT) RETURNS VARCHAR(50) CHARSET utf8mb4  BEGIN
	DECLARE nextorder VARCHAR(50) DEFAULT '';
         SELECT CONCAT(
    COALESCE((SELECT y.store_code FROM stores_tbl y WHERE y.store_id = storeid), ''),
    '/',
    'GRN',
    '/',
    (SELECT COUNT(*) +1
     FROM transfer_packets x
     WHERE x.transpack_to = storeid AND x.transpack_grn != '')
) INTO nextorder;
    	RETURN nextorder;
END$$

CREATE  FUNCTION `fnCreateIntendNumber` (`storeid` INT) RETURNS VARCHAR(50) CHARSET utf8mb4  BEGIN
	DECLARE nextorder VARCHAR(50) DEFAULT '';
    
        SELECT CONCAT('INTD-', COALESCE((SELECT y.store_code FROM stores_tbl y WHERE y.store_id = storeid), ' '), COUNT(*)+1) 		INTO nextorder 
        FROM  intends_tbl x 
        WHERE x.intend_from = storeid; 
   
    	RETURN nextorder;
END$$

CREATE  FUNCTION `fnCreatePurchaseOrder` (`supplier` INT, `suppliertype` INT, `storeto` INT, `strorder` TEXT, `odrmode` INT, `adminid` INT) RETURNS INT  BEGIN
	DECLARE insid, ordid, ordtotal, orditem INT DEFAULT 0;
    DECLARE strtrans, stritems,notes TEXT DEFAULT '';
    DECLARE stkid, stkitem INT DEFAULT 0;
    DECLARE license,amount,deliverby INT DEFAULT 0;

    SET @text := TRIM(BOTH '##' FROM strorder);
  	SET @strLen := 0;
  	SET @i := 1;
      WHILE @strLen < LENGTH(@text) DO
    	SET @str := SUBSTRING_INDEX(@text, '##', @i);
    	SET @strLen := LENGTH(@str);
    	SET @i := @i + 1;
    	SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
     	SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 	SET @strGLen := 0;
     	SET @Gi := 1;
     
     	SET @icols := 1;
     	WHILE @strGLen < LENGTH(@GRAPE) DO
        	SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
        	SET @strGLen := LENGTH(@Gstr);
        	SET @Gi := @Gi + 1;
        	IF @icols = 1 THEN
        		SET @item := SUBSTRING_INDEX(@Gstr, '|', -1);
                SET stritems = IF(stritems = '', @item, CONCAT_WS(',', stritems, @item));
            ELSEIF @icols=2 THEN
            	SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
        	ELSE
            	SET @price := SUBSTRING_INDEX(@Gstr, '|', -1);
        	END IF;
        	SET @icols := @icols + 1;
     	END WHILE;
        IF strtrans = '' THEN
        	SET strtrans = CONCAT( @item, '|',@qty , '|', @price);
        ELSE            
        	SET strtrans = CONCAT(strtrans, '##', @item, '|',@qty , '|', @price);	                
        END IF;
        
      END WHILE;
     
       IF TRIM(strtrans) <> '' THEN
     		CALL addPurchaseOrder(fnGeneratePurchaseOrderNumber(odrmode,storeto), CURRENT_DATE(),license,suppliertype,supplier,amount,strtrans,notes,storeto,deliverby,adminid);
     	SET insid = LAST_INSERT_ID();     
        SELECT x.podetail_order INTO ordid FROM purchase_details x WHERE x.podetail_id = insid;
  	END IF;
    RETURN ordid;
END$$

CREATE  FUNCTION `fnCreateTransferOrder` (`storefrom` INT, `storeto` INT, `strorder` TEXT, `adminid` INT) RETURNS INT  BEGIN
	DECLARE finish, ordcount, ordqty, insid, ordid, ordtotal, orditem INT DEFAULT 0;
    DECLARE batch VARCHAR(50) DEFAULT '';
    DECLARE expiry DATE DEFAULT NULL;
    DECLARE strtrans, stritems, test TEXT DEFAULT '';
    DECLARE stkid, stkitem, store, stock, minstk INT DEFAULT 0;
      
	SET @text := TRIM(BOTH '##' FROM strorder);
  	SET @strLen := 0;
  	SET @i := 1;
  	WHILE @strLen < LENGTH(@text) DO
    	SET @str := SUBSTRING_INDEX(@text, '##', @i);
    	SET @strLen := LENGTH(@str);
    	SET @i := @i + 1;
    	SET @GRPS := SUBSTRING_INDEX(@str, '##', -1);
     	SET @GRAPE := TRIM(BOTH '|' FROM @GRPS);
  	 	SET @strGLen := 0;
     	SET @Gi := 1;
     
     	SET @icols := 1;
     	WHILE @strGLen < LENGTH(@GRAPE) DO
        	SET @Gstr := SUBSTRING_INDEX(@GRAPE, '|', @Gi);
        	SET @strGLen := LENGTH(@Gstr);
        	SET @Gi := @Gi + 1;
        	IF @icols = 1 THEN
        		SET @item := SUBSTRING_INDEX(@Gstr, '|', -1);
                SET stritems = IF(stritems = '', @item, CONCAT_WS(',', stritems, @item));
        	ELSE
            	SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
        	END IF;
        	SET @icols := @icols + 1;
     	END WHILE;
        
        BLOCK2:BEGIN
        	DECLARE stcurs CURSOR FOR SELECT sp.strstk_id, si.stockin_batch, si.stockin_expiry, sp.strstk_item, sp.strstk_store, (sp.strstk_stock - sp.strstk_reserved) AS stock, sm.storestock_min, @qty 
        	FROM storestock_pricing sp 
        	LEFT JOIN stock_inwards si ON si.stockin_id = sp.strstk_refer
            LEFT JOIN storestock_master sm ON sm.storestock_item = sp.strstk_item AND sm.storestock_store = sp.strstk_store
        	WHERE sp.strstk_item = @item AND sp.strstk_store = storefrom AND (sp.strstk_stock - sp.strstk_reserved)>0
        	ORDER BY si.stockin_expiry ASC, stock;
    		DECLARE CONTINUE HANDLER FOR NOT FOUND SET finish = 1;
	        SET ordtotal = 0;
            SET ordqty = 0;
            SET ordcount = 0;
            OPEN stcurs;
        	runorder:LOOP
        		FETCH stcurs INTO stkid, batch, expiry, stkitem, store, stock, minstk, ordcount;
        		IF finish = 1 THEN
            		SET finish = 0;
                    LEAVE runorder;
            	END IF;
            	#SELECT CONCAT(stkid,'|', batch,'|', expiry,'|', stkitem,'|',  store,'|',  stock,'|',  minstk,'|',  @qty) INTO test;
                
                
               /* IF stock > minstk AND ordcount > 0 THEN
                	IF strtrans = '' THEN
                		SET ordqty = IF(stock >= ordcount, ordcount, stock);
                		SET strtrans = CONCAT(stkid, '|', @item, '|', ordqty, '|', batch, '|', expiry);
                     	SET ordtotal = ordqty;
                    ELSE
                    	IF ordtotal < ordcount THEN
                        	SET ordqty = IF(stock >= (ordcount - ordqty), (ordcount - ordqty), stock);
                    		SET strtrans = CONCAT(strtrans, '##', stkid, '|', @item, '|', ordqty, '|', batch, '|', expiry);
                    		SET ordtotal = ordtotal + (ordcount - ordqty);
                        ELSE
                        	SET ordtotal = ordcount;
                        END IF;
                    END IF;
                END IF;*/
                
                IF stock > minstk AND ordcount > 0 THEN

                    SET @remaining = ordcount - ordtotal;

                    IF @remaining > 0 THEN

                        SET ordqty = IF(stock >= @remaining, @remaining, stock);

                        -- Prevent zero quantity
                        IF ordqty > 0 THEN

                            IF strtrans = '' THEN
                                SET strtrans = CONCAT(
                                    stkid, '|', @item, '|', ordqty, '|', batch, '|', IFNULL(expiry, '')
                                );
                            ELSE
                                SET strtrans = CONCAT(
                                    strtrans, '##',
                                    stkid, '|', @item, '|', ordqty, '|', batch, '|', IFNULL(expiry, '')
                                );
                            END IF;

                            SET ordtotal = ordtotal + ordqty;

                        END IF;

                    END IF;

                END IF;
            END LOOP runorder;
            SET finish = 0;
	        CLOSE stcurs;
        END BLOCK2;
    END WHILE;  
    IF TRIM(strtrans) <> '' THEN
        CALL addStockTransferOrderNew(fnGenerateTransferOrderNumber(storefrom), CURRENT_DATE(), storefrom, storeto, strtrans, adminid, '');
        SET insid = LAST_INSERT_ID();
        SELECT x.stockorder_refer INTO ordid FROM stocktransfer_details x WHERE x.stockorder_id = insid;
  	END IF;
    RETURN ordid;

END$$

CREATE  FUNCTION `fnGenerateBillNumber` (`storeid` INT) RETURNS VARCHAR(50) CHARSET utf8mb4  BEGIN
    DECLARE nextorder VARCHAR(50) DEFAULT '';
    
 SELECT CONCAT('bill_', 
              COALESCE((SELECT y.store_code FROM stores_tbl y WHERE y.store_id = storeid), ' '),' - ',
              COUNT(*) + 1) INTO nextorder 
FROM bills_table x 
WHERE x.bill_store = storeid;
        RETURN nextorder;
END$$

CREATE  FUNCTION `fnGeneratePurchaseOrderNumber` (`ordmode` INT, `storeid` INT) RETURNS VARCHAR(50) CHARSET utf8mb4  BEGIN
	DECLARE nextorder VARCHAR(50) DEFAULT '';
    IF (ordmode = 1) THEN
        SELECT CONCAT('POID-', COALESCE((SELECT y.store_code FROM stores_tbl y WHERE y.store_id = storeid), ' '), 					COUNT(*)+1) 		INTO nextorder 
        FROM purchase_orders x 
        WHERE x.purchord_deliverat = storeid; 
    ELSE
      	SELECT CONCAT('PO_TEL-', COALESCE((SELECT y.store_code FROM stores_tbl y WHERE y.store_id = storeid), ' '), 				COUNT(*)+1) 			INTO nextorder 
        FROM purchase_orders x 
        WHERE x.purchord_deliverat = storeid; 
        
    END IF;
    	RETURN nextorder;
END$$

CREATE  FUNCTION `fnGenerateTransferOrderNumber` (`storeid` INT) RETURNS VARCHAR(50) CHARSET utf8mb4  BEGIN
	DECLARE nextorder VARCHAR(50) DEFAULT '';
    
    SELECT CONCAT('IDTR', COALESCE((SELECT y.store_code FROM stores_tbl y WHERE y.store_id = storeid), ' '), COUNT(*)+1) INTO nextorder 
    FROM stock_transfers x 
    WHERE x.stocktrans_strfrom = storeid; 
    RETURN nextorder;
END$$

CREATE  FUNCTION `fnGetDrugclassParent` (`drgclsid` INT) RETURNS INT  BEGIN
	DECLARE cpid, spid INT DEFAULT 0;
    
	SELECT x.drugclass_parent INTO cpid 
    FROM drug_classifications x 
    WHERE x.drugclass_id = drgclsid;
    
    IF cpid > 0 THEN
    	SELECT y.drugclass_parent INTO spid
    	FROM drug_classifications y
   	 	WHERE y.drugclass_id = cpid;
    END IF;
    
    RETURN spid;
END$$

CREATE  FUNCTION `fnGetProductclassParent` (`prdclsid` INT) RETURNS INT  BEGIN
	DECLARE cpid, spid INT DEFAULT 0;
    
	SELECT x.prodclass_parent INTO cpid 
    FROM product_classes_seq x 
    WHERE x.prodclass_id = prdclsid;
    
    IF cpid > 0 THEN
    	SELECT y.prodclass_parent INTO spid
    	FROM product_classes_seq y
   	 	WHERE y.prodclass_id = cpid;
    END IF;
    
    RETURN spid;
END$$

CREATE  FUNCTION `fnGetProductFromPack` (`packid` INT, `flag` INT) RETURNS VARCHAR(200) CHARSET utf8mb4  BEGIN
	DECLARE prodkt INT DEFAULT 0;
    DECLARE packfull, packshort, product VARCHAR(200) DEFAULT NULL;
    DECLARE resp VARCHAR(200) DEFAULT NULL;
	
    SELECT x.prodpack_product, 
    	CONCAT(p.product_name, ' ', k.packing_type, ':', x.prodpack_quantity, ' ', m.measunit_name), 
        CONCAT(p.product_name, ' ', k.packing_type, ':', x.prodpack_quantity, ' ', m.measunit_shortname) 
        INTO prodkt, packfull, packshort 
    FROM product_packing x 
    LEFT JOIN products_tbl p ON p.product_id = x.prodpack_product 
    LEFT JOIN packing_tbl k ON k.packing_id = x.prodpack_package 
    LEFT JOIN measure_units m ON m.measunit_id = x.prodpack_unit 
    WHERE x.prodpack_id = packid;
    
    IF flag = '0' THEN
    	RETURN packshort;
    ELSEIF flag = 1 THEN
    	RETURN packfull;
    ELSE
    	RETURN prodkt;
    END IF;
END$$

CREATE  FUNCTION `fnGetPurchaseOrderStatus` (`poid` INT) RETURNS INT  BEGIN
	DECLARE pstatus, aproved, issued, retval INT DEFAULT 0;
	
    SELECT x.purchord_status, x.purchord_aprvdby, x.purchord_issuedby INTO pstatus, aproved, issued 
    FROM purchase_orders x WHERE x.purchord_id = poid;
    
    IF pstatus = 0 THEN
    	SET retval = 0;
    ELSEIF pstatus = 1 THEN
    	IF aproved > 0 THEN
        	SET retval = 2;
        ELSEIF issued > 0 THEN
        	SET retval = 3;
        ELSE
        	SET retval = 1;
        END IF;
    ELSEIF pstatus = 5 THEN
    	SET retval = 5;
    ELSE	
    	SET retval = 10;
    END IF;
    
    RETURN retval;
END$$

CREATE  FUNCTION `fnGetStoreStock` (`storeid` INT, `stockid` INT) RETURNS INT  BEGIN
	DECLARE stocks INT DEFAULT 0;
    IF storeid > 0 THEN
		SELECT (x.storestock_available - x.storestock_reserved) INTO stocks 
        FROM storestock_master x 
    	WHERE x.storestock_item = stockid AND x.storestock_store = storeid;
	ELSE
    	SELECT SUM(x.storestock_available - x.storestock_reserved) INTO stocks 
        FROM storestock_master x 
    	WHERE x.storestock_item = stockid;
    END IF;

    RETURN IFNULL(stocks, 0);
END$$

CREATE  FUNCTION `fnGetSupplierCountForItem` (`prodid` INT) RETURNS INT  BEGIN
	DECLARE dcount, dlcount, stkcount INT DEFAULT 0;
	
    SELECT COUNT(*) into stkcount FROM stockist_products st 
    WHERE st.stockistprod_product = prodid AND st.stockistprod_status = 1;
    SELECT COUNT(*) INTO dcount FROM distributor_products dp 
    WHERE dp.distriprod_product = prodid AND dp.distriprod_status = 1;
    SELECT COUNT(*) into dlcount FROM dealer_products dl 
    WHERE dl.dealerprod_product = prodid AND dl.dealerprod_status = 1;
    
    RETURN (dcount + dlcount + stkcount);
    
END$$

CREATE  FUNCTION `fnGetVendorContacts` (`vtype` INT, `vendid` INT) RETURNS VARCHAR(200) CHARSET utf8mb4  BEGIN
	DECLARE vendor VARCHAR(200) DEFAULT '';
	IF vtype = 1 THEN
    	SELECT CONCAT(stockist_name, '|', stockist_email, '|', stockist_whatsapp, '|', stockist_phones) INTO vendor 
        FROM stockists_tbl WHERE stockist_id = vendid;
    ELSEIF VTYPE = 2 THEN
    	SELECT CONCAT(distri_name, '|', distri_email, '|', distri_whatsapp, '|', distri_phones) INTO vendor 
        FROM distributors_tbl WHERE distri_id = vendid;
    ELSE
    	SELECT CONCAT(dealer_name, '|', dealer_email, '|', dealer_whatsapp, '|', dealer_phones) INTO vendor 
        FROM dealers_tbl WHERE dealer_id = vendid;
    END IF;
    
    RETURN vendor;
END$$

CREATE  FUNCTION `fnGetVendorLicense` (`vtype` INT, `vendid` INT) RETURNS VARCHAR(200) CHARSET utf8mb4  BEGIN
	DECLARE license VARCHAR(200) DEFAULT '';
	IF vtype = 1 THEN
    	SELECT stockist_regn INTO license 
        FROM stockists_tbl WHERE stockist_id = vendid;
    ELSEIF VTYPE = 2 THEN
    	SELECT distri_regn INTO license 
        FROM distributors_tbl WHERE distri_id = vendid;
    ELSE
    	SELECT dealer_regn INTO license 
        FROM dealers_tbl WHERE dealer_id = vendid;
    END IF;
    
    RETURN license;
END$$

CREATE  FUNCTION `fnGetVendorName` (`vtype` INT, `vendid` INT) RETURNS VARCHAR(200) CHARSET utf8mb4  BEGIN
	DECLARE vendor VARCHAR(200) DEFAULT '';
	IF vtype = 1 THEN
    	SELECT stockist_name INTO vendor 
        FROM stockists_tbl WHERE stockist_id = vendid;
    ELSEIF VTYPE = 2 THEN
    	SELECT distri_name INTO vendor 
        FROM distributors_tbl WHERE distri_id = vendid;
    ELSE
    	SELECT dealer_name INTO vendor 
        FROM dealers_tbl WHERE dealer_id = vendid;
    END IF;
    
    RETURN vendor;
END$$

CREATE  FUNCTION `GetProductTotalQuantity` (`prdid` INT, `packid` INT, `stockid` INT) RETURNS INT  BEGIN
    DECLARE qtys, strk,TotalStock INT DEFAULT 0;
    DECLARE mrp, msp, disc DOUBLE DEFAULT 0;
    DECLARE strArray TEXT; 
    
    SELECT e1.strstk_mrp, e1.strstk_msp, e1.strstk_discount, 
           (e1.strstk_stock - e1.strstk_reserved), e1.strstk_id 
    INTO mrp, msp, disc, qtys, strk 
    FROM storestock_pricing e1
    JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer
    WHERE e1.strstk_product = prdid  
      AND e1.strstk_item = packid 
      AND e1.strstk_id = stockid;
     
     SELECT SUM(x.stock_available) INTO TotalStock
FROM (
    SELECT e1.strstk_item, 
           s1.stockin_expiry, 
           e1.strstk_discount AS max_discount, 
           (e1.strstk_stock - e1.strstk_reserved) AS stock_available, 
           e1.strstk_mrp, 
           e1.strstk_msp, 
           e1.strstk_id, 
           e1.strstk_product 
    FROM storestock_pricing e1 
    JOIN stock_inwards s1 ON s1.stockin_id = e1.strstk_refer 
    WHERE e1.strstk_product = prdid 
      AND (e1.strstk_stock - e1.strstk_reserved) > 0 
      AND s1.stockin_expiry >= CURRENT_DATE() 
      AND e1.strstk_item = packid
) AS x
WHERE x.stock_available > 0 
  AND x.stockin_expiry >= CURRENT_DATE() 
   AND x.strstk_mrp = CAST(mrp AS DECIMAL(10,2)) 
  AND x.strstk_msp = CAST(msp AS DECIMAL(10,2)) 
  AND x.max_discount = CAST(disc AS DECIMAL(10,2))
 GROUP BY x.strstk_product
ORDER BY x.stockin_expiry ASC, x.max_discount DESC, x.stock_available DESC;
      
RETURN TotalStock;
    
END$$

DELIMITER ;

-- --------------------------------------------------------

--
