-- https://www.phpmyadmin.net/
--

START TRANSACTION;



--
-- Database: `ddcph_ddcpharmacy`
--

DELIMITER $$
--
-- Procedures
--
CREATE  PROCEDURE `activateUserbyOTP` (IN `userid` INT)   BEGIN

END$$

CREATE  PROCEDURE `addAdvertisements` (IN `adtype` INT, IN `adtitle` VARCHAR(255), IN `adowner` VARCHAR(255), IN `adbrand` INT, IN `adfromdate` DATE, IN `addateto` DATE, IN `adproduct` INT, IN `admainctgory` INT, IN `adsubctgory` INT, IN `adcatogry` INT, IN `adcontent` TEXT, IN `adlogo` VARCHAR(255), IN `adurl` VARCHAR(255), IN `adpublish` INT, IN `adstatus` INT, IN `adoffer` INT, IN `homepagestat` INT, IN `maincatstat` INT, IN `subcatstat` INT, IN `catstatus` INT, IN `adminid` INT)   BEGIN  

	DECLARE lid INT DEFAULT 0;
	INSERT INTO advertisements_tbl(advt_type,advt_title,advt_owner,advt_brand,advt_datefrom,advt_dateto,advt_products,advt_maincategories,advt_subcategories, advt_catgory,advt_content, advt_image, advt_linkedurl,advt_publish, advt_status,advt_offer,advt_hompagestatus,advt_maincatstatus,advt_subcatstatus,advt_catstatus, advt_crtdby, advt_crtdon) VALUES (adtype,adtitle,adowner,adbrand,adfromdate,addateto,adproduct,admainctgory,adsubctgory,adcatogry,adcontent,adlogo,adurl,adpublish,adstatus,adoffer,homepagestat,maincatstat,subcatstat,catstatus,adminid,CURRENT_TIMESTAMP());
    
    SET lid = LAST_INSERT_ID();
END$$

CREATE  PROCEDURE `addAdvice` (IN `qtype` INT, IN `qitem` INT, IN `advice` TEXT, IN `adminid` INT)   BEGIN
	DECLARE adid INT DEFAULT 0;
    
	INSERT INTO advices_table  
    (advice_type, advice_item, advice_content, advice_crtdby)
    VALUES(qtype, qitem, advice, adminid);
    
    SET adid = LAST_INSERT_ID();
    SELECT adid;
END$$

CREATE  PROCEDURE `addbillStock` (IN `storeid` INT, IN `itemid` INT, IN `batch` VARCHAR(255))   BEGIN
SELECT bill_stock FROM billstock_tbl b  WHERE  billstore_id =storeid AND billstock_item=itemid AND bill_batch=batch;
END$$

CREATE  PROCEDURE `addBrandManufactureDuplicate` (IN `brandId` VARCHAR(225), IN `manufId` INT)   BEGIN  
INSERT INTO brand_manufacturer_tbl (brnd_id, brndmanu_id)
SELECT b.brand_id, b.brand_owner
FROM brands_tbl b
WHERE b.brand_id = brandId AND b.brand_owner=manufId AND b.brand_status=1;
UPDATE brands_tbl b SET b.brand_duplicate=1 WHERE b.brand_id = brandId AND b.brand_owner=manufId AND b.brand_status=1;
END$$

CREATE  PROCEDURE `addCartDataToOrderDetails` (IN `custmrid` INT, IN `orderno` VARCHAR(20), IN `razorpayid` VARCHAR(20), IN `amount` DECIMAL(11,2), IN `trnstnid` VARCHAR(50), IN `delvid` INT)   BEGIN
DECLARE ordid ,ord_ids ,store,item INT DEFAULT 0;
DECLARE resultString ,resultQty ,singleValue,singleQty TEXT;
 /* insert into order table Table */
  INSERT INTO orders_tbl(order_customer,order_deliverId,order_orderid,order_razorpayid ,order_source, order_paidby,order_shipby,order_subtotal,order_updby, order_updon) VALUES(custmrid,delvid,orderno,razorpayid,1,custmrid,NULL,amount,1,CURRENT_TIMESTAMP);
     SET ordid = LAST_INSERT_ID();
/* insert into Payment Table */
    INSERT INTO payments_tbl(paymt_orderid,paymt_userid,paymt_paid,paymt_paidon,paymt_paidby,paymt_transid)
    VALUES (ordid,custmrid,amount,CURRENT_TIMESTAMP,1,trnstnid);
   /* insert into order details Table */
     		/*INSERT INTO order_details(ordet_order,ordet_cartid, ordet_productid, ordet_quantity, ordet_producpackid, order_batchid) SELECT ordid,cart_id,product_id,quantity,prodpack_id,batch_id FROM user_cart WHERE user_id=custmrid;
       */
       CALL AllocateProductStock(custmrid,ordid);
       SELECT order_id  INTO ord_ids FROM orders_tbl WHERE order_customer=custmrid ORDER BY order_id DESC LIMIT 1;
    SELECT GROUP_CONCAT(order_batchid) INTO resultString FROM order_details WHERE ordet_order=ord_ids;
    SELECT GROUP_CONCAT(ordet_quantity) INTO resultQty FROM order_details WHERE ordet_order=ord_ids;
 WHILE resultString IS NOT NULL AND resultString != '' DO
        SET singleValue = SUBSTRING_INDEX(resultString, ',', 1);
        SET singleQty = SUBSTRING_INDEX(resultQty, ',', 1);
        SELECT strstk_store,strstk_item INTO store,item FROM storestock_pricing WHERE strstk_id =singleValue;
        UPDATE storestock_pricing SET strstk_reserved=strstk_reserved+singleQty WHERE strstk_id =singleValue;
        UPDATE storestock_master SET storestock_reserved=storestock_reserved+singleQty WHERE storestock_store = store AND storestock_item =item;
        -- Remove the processed value from resultString
        SET resultString = REPLACE(resultString, CONCAT(singleValue, ','), '');
        SET resultQty = REPLACE(resultQty, CONCAT(singleQty, ','), '');
        IF resultString = singleValue AND resultQty=singleQty  THEN
            SET resultString = '';
            SET resultQty='';
        END IF;
    END WHILE;
    DELETE FROM user_cart  WHERE user_id=custmrid AND order_id=0;
SELECT c.customer_phone as phone FROM customers_tbl c WHERE c.customer_id=custmrid;
END$$

CREATE  PROCEDURE `addCartDataToOrderDetailswithPrescription` (IN `custmrid` INT, IN `orderno` VARCHAR(20), IN `razorpayid` VARCHAR(20), IN `amount` DECIMAL(11,2), IN `trnstnid` VARCHAR(50), IN `delvid` INT, IN `checkval` INT)   BEGIN
DECLARE ordid ,ord_ids ,store,item INT DEFAULT 0;
DECLARE resultString ,resultQty ,singleValue,singleQty TEXT;
 /* insert into order table Table */
  INSERT INTO orders_tbl(order_customer,order_deliverId,order_orderid,order_razorpayid ,order_source, order_paidby,order_shipby,order_subtotal,order_prescription,order_updby, order_updon) VALUES(custmrid,delvid,orderno,razorpayid,1,custmrid,NULL,amount,checkval,1,CURRENT_TIMESTAMP);
     SET ordid = LAST_INSERT_ID();
/* insert into Payment Table */
    INSERT INTO payments_tbl(paymt_orderid,paymt_userid,paymt_paid,paymt_paidon,paymt_paidby,paymt_transid)
    VALUES (ordid,custmrid,amount,CURRENT_TIMESTAMP,1,trnstnid);
   /* insert into order details Table */
     		/*INSERT INTO order_details(ordet_order,ordet_cartid, ordet_productid, ordet_quantity, ordet_producpackid, order_batchid) SELECT ordid,cart_id,product_id,quantity,prodpack_id,batch_id FROM user_cart WHERE user_id=custmrid;
       */
       CALL AllocateProductStock(custmrid,ordid);
       SELECT order_id  INTO ord_ids FROM orders_tbl WHERE order_customer=custmrid ORDER BY order_id DESC LIMIT 1;
    SELECT GROUP_CONCAT(order_batchid) INTO resultString FROM order_details WHERE ordet_order=ord_ids;
    SELECT GROUP_CONCAT(ordet_quantity) INTO resultQty FROM order_details WHERE ordet_order=ord_ids;
 WHILE resultString IS NOT NULL AND resultString != '' DO
        SET singleValue = SUBSTRING_INDEX(resultString, ',', 1);
        SET singleQty = SUBSTRING_INDEX(resultQty, ',', 1);
        SELECT strstk_store,strstk_item INTO store,item FROM storestock_pricing WHERE strstk_id =singleValue;
        UPDATE storestock_pricing SET strstk_reserved=strstk_reserved+singleQty WHERE strstk_id =singleValue;
        UPDATE storestock_master SET storestock_reserved=storestock_reserved+singleQty WHERE storestock_store = store AND storestock_item =item;
        -- Remove the processed value from resultString
        SET resultString = REPLACE(resultString, CONCAT(singleValue, ','), '');
        SET resultQty = REPLACE(resultQty, CONCAT(singleQty, ','), '');
        IF resultString = singleValue AND resultQty=singleQty  THEN
            SET resultString = '';
            SET resultQty='';
        END IF;
    END WHILE;
    DELETE FROM user_cart  WHERE user_id=custmrid AND order_id=0;
    SELECT ordid, c.customer_phone as phone FROM customers_tbl c WHERE c.customer_id=custmrid;

END$$

CREATE  PROCEDURE `addCartDataToOrderDetailswithPrescriptionbyOrderID` (IN `custmrid` INT, IN `orderno` VARCHAR(20), IN `razorpayid` VARCHAR(20), IN `amount` DECIMAL(11,2), IN `trnstnid` VARCHAR(50), IN `delvid` INT)   BEGIN
DECLARE ordid ,ord_ids ,store,item INT DEFAULT 0;
DECLARE resultString ,resultQty ,singleValue,singleQty TEXT;
 /* insert into order table Table */
  
     
     SELECT o.order_id INTO ordid from orders_tbl o WHERE o.order_orderid=orderno AND o.order_customer=custmrid;
     
     UPDATE orders_tbl o SET o.order_razorpayid=razorpayid,o.order_source=1,o.order_delivery=1,o.order_subtotal=amount,o.order_quick=0,o.order_updby=custmrid WHERE o.order_customer=custmrid AND o.order_orderid=orderno;
     
/* insert into Payment Table */
    INSERT INTO payments_tbl(paymt_orderid,paymt_userid,paymt_paid,paymt_paidon,paymt_paidby,paymt_transid)
    VALUES (ordid,custmrid,amount,CURRENT_TIMESTAMP,1,trnstnid);
   /* insert into order details Table */
     		/*INSERT INTO order_details(ordet_order,ordet_cartid, ordet_productid, ordet_quantity, ordet_producpackid, order_batchid) SELECT ordid,cart_id,product_id,quantity,prodpack_id,batch_id FROM user_cart WHERE user_id=custmrid;
       */
       CALL AllocateProductStockk(custmrid,ordid);
       SELECT order_id  INTO ord_ids FROM orders_tbl WHERE order_customer=custmrid AND order_orderid=orderno;
    SELECT GROUP_CONCAT(order_batchid) INTO resultString FROM order_details WHERE ordet_order=ord_ids;
    SELECT GROUP_CONCAT(ordet_quantity) INTO resultQty FROM order_details WHERE ordet_order=ord_ids;
 WHILE resultString IS NOT NULL AND resultString != '' DO
        SET singleValue = SUBSTRING_INDEX(resultString, ',', 1);
        SET singleQty = SUBSTRING_INDEX(resultQty, ',', 1);
        SELECT strstk_store,strstk_item INTO store,item FROM storestock_pricing WHERE strstk_id =singleValue;
        UPDATE storestock_pricing SET strstk_reserved=strstk_reserved+singleQty WHERE strstk_id =singleValue;
        UPDATE storestock_master SET storestock_reserved=storestock_reserved+singleQty WHERE storestock_store = store AND storestock_item =item;
        -- Remove the processed value from resultString
        SET resultString = REPLACE(resultString, CONCAT(singleValue, ','), '');
        SET resultQty = REPLACE(resultQty, CONCAT(singleQty, ','), '');
        IF resultString = singleValue AND resultQty=singleQty  THEN
            SET resultString = '';
            SET resultQty='';
        END IF;
    END WHILE;
    DELETE FROM user_cart  WHERE user_id=custmrid AND order_id=ordid;
    SELECT orderno, c.customer_phone as phone FROM customers_tbl c WHERE c.customer_id=custmrid;

END$$

CREATE  PROCEDURE `addCourier` (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` LONGTEXT, IN `collect` LONGTEXT, 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) ) = 0 THEN
    		INSERT INTO couriers_tbl( courier_type, courier_staffid, courier_name, courier_mobile, courier_vehicle, courier_vehregn, courier_contact, courier_address, courier_gst, courier_tin, courier_phones, courier_whatsapp, courier_email, courier_url, courier_rates, courier_areas, courier_collect, courier_notes, courier_status, courier_crtdby ) 
            VALUES( ctype, staffid, cname, mobile, vehicle, regno, contact, address, gst, tin, phones, whatsapp, email, url, rates, areas, collect,notes, status,adminid );
        SET success = 1;
   	END IF;
    
    SELECT success;
END$$

CREATE  PROCEDURE `addDealer` (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 distid INT DEFAULT 0;
    DECLARE front TEXT DEFAULT '';
    DECLARE frontlen INT DEFAULT 0;
    DECLARE tempVal TEXT DEFAULT '';
    
	INSERT INTO dealers_tbl   
    ( dealer_name, dealer_address, dealer_phones, dealer_email, dealer_website, dealer_contact, dealer_contactno, dealer_contactemail, dealer_contactcell, dealer_whatsapp, dealer_contactat, dealer_regn, dealer_GST, dealer_TIN, dealer_remarks, dealer_status, dealer_crtdby )
	VALUES( dname, address, phones, email, website, contact, contactno, conemail, concell, whatsapp, contactat, regn, gstnum, tin, remarks, mstatus, adminid );
    
    SET distid = LAST_INSERT_ID();
    
    IF distid > 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 (distid, tempVal, 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 (distid, tempVal, adminid);
            SET products = INSERT(products, 1, frontlen + 1, '');
        END LOOP;
        
    END IF;
END$$

CREATE  PROCEDURE `addDeliverydetails` (IN `user_id` INT, IN `delivery_to` VARCHAR(200), IN `delivery_phone` VARCHAR(200), IN `customer_email` VARCHAR(200), IN `delivery_pin` VARCHAR(200), IN `delivery_house` TEXT, IN `delivery_street` TEXT, IN `delivery_landmark` TEXT, IN `delivery_city` VARCHAR(200), IN `delivery_state` VARCHAR(200), IN `delivery_type` INT, IN `guest_address` INT)   BEGIN
declare ids int;
DECLARE counts int;
IF (user_id IS NULL) THEN
SELECT COUNT(*) into counts FROM customers_tbl c WHERE c.customer_phone=delivery_phone and c.customer_type=0;
IF(counts>=1)THEN
SELECT c.customer_id into ids FROM customers_tbl c WHERE c.customer_phone=delivery_phone and c.customer_type=0;

 -- Check if the delivery address exists
        IF EXISTS (
            SELECT 1 
            FROM delivery_address d 
            WHERE d.delivery_user = ids 
              AND d.delivery_status = 1
            LIMIT 1
        ) THEN
           UPDATE delivery_address d SET d.delivery_to=delivery_to,d.delivery_email=customer_email,d.delivery_pin=delivery_pin,d.delivery_house=delivery_house,d.delivery_street=delivery_street,d.delivery_landmark=delivery_landmark,d.delivery_city=delivery_city,d.delivery_state=delivery_state,d.delivery_type=delivery_type WHERE d.delivery_user=ids;
        
        ELSE
            -- Insert new delivery address if none exists
           INSERT INTO `delivery_address`(`delivery_user`, `delivery_to`, `delivery_phone`,`delivery_email`, `delivery_pin`, `delivery_house`, `delivery_street`, `delivery_landmark`, `delivery_city`, `delivery_state`, `delivery_type`, `delivery_status`) VALUES (ids, delivery_to, delivery_phone,customer_email,delivery_pin, delivery_house, delivery_street, delivery_landmark, delivery_city, delivery_state, delivery_type, 1);    
        END IF;
SELECT ids as userId, 0 as type ;
ELSE

INSERT INTO `customers_tbl`( `customer_type`,`customer_phone`) VALUES (0,delivery_phone);
SET ids = LAST_INSERT_ID();
INSERT INTO `delivery_address`(`delivery_user`, `delivery_to`, `delivery_phone`,`delivery_email`, `delivery_pin`, `delivery_house`, `delivery_street`, `delivery_landmark`, `delivery_city`, `delivery_state`, `delivery_type`, `delivery_status`) VALUES (ids, delivery_to, delivery_phone,customer_email,delivery_pin, delivery_house, delivery_street, delivery_landmark, delivery_city, delivery_state, delivery_type, 1);
SELECT ids as userId, 0 as type ;
END IF;

ELSE
IF(guest_address!=0)THEN
UPDATE delivery_address d SET d.delivery_to=delivery_to,d.delivery_phone=delivery_phone,d.delivery_email=customer_email,d.delivery_pin=delivery_pin,d.delivery_house=delivery_house,d.delivery_street=delivery_street,d.delivery_landmark=delivery_landmark,d.delivery_city=delivery_city,d.delivery_state=delivery_state,d.delivery_type=delivery_type WHERE d.delivery_user=user_id and d.delivery_id=guest_address;
SELECT user_id as userId, 1 as type;
ELSE
SELECT COUNT(*) into counts FROM customers_tbl c WHERE c.customer_id=user_id and c.customer_type=1;
IF(counts=1)THEN
UPDATE delivery_address d SET d.delivery_status=0 WHERE d.delivery_user=user_id;
INSERT INTO `delivery_address`(`delivery_user`, `delivery_to`, `delivery_phone`,`delivery_email`, `delivery_pin`, `delivery_house`, `delivery_street`, `delivery_landmark`, `delivery_city`, `delivery_state`, `delivery_type`, `delivery_status`) VALUES (user_id, delivery_to, delivery_phone,customer_email,delivery_pin, delivery_house, delivery_street, delivery_landmark, delivery_city, delivery_state, delivery_type, 1);
SELECT user_id as userId, 1 as type;
ELSE 
SELECT "" as userId, "" as type;
END IF;
END IF;
END IF;
END$$

CREATE  PROCEDURE `addDeliverydetailsold` (IN `user_id` INT, IN `delivery_to` VARCHAR(200), IN `delivery_phone` VARCHAR(200), IN `customer_email` VARCHAR(200), IN `delivery_pin` VARCHAR(200), IN `delivery_house` TEXT, IN `delivery_street` TEXT, IN `delivery_landmark` TEXT, IN `delivery_city` VARCHAR(200), IN `delivery_state` VARCHAR(200), IN `delivery_type` INT, IN `guest_address` INT)   BEGIN
declare ids int;
DECLARE counts int;
if(user_id=null OR user_id="")THEN
if(guest_address=1)THEN
SELECT c.customer_id as userId, 0 as type FROM customers_tbl c WHERE c.customer_phone=delivery_phone and c.customer_type=0;
ELSE
SELECT COUNT(*) into counts FROM customers_tbl c WHERE c.customer_phone=delivery_phone and c.customer_type=0;
IF(counts=1)THEN
SELECT c.customer_id into ids FROM customers_tbl c WHERE c.customer_phone=delivery_phone and c.customer_type=0;
UPDATE delivery_address d SET d.delivery_status=0 WHERE d.delivery_user=ids;
INSERT INTO `delivery_address`(`delivery_user`, `delivery_to`, `delivery_phone`,`delivery_email`, `delivery_pin`, `delivery_house`, `delivery_street`, `delivery_landmark`, `delivery_city`, `delivery_state`, `delivery_type`, `delivery_status`) VALUES (ids, delivery_to, delivery_phone,customer_email,delivery_pin, delivery_house, delivery_street, delivery_landmark, delivery_city, delivery_state, delivery_type, 1);
SELECT ids as userId, 0 as type ;
ELSE

INSERT INTO `customers_tbl`( `customer_type`,`customer_phone`) VALUES (0,delivery_phone);
SET ids = LAST_INSERT_ID();
INSERT INTO `delivery_address`(`delivery_user`, `delivery_to`, `delivery_phone`,`delivery_email`, `delivery_pin`, `delivery_house`, `delivery_street`, `delivery_landmark`, `delivery_city`, `delivery_state`, `delivery_type`, `delivery_status`) VALUES (ids, delivery_to, delivery_phone,customer_email,delivery_pin, delivery_house, delivery_street, delivery_landmark, delivery_city, delivery_state, delivery_type, 1);
SELECT ids as userId, 0 as type ;
END IF;
END IF;
ELSE
SELECT COUNT(*) into counts FROM customers_tbl c WHERE c.customer_id=user_id;
IF(counts=1)THEN
INSERT INTO `delivery_address`(`delivery_user`, `delivery_to`, `delivery_phone`, `delivery_pin`, `delivery_house`, `delivery_street`, `delivery_landmark`, `delivery_city`, `delivery_state`, `delivery_type`, `delivery_status`) VALUES (user_id, delivery_to, delivery_phone,delivery_pin, delivery_house, delivery_street, delivery_landmark, delivery_city, delivery_state, delivery_type, 1);
SELECT user_id as userId, 1 as type;
ELSE 
SELECT "" as userId, "" as type;
END IF;
END IF;
END$$

CREATE  PROCEDURE `addDistributor` (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 distid INT DEFAULT 0;
    DECLARE front TEXT DEFAULT '';
    DECLARE frontlen INT DEFAULT 0;
    DECLARE tempVal TEXT DEFAULT '';
    
	INSERT INTO distributors_tbl  
    ( distri_name, distri_address, distri_phones, distri_email, distri_website, distri_contact, distri_contactno, distri_contactemail, distri_contactcell, distri_whatsapp, distri_contactat, distri_regn, distri_GST, distri_TIN, distri_remarks, distri_status, distri_crtdby )
	VALUES( dname, address, phones, email, website, contact, contactno, conemail, concell, whatsapp, contactat, regn, gstnum, tin, remarks, mstatus, adminid );
    
    SET distid = LAST_INSERT_ID();
    
    IF distid > 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 (distid, tempVal, 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 (distid, tempVal, 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 (distid, tempVal, adminid);
            SET products = INSERT(products, 1, frontlen + 1, '');
        END LOOP;
        
    END IF;
END$$

CREATE  PROCEDURE `adddoctor` (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 `adminid` INT)   BEGIN

DECLARE did INT DEFAULT 0;
INSERT INTO doctors_tbl(doctor_type, doctor_name, doctor_regno, doctor_mobile, doctor_email, doctor_degrees, doctor_hospital, doctor_remarks, doctor_photo, doctor_signature, doctor_datefrom, doctor_availfrom, doctor_dateto, doctor_availto, doctor_crtdby) VALUES (dtype, dname, dregno, dmobile, demail, ddegrees, dhospital, dremarks, dphoto, dsignature, ddatefrom, davailfrom, ddateto, davailto, adminid);
    
    SET did = LAST_INSERT_ID();
END$$

CREATE  PROCEDURE `addDrugClassification` (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 drugid INT DEFAULT 0;
    
	INSERT INTO drug_classifications 
    ( drugclass_name, drugclass_parent, drugclass_details, drugclass_uses, drugclass_warnings, drugclass_precautions, drugclass_procedure, drugclass_dosage, drugclass_missdose, drugclass_overdose, drugclass_avoids, drugclass_sideffects, drugclass_interactions, drugclass_status, drugclass_crtdby )
    VALUES( drgclass, parent, remarks, uses, warning, precautions, howto, dosage, misdose, overdose, avoids, sideffects, interactions, dstatus, adminid );
    
    SET drugid = LAST_INSERT_ID();
    CALL reworkDrugSequence(drugid);
END$$

CREATE  PROCEDURE `addFaq` (IN `qtype` INT, IN `qitem` INT, IN `question` VARCHAR(255), IN `answer` TEXT, IN `adminid` INT)   BEGIN
	DECLARE faqid INT DEFAULT 0;
	INSERT INTO faq_table  
    (faq_type, faq_item, faq_question, faq_answer, faq_crtdby)
    VALUES(qtype, qitem, question, answer, adminid);
    SET faqid = LAST_INSERT_ID();
    SELECT faqid;
END$$

CREATE  PROCEDURE `addGenericMedicine` (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
    	INSERT INTO generic_medicines( genmed_name, genmed_uses, genmed_working, genmed_sideffects, genmed_remarks, genmed_status, genmed_crtdby )
       	VALUES( medicine, uses, working, sideffects, notes, mstatus, adminid);
    END IF;
END$$

CREATE  PROCEDURE `addIngredient` (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
	INSERT INTO ingredients_tbl 
    ( ingred_name, ingred_type, ingred_formula, ingred_drugbankid, ingred_codes, ingred_isactive, ingred_drugclasses, ingred_notes, ingred_status, ingred_crtdby )
    VALUES ( ingred, itype, formula, bankid, atccode, isactive, drclass, notes, istatus, admin);
END$$

CREATE  PROCEDURE `addIntoPrograms` (IN `menu` VARCHAR(50), IN `url` VARCHAR(100), IN `icon` VARCHAR(100), IN `parent` INT(10))   begin
DECLARE maxid int default 0;
SELECT MAX(progr_id) FROM programs_table into maxid ;
insert into programs_table(progr_menu ,progr_url, progr_icon, progr_parent,progr_serial) values(menu,url,icon,parent,maxid+1);

set @last_insert_id = LAST_INSERT_ID();

/*UPDATE programs_table s set s.progr_serial  = @last_insert_id WHERE s.progr_id = @last_insert_id;
*/
END$$

CREATE  PROCEDURE `addInvoice` (IN `invno` VARCHAR(50), IN `invdated` DATE, IN `ventype` INT, IN `venid` INT, IN `vendorgst` VARCHAR(255), IN `storeid` INT, IN `storegst` VARCHAR(255), 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 invid, resp INT DEFAULT 0;
    IF( SELECT COUNT(*) FROM invoices_tbl WHERE invoice_number = trim(invno) ) = 0 THEN
		INSERT INTO invoices_tbl( invoice_number, invoice_dated, invoice_vendertype, invoice_vendor,invoice_vendorgst,invoice_delstore,invoice_delgst, invoice_amount, invoice_cgst, invoice_sgst, invoice_notes, invoice_crtdby, invoice_delstatus )
    	VALUES( invno, invdated, ventype, venid,vendorgst,storeid,storegst, total, cst, gst, notes, adminid, 1 );
    	SET invid = LAST_INSERT_ID();
    	SET resp = invid;
    	IF invid > 0 THEN
    		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;
     			IF @pord !=0 THEN
                 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 );
                ELSE
                INSERT INTO invoice_details( invdet_invoice, invdet_porder,	invdet_wopo, 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,1, @item, @qty, @price, @cstpc, @cst, @sstpc, @sst, @delat, @mrp, @free, @schdisc, @hsn, @ptr, @taxamt, @discpc, @disct, @batch, @expiry );
                END IF;
                UPDATE purchase_orders p SET p.purchord_status=5 WHERE p.purchord_id=@pord;
  			END WHILE;
    	END IF;
    END IF;
    SELECT resp;
END$$

CREATE  PROCEDURE `addItemtoGallery` (IN `packid` 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
	INSERT INTO product_gallery( prodgal_prodpack, prodgal_url, prodgal_placedat, prodgal_medium, prodgal_heading, prodgal_descr, prodgal_title, prodgal_alt, prodgal_serial, prodgal_publish, prodgal_status, prodgal_crtdby )
    VALUES( packid, url, placedat, medm, heading, descr, title, alt, serial, publish, gstatus, adminid );
END$$

CREATE  PROCEDURE `addLocation` (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
	DECLARE lid INT DEFAULT 0;
    
	INSERT INTO delivery_areas( delarea_location, delarea_pincode, delarea_country, delarea_province, delarea_district, delarea_remarks, delarea_status, delarea_crtdby )
    VALUES( location, pin, country, state, district, remarks, dstatus, adminid );
    
    SET lid = LAST_INSERT_ID();
    
    SELECT lid;
END$$

CREATE  PROCEDURE `addManufacturer` (IN `mname` VARCHAR(200), IN `mcode` VARCHAR(20), 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)   BEGIN
	INSERT INTO manufacturers_tbl 
    (manuf_name, manuf_code,manuf_address, manuf_phones, manuf_email, manuf_website, manuf_contact, 
     manuf_contactno, manuf_contactemail, manuf_contactcell, manuf_whatsapp, manuf_contactat, 
     manuf_regn, manuf_remarks, manuf_status, manuf_crtdby)
	VALUES( mname,mcode,address, phones, email, website, contact, contactno, conemail, concell, 
           whatsapp, contactat, regn, remarks, mstatus, adminid );
END$$

CREATE  PROCEDURE `addMeasuringUnit` (IN `measur` VARCHAR(50), IN `shorted` VARCHAR(10), IN `adminid` INT)   BEGIN
	DECLARE mid INT DEFAULT 0;
    
	INSERT INTO measure_units( measunit_name, measunit_shortname, measunit_crtdby )
    VALUES( measur, shorted, adminid );
    
    SET mid = LAST_INSERT_ID();
    SELECT mid;
END$$

CREATE  PROCEDURE `addNewIssusPerTask` (IN `task_id` INT, IN `issues` TEXT, IN `solution` TEXT)   BEGIN

INSERT INTO tbl_help_desk_reason (reason_help_id,reason_issue,reason_help,reason_status) VALUES (task_id,issues,solution,1) ;




END$$

CREATE  PROCEDURE `addOnInvoice` (IN `invoiceno` VARCHAR(50), IN `invdated` DATE, IN `vendtype` INT, IN `vendor` INT, IN `vendorgst` VARCHAR(255), IN `storeid` INT, IN `storegst` VARCHAR(255), IN `invdetails` TEXT, IN `notes` TEXT, IN `adminid` INT)   BEGIN
	DECLARE invid, resp INT DEFAULT 0;
     IF( SELECT COUNT(*) FROM invoices_tbl WHERE invoice_number = trim(invoiceno) ) = 0 THEN
		INSERT INTO invoices_tbl(invoice_number, invoice_dated, invoice_vendertype,	invoice_vendor,invoice_vendorgst,invoice_delstore,invoice_delgst,invoice_amount, invoice_cgst, invoice_sgst, invoice_notes, invoice_crtdby, invoice_delstatus )
    	VALUES(invoiceno, invdated, vendtype, vendor,vendorgst,storeid,storegst, 0, 0, 0, notes, adminid, 1 );
    	SET invid = LAST_INSERT_ID();
    	SET resp = invid;
    	IF invid > 0 THEN
    		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 @invref := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 2 THEN                   	
                        SET @pord := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 3 THEN                   	
                        SET @stoknid := SUBSTRING_INDEX(@Gstr, '|', -1);
                	ELSEIF @icols = 4 THEN
                    	SET @item := SUBSTRING_INDEX(@Gstr, '|', -1);
                	ELSEIF @icols = 5 THEN
                    	SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 6 THEN
                    	SET @qtyshort := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 7 THEN
                    	SET @delat := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 8 THEN
                    	SET @mrp := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 9 THEN
                    	SET @hsn := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 10 THEN
                    	SET @ptr := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSEIF @icols = 11 THEN
                    	SET @batch := SUBSTRING_INDEX(@Gstr, '|', -1);
                	ELSE
                    	SET @expiry := 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_hsn, invdet_ptr, invdet_taxamt, invdet_discpc, invdet_discount, invdet_batch, invdet_expiry )
            	VALUES(invid, @pord, @item, @qty, 0, 0, 0, 0, 0, @delat, @mrp,0, @hsn, @ptr,0,0,0, @batch, @expiry );
                INSERT INTO addoninvoice(addinv_stokinid,addinv_ref,addinv_invoice, addinv_item,addinv_short,addinv_supply,addinv_status,addinv_updby,addinv_updon) VALUES (@stoknid,@invref,invid,@item, @qtyshort,@qty,1,adminid,CURRENT_TIMESTAMP);
UPDATE stock_inwards SET stockin_short = (@qtyshort - @qty) WHERE stockin_id = @stoknid AND stockin_invref IN (SELECT invdet_id FROM invoice_details WHERE invdet_invoice = @invref);
  			END WHILE;
    	END IF;
    END IF;
    SELECT resp;
END$$

CREATE  PROCEDURE `addPackingType` (IN `packing` VARCHAR(50), IN `packsale` INT, IN `adminid` INT)   BEGIN
	DECLARE pid INT DEFAULT 0;
	INSERT INTO packing_tbl( packing_type, packing_sale, packing_crtdby)
    VALUES( packing, packsale, adminid );
    SET pid = LAST_INSERT_ID();
    SELECT pid;
END$$

CREATE  PROCEDURE `addpharmacontent` (IN `pharma_name` VARCHAR(750), IN `pharma_status` INT, IN `adminid` INT)   BEGIN
    INSERT INTO pharmacologicalcontent_tbl (pharma_name, pharma_status, pharma_crtdby)
    VALUES (pharma_name, pharma_status, adminid);
    SELECT LAST_INSERT_ID() AS new_id;

END$$

CREATE  PROCEDURE `addPrescriptionFiles` (IN `p_user_id` INT, IN `p_ordid` VARCHAR(100), IN `p_files` JSON, IN `p_path` VARCHAR(255), IN `p_phone` VARCHAR(20), IN `p_status` INT)   BEGIN
    DECLARE i INT DEFAULT 0;
    DECLARE total INT DEFAULT 0;

    -- Handle NULL safely
    IF p_files IS NOT NULL AND JSON_VALID(p_files) THEN
        SET total = JSON_LENGTH(p_files);
    END IF;

    -- Case 1: If files exist, insert each file
    IF total > 0 THEN
        WHILE i < total DO
            INSERT INTO prescription_files(user_id, order_id, file_name, file_path, user_phone,file_status)
            VALUES (
                p_user_id,
                p_ordid,
                JSON_UNQUOTE(JSON_EXTRACT(p_files, CONCAT('$[', i, ']'))),
                p_path,
                p_phone,
                p_status
            );
            SET i = i + 1;
        END WHILE;
    ELSE
        -- Case 2: Only phone number, no files
        INSERT INTO prescription_files(user_id, order_id, file_name, file_path, user_phone,file_status)
        VALUES (p_user_id, p_ordid, NULL, NULL, p_phone,p_status);
    END IF;
END$$

CREATE  PROCEDURE `addPrescriptiontmpFiles` (IN `p_user_id` INT, IN `p_files` JSON, IN `p_path` VARCHAR(255))   BEGIN
    DECLARE i INT DEFAULT 0;
    DECLARE total INT DEFAULT 0;

    -- Handle NULL safely
    IF p_files IS NOT NULL AND JSON_VALID(p_files) THEN
        SET total = JSON_LENGTH(p_files);
    END IF;

    -- Case 1: If files exist, insert each file
    IF total > 0 THEN
        WHILE i < total DO
            INSERT INTO prescription_files_attached(user_id, file_name, file_path)
            VALUES (
                p_user_id,
          
                JSON_UNQUOTE(JSON_EXTRACT(p_files, CONCAT('$[', i, ']'))),
                p_path
               
            );
            SET i = i + 1;
        END WHILE;
    ELSE
        -- Case 2: Only phone number, no files
        INSERT INTO prescription_files_attached(user_id,file_name, file_path)
        VALUES (p_user_id, NULL, NULL);
    END IF;
END$$

CREATE  PROCEDURE `addProduct` (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` TEXT, IN `taxgrp` INT, IN `schedule_id` INT, IN `pcontent` INT, IN `adminid` INT)   BEGIN

	DECLARE pid INT DEFAULT 0;
    
    INSERT INTO products_tbl( product_name, product_display,product_generic, product_maincategory, product_subcategory, product_category, product_manufacturer, product_brand, product_drugmainclass, product_drugsubclass, product_drugclass, product_classified, product_prescrption, product_highlights, product_information, product_working, product_howto, product_benefits, product_specifications, product_features, product_usage, product_precautions, product_warnings, product_sideffects, product_antidot, product_interactions, product_publish, product_sale, product_online, product_featured, product_popular, product_taxgroup, product_schedule, product_pcontent, product_crtdby) 
    VALUES(pname, display,generic, maincat, subcat, categ, manuf, brand, drugmain, drugsub, drugclass, clasfd, prescrp, highlights, inform, working, howto, benefits, specs, features, usge, caution, warns, effects, antidot, interact, publish, sale, onlne, featured, popular,taxgrp,schedule_id, pcontent, adminid);

	SET pid = LAST_INSERT_ID();
    
    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;
/* SELECT @ingrd, @qty, @unt,pid; */
	 INSERT INTO product_ingredients( prodingred_product, prodingred_ingredient, prodingred_quantity, prodingred_unit, prodingred_crtdby ) 
     VALUES( pid, @ingrd, @qty, @unt, 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 @stkmax := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 5 THEN
            SET @stkmin := 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 );
  END WHILE;
    
    END IF;
END$$

CREATE  PROCEDURE `addProductClass` (IN `prparent` INT, IN `prclass` VARCHAR(100), IN `serial` INT, IN `adminid` INT, IN `thumb` VARCHAR(100))   BEGIN
	DECLARE prid INT DEFAULT 0;
	INSERT INTO product_classes  
    (prodclass_parent, prodclass_name, prodclass_serial, prodclass_crtdby, prodclass_thumb)
    VALUES( prparent, prclass, serial, adminid, thumb );
    
    SET prid = LAST_INSERT_ID(); 
    CALL reworkProductClassSequence(prid);
    SELECT prid;
END$$

CREATE  PROCEDURE `AddProductStockk` (IN `p_product_id` INT, IN `p_item_id` INT, IN `p_stock_id` INT, IN `p_required_qty` INT, IN `order_id` INT, IN `cart_id` 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 (
          product_id INT,
        allocated_quantity INT,
        strstk_item INT,
        strstk_id INT,
        mrp DECIMAL(9,2),
         msp DECIMAL(9,2),
         discount DECIMAL(5,2)
    );
 -- Insert eligible stock entries sorted by expiry
    CREATE TEMPORARY TABLE IF NOT EXISTS TempStockData AS
    SELECT 
    e1.strstk_product,
        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_product,strstk_id, strstk_item, available_stock, stockin_expiry, 
               strstk_discount, strstk_mrp, strstk_msp
        INTO @product_id,@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 (
            product_id,allocated_quantity,strstk_item,strstk_id, mrp,msp,discount
        ) VALUES (
            @product_id,allocated_qty,@stock_item,@stock_id,@stock_mrp,@stock_msp,@stock_discount
        );

        -- 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
    INSERT INTO order_details (ordet_order, ordet_cartid, ordet_productid, ordet_quantity, ordet_producpackid, order_batchid,order_mrp,order_msp,order_disc)
SELECT order_id, cart_id, product_id,allocated_quantity,strstk_item,strstk_id,mrp,msp,discount
FROM TempStockSelection;
    
    /*SELECT * FROM order_details WHERE ordet_order=order_id;*/

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

CREATE  PROCEDURE `addPromotions` (IN `promotype` INT, IN `title` VARCHAR(255), IN `promoacnt` INT, IN `discamount` DECIMAL(10,0), IN `discprcntg` 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
	DECLARE lid INT DEFAULT 0;
    INSERT INTO promotions_tbl(promo_type,promo_title, promo_account, promo_discountamt, promo_discountpc, promo_max, promo_count, promo_datefrom, promo_dateto, promo_status, promo_publish, promo_highlights, promo_crtdby, promo_crtdon) VALUES (promotype,title,promoacnt,discamount,discprcntg,promomax,promocount,datefrom,dateto,promostatus,publishstatus,promohighlights,adminid,CURRENT_TIMESTAMP());
    SET lid = LAST_INSERT_ID();
END$$

CREATE  PROCEDURE `addPurchaseOrder` (IN `orderef` VARCHAR(20), IN `ordate` DATE, IN `license` VARCHAR(50), IN `vtype` INT, IN `vendid` INT, IN `amount` DECIMAL(11,2), IN `ordetails` TEXT, IN `notes` TEXT, IN `deliverat` INT, IN `deliverby` DATE, IN `adminid` INT)   BEGIN
	DECLARE ordid ,checkid INT DEFAULT 0;
    SELECT user_id INTO checkid  FROM users_tbl  WHERE user_checkid=adminid;
    INSERT INTO purchase_orders( purchord_ref, purchord_date, purchord_license, purchord_vendtype, purchord_vendor, purchord_amount, purchord_notes, purchord_preprdby, purchord_crtdby, purchord_deliverat, purchord_deliverby, purchord_preprdon )
    VALUES( orderef, ordate, license, vtype, vendid, amount, notes, checkid, checkid, deliverat, deliverby, CURDATE() );
    SET ordid = LAST_INSERT_ID();
    IF ordid > 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;
     		INSERT INTO purchase_details( podetail_order, podetail_item, podetail_qty, podetail_price )
            VALUES( ordid, @item, @qty, @price );
  		END WHILE;
    END IF;
END$$

CREATE  PROCEDURE `addReceivedPacketsItems` (IN `flag` INT, IN `secret_id` VARCHAR(100), IN `tnfr_packid` INT, IN `packid` TEXT, IN `fromstore` INT, IN `tostore` INT, IN `itemdetails` VARCHAR(255), IN `courierid` INT, IN `note` TEXT, IN `adminid` INT)   BEGIN
	DECLARE front, TempValue, alltracks, packets TEXT DEFAULT NULL;
   	DECLARE frontlen INT DEFAULT 0;
    IF flag=1 THEN
    
    select u.user_id from users_tbl u  where u.user_checkid = secret_id into @receiveid ;
    
    	UPDATE transfer_packets SET transpack_deliverby=courierid,transpack_deliveron=CURRENT_TIMESTAMP(),transpack_status=10 ,transpack_notes = CONCAT(transpack_notes, '<COURNOTES>', note, '</COURNOTES>'),transpack_receiveby=@receiveid,transpack_receiveon=CURRENT_TIMESTAMP(), transpack_grn=fnCreateGRNnumber(tostore) WHERE transpack_id=tnfr_packid;
    	SELECT transpack_to INTO tostore FROM transfer_packets WHERE transpack_id = packid;
		SET @text := TRIM(BOTH '##' FROM itemdetails);
  		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 @items := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 2 THEN
                    SET @orditems := SUBSTRING_INDEX(@Gstr, '|', -1); /* store_stock_pricing_id */
                ELSEIF @icols = 3 THEN
                    SET @ordqty := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 4 THEN
                    SET @rcvdqty := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSE
                	 SET @rack := SUBSTRING_INDEX(@Gstr, '|', -1);
                END IF;
                SET @icols := @icols + 1;
      		END WHILE;
           /* SELECT @ordqty,@rcvdqty,(@ordqty-@rcvdqty),@items,@orditems;*/
        	START TRANSACTION;
            UPDATE transferpack_items SET store_stack=@rack, transferpack_recieved=@rcvdqty,transferpack_short=(@ordqty-@rcvdqty),	transferpack_checkby=secret_id, transferpack_checkon=CURRENT_TIMESTAMP(), transferpack_status=10 WHERE transferpack_packet=packid AND transferpack_item=@items AND transferpack_qty=@ordqty;
        	/*	#update stock at source store
        	UPDATE storestock_pricing
        	SET strstk_transfer = (strstk_transfer + @rcvdqty), strstk_reserved = (strstk_reserved - @rcvdqty),
            strstk_stock = (strstk_stock - @rcvdqty)
        	WHERE strstk_id = @orditems; */
       	 	#insert stock at receiving store
        	INSERT INTO storestock_pricing(strstk_refer, strstk_store, strstk_item, strstk_product, strstk_msp, strstk_discount, strstk_mrp, strstk_cost, strstk_last, strstk_currency, strstk_inward, strstk_stock,strstk_stack ,strstk_crtdby)
            SELECT strstk_refer, tostore, strstk_item, strstk_product, strstk_msp, strstk_discount, strstk_mrp, strstk_cost, strstk_last, strstk_currency, @rcvdqty, @rcvdqty,@rack, adminid FROM storestock_pricing WHERE strstk_id = @orditems;
          /* #update stock at source store in stockmaster
          UPDATE storestock_master SET storestock_available=(storestock_available- @rcvdqty) ,storestock_reserved=(storestock_reserved - @rcvdqty) WHERE storestock_store =fromstore AND storestock_item =@items; */
          #insert stockes to receiving store
          INSERT INTO storestock_master (storestock_item,storestock_store,storestock_available,storestock_inward) VALUES (@items,tostore,@rcvdqty,@rcvdqty) ON DUPLICATE KEY UPDATE storestock_available=(storestock_available + @rcvdqty);
        	COMMIT;
		END WHILE;
	ELSEIF flag=2 THEN
     	SET packets = packid;
    	iterator:
			LOOP
				IF LENGTH(TRIM(packid)) = 0 OR packid IS NULL THEN
					LEAVE iterator;
				END IF;
				SET front = SUBSTRING_INDEX(packid,',',1);
				SET frontlen = LENGTH(front);
				SET TempValue = TRIM(front);
    			UPDATE transfer_packets SET transpack_receiveby=secret_id, transpack_updby=adminid, transpack_receiveon=CURRENT_TIMESTAMP(),transpack_status=15 WHERE transpack_id=TempValue;
                SET packid = INSERT(packid, 1, frontlen + 1, '');
			END LOOP;
  	END IF;
END$$

CREATE  PROCEDURE `addRefundDetails` (IN `ids` INT, IN `oderno` VARCHAR(225), IN `userid` INT, IN `payids` VARCHAR(225), IN `razorid` VARCHAR(225), IN `amount` DECIMAL(10,2), IN `statuss` VARCHAR(225))   BEGIN
DECLARE store,item INT DEFAULT 0;
DECLARE resultString ,resultQty ,singleValue,singleQty TEXT;
INSERT INTO refund_table(refund_orderid,refund_order,refund_userid,refund_paymentid,refund_razorid,refund_amount,refund_status) VALUES 
(ids,oderno,userid,payids,razorid,amount,statuss);

UPDATE orders_tbl set order_delivery=5 WHERE order_id=ids;
SELECT GROUP_CONCAT(c.order_batchid) INTO resultString FROM order_details c WHERE c.ordet_order=ids ;
    SELECT GROUP_CONCAT(c.ordet_quantity) INTO resultQty FROM order_details c WHERE c.ordet_order=ids ;
 WHILE resultString IS NOT NULL AND resultString != '' DO
        SET singleValue = SUBSTRING_INDEX(resultString, ',', 1);
        SET singleQty = SUBSTRING_INDEX(resultQty, ',', 1);
        SELECT strstk_store,strstk_item INTO store,item FROM storestock_pricing WHERE strstk_id =singleValue;
        UPDATE storestock_pricing SET strstk_reserved=strstk_reserved-singleQty WHERE strstk_id =singleValue;
        UPDATE storestock_master SET storestock_reserved=storestock_reserved-singleQty WHERE storestock_store = store AND storestock_item =item;
        -- Remove the processed value from resultString
        SET resultString = REPLACE(resultString, CONCAT(singleValue, ','), '');
        SET resultQty = REPLACE(resultQty, CONCAT(singleQty, ','), '');
        IF resultString = singleValue AND resultQty=singleQty  THEN
            SET resultString = '';
            SET resultQty='';
        END IF;
    END WHILE;

SELECT DATE_FORMAT(CURRENT_TIMESTAMP, "%M %d, %Y %h:%i %p") AS rdate;
END$$

CREATE  PROCEDURE `addSalesbill` (IN `billdate` DATE, IN `billstore` INT, IN `billno` INT, IN `billstaff` VARCHAR(255), IN `staffcheckid` VARCHAR(100), IN `billcustomer` VARCHAR(255), IN `billmob` VARCHAR(100), IN `billname` VARCHAR(255), IN `billage` INT, IN `billgender` INT, IN `billaddress` VARCHAR(255), IN `billreferrer` VARCHAR(255), IN `billdoctor` INT, IN `billitems` TEXT, IN `billquantity` INT, IN `billmrp` INT, IN `billtaxable` DECIMAL(10,2), IN `billcgst` DECIMAL(10,2), IN `billsgst` DECIMAL(10,2), IN `billnetpay` DECIMAL(10,2), IN `billpayref` INT, IN `delmode` INT, IN `billtransid` VARCHAR(20), IN `paymnt` INT, 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;

    insert INTO bills_table(bill_date, bill_store,bill_no, bill_pharmacist, billpharmacist_checkid, bill_customer, bill_mobile, bill_name, bill_age, bill_gender, bill_address, bill_referrer, bill_doctor, bill_quantity, bill_mrp, bill_taxable, bill_cgst, bill_sgst, bill_netpay, bill_payref,bill_delmode, bill_transid, bill_payby, bill_crtdby)
   
    VALUES(billdate, billstore, fnGenerateBillNumber(billstore),  billstaff, staffcheckid, billcustomer,billmob, billname, billage, billgender,billaddress, billreferrer, billdoctor, billquantity, billmrp, billtaxable, billcgst, billsgst, billnetpay, billpayref,delmode, billtransid, paymnt, adminid);
       
      

         /* item details */
  
  SET billid = LAST_INSERT_ID();
    IF billid > 0 THEN
    	SET @text := TRIM(BOTH '##' FROM billitems);
  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 @itemid := SUBSTRING_INDEX(@Gstr, '|', -1);
       ELSEIF @icols = 2 THEN
        	SET @itemname := SUBSTRING_INDEX(@Gstr, '|', -1);
        ELSEIF @icols = 3 THEN
            SET @hsn := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 4 THEN
            SET @mfr := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 5 THEN
            SET @batch := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 6 THEN
            SET @exp := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 7 THEN
            SET @sch := SUBSTRING_INDEX(@Gstr, '|', -1);
              ELSEIF @icols = 8 THEN
            SET @mrp := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 9 THEN
            SET @discper := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 10 THEN
            SET @rate := SUBSTRING_INDEX(@Gstr, '|', -1);
              ELSEIF @icols = 11 THEN
            SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 12 THEN
            SET @amt := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 13 THEN
            SET @cgst := SUBSTRING_INDEX(@Gstr, '|', -1);
             ELSEIF @icols = 14 THEN
            SET @sgst := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 15 THEN
        		SET @strstk := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSE 
        		SET @mode := SUBSTRING_INDEX(@Gstr, '|', -1);
        END IF;
        SET @icols := @icols + 1;
     END WHILE;
     START TRANSACTION;
     INSERT INTO bill_items(billit_id,billit_item,billit_strstkid, billit_name, billit_hsn, billit_mfr, billit_batch, billit_expiry,billit_sched, billit_mrp, billit_discount, billit_rate, billit_qty, billit_amount, billit_cgstpc,  billit_sgstpc)  VALUES (billid, @itemid,@strstk, @itemname, @hsn, @mfr, @batch, @exp, @sch, @mrp, @discper, @rate, @qty, @amt, @cgst, @sgst);
    
 SELECT ss.strstk_refer,ss.strstk_stock INTO strids,stkTotal FROM storestock_pricing ss WHERE ss.strstk_id= @strstk;
 if(@mode='Strip')THEN
       
       SELECT l.LsQty_lqty, l.LsQty_sqty INTO lqty, sqty FROM looseitemqty_tbl l WHERE l.LsQty_refer = strids AND l.LsQty_batch=@batch;
   
       
     set stockval=FLOOR(((lqty*stkTotal)-@qty) / lqty);
     
  UPDATE storestock_pricing SET strstk_stock=stockval WHERE strstk_id =@strstk;
    UPDATE storestock_master SET storestock_available=(storestock_available-stkTotal)+stockval WHERE storestock_item=@itemid AND storestock_store=billstore;
   
     set minvalue = FLOOR((lqty*(stkTotal-stockval))-@qty);
    UPDATE looseitemqty_tbl l SET l.LsQty_sqty= l.LsQty_sqty+minvalue WHERE l.LsQty_refer = strids AND l.LsQty_batch=@batch;
   
    ELSEIF(@mode='loose')THEN
     UPDATE looseitemqty_tbl l SET l.LsQty_sqty= l.LsQty_sqty-@qty WHERE l.LsQty_refer = strids AND l.LsQty_batch=@batch;
   ELSEIF(@mode='return')THEN
         UPDATE looseitreturn_tbl l SET l.LsQty_sqty= l.LsQty_sqty-@qty WHERE l.LsQty_refer = strids AND l.LsQty_batch=@batch;
ELSE
UPDATE storestock_pricing SET strstk_stock=strstk_stock-@qty WHERE strstk_id =@strstk;
    UPDATE storestock_master SET storestock_available=storestock_available-@qty WHERE storestock_item=@itemid AND storestock_store=billstore;
    END IF;
    
    
   COMMIT;
  END WHILE;
  END IF;
  
  INSERT INTO offline_customers_tbl (customer_number, customer_name, customer_address, customer_phone, customer_gender, customer_age) VALUES(billcustomer, billname, billaddress, billmob, billgender, billage);
  
SELECT b.bill_id, b.bill_date, b.bill_store, b.bill_no, b.bill_pharmacist, b.bill_customer, b.bill_name, b.bill_age, b.bill_gender, b.bill_address, b.bill_referrer, b.bill_doctor, b.bill_license, 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_paidon, b.bill_payby, b.bill_payref, b.bill_transid, b.bill_balance, bt.* FROM bills_table b JOIN bill_items bt ON b.bill_id = bt.billit_id WHERE b.bill_id = billid;


END$$

CREATE  PROCEDURE `addSalesItemsDetails` (IN `storeid` INT, IN `itemid` INT, IN `qty` INT, IN `batch` VARCHAR(255))   BEGIN
DECLARE stock, newqty,newstock INT DEFAULT 0;
SELECT strstk_stock INTO stock FROM storestock_pricing LEFT JOIN stock_inwards si ON si.stockin_id= strstk_refer WHERE strstk_store= storeid AND strstk_item=itemid AND si.stockin_batch= batch ;
SELECT bill_stock INTO newqty FROM billstock_tbl  WHERE billstock_item= itemid AND bill_batch= batch;
INSERT INTO billstock_tbl (billstore_id , billstock_item ,bill_stock,bill_qty,bill_batch) VALUES(storeid,itemid,(stock-qty),qty,batch) ON DUPLICATE KEY UPDATE bill_stock=newqty-qty, bill_qty = bill_qty+qty;
SELECT bill_stock INTO newstock FROM billstock_tbl  WHERE billstock_item= itemid AND bill_batch= batch;
SELECT newstock;
END$$

CREATE  PROCEDURE `addScheduledDiscountDatas` (IN `dates` DATE, IN `storeid` INT, IN `mainpdct` TEXT, IN `freepdct` TEXT, IN `note` TEXT, IN `adminid` INT)   BEGIN
INSERT INTO schedulediscount_tbl  (dis_date,dis_store,dis_mainitem,dis_freeitem,dis_note,dis_crtdby,dis_crtdon) VALUES (dates,storeid,mainpdct,freepdct,note,adminid,CURRENT_TIMESTAMP());
END$$

CREATE  PROCEDURE `addSearchlogbyStore` (IN `storeid` INT, IN `item` INT, IN `adminid` INT)   BEGIN

INSERT INTO searchlog_tbl(search_item,search_store,search_crtdby) VALUES(item,storeid,adminid);

END$$

CREATE  PROCEDURE `addStaff` (IN `staffname` VARCHAR(100), IN `staffcode` VARCHAR(100), IN `staffdob` DATE, IN `staffgender` TINYINT, IN `staffmobile` VARCHAR(100), IN `staffemail` VARCHAR(100), IN `staffaddress` TEXT, IN `adminid` INT)   begin

INSERT into staff_tbl(staff_name,staff_code,staff_dob,staff_gender,staff_mobile,staff_email,staff_address,staff_crtby) values(staffname,staffcode,staffdob,staffgender,staffmobile,staffemail,staffaddress,adminid);

END$$

CREATE  PROCEDURE `addStock` (IN `invid` INT, IN `supply` VARCHAR(255), IN `charges` VARCHAR(200), IN `adminid` INT, IN `notes` TEXT)   BEGIN
	DECLARE delstat, newrec, mindel, minstat, inwardid,porder, newprod,checkid,lqty,packingsale INT DEFAULT 0;
    DECLARE maxdate DATE;
    SELECT user_id INTO checkid FROM users_tbl WHERE user_checkid=adminid ;
    UPDATE invoices_tbl SET invoice_delnotes = notes
    WHERE invoice_id = invid;
	SET @text := TRIM(BOTH '##' FROM supply);
  	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 @refer := 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 @short := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 5 THEN
                SET @qr := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 6 THEN
                SET @dated := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 7 THEN
                SET @batch := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 8 THEN
                SET @expiry := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 9 THEN
                SET @stack := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 10 THEN
                SET @store := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSEIF @icols = 11 THEN
                SET @damage := SUBSTRING_INDEX(@Gstr, '|', -1);
            ELSE
                SET @mrp := SUBSTRING_INDEX(@Gstr, '|', -1);
            END IF;
        	SET @icols := @icols + 1;
      	END WHILE;
        IF(SELECT COUNT(*) FROM stock_inwards x WHERE x.stockin_item = @item AND x.stockin_invref = @refer) = 0 THEN
     		INSERT INTO stock_inwards( stockin_item, stockin_invref, stockin_qrcode,
				stockin_supdate, stockin_batch, stockin_expiry, stockin_stack,
				stockin_inward, stockin_short,stockin_damaged, stockin_balance, stockin_store, stockin_mrp, stockin_crtdby, stockin_mode)
            VALUES( @item, @refer, @qr, @dated, @batch, @expiry, @stack, @qty, @short,@damage, @qty, @store, @mrp, checkid, 1 );
            SET inwardid = LAST_INSERT_ID();
            INSERT INTO stock_master (stock_item, stock_available, stock_inward)
            VALUES(@item, @qty, @qty)
            ON DUPLICATE KEY UPDATE stock_available = stock_available + @qty, stock_inward = stock_inward + @qty;
            INSERT INTO storestock_master( storestock_item, storestock_store, storestock_available, storestock_inward )
            VALUES(@item, @store, @qty, @qty)
            ON DUPLICATE KEY UPDATE storestock_available = storestock_available + @qty,
            storestock_inward = storestock_inward + @qty;
            #looseitemqty_table
            SELECT p.prodpack_quantity,pt.packing_sale INTO lqty,packingsale FROM product_packing p join packing_tbl pt on 				pt.packing_id = p.prodpack_package WHERE p.prodpack_id=@item;
            INSERT INTO 											looseitemqty_tbl(LsQty_refer,LsQty_item,LsQty_store,LsQty_batch,LsQty_pack,LsQty_lqty,LsQty_sqty,LsQty_crtdby,LsQty_crtdon)
 VALUES(inwardid,@item,@store,@batch,0,(CASE WHEN packingsale = 0 THEN 1 ELSE lqty END),0,checkid,CURRENT_TIMESTAMP());
 
 INSERT INTO 											looseitreturn_tbl(LsQty_refer,LsQty_item,LsQty_store,LsQty_batch,LsQty_pack,LsQty_lqty,LsQty_sqty,LsQty_crtdby,LsQty_crtdon)
 VALUES(inwardid,@item,@store,@batch,0,(CASE WHEN packingsale = 0 THEN 1 ELSE lqty END),0,checkid,CURRENT_TIMESTAMP());
 
 
            SELECT prodpack_product INTO newprod FROM product_packing
            WHERE prodpack_id = @item;
            INSERT INTO storestock_pricing (strstk_refer, strstk_store, strstk_item, strstk_product, strstk_mrp, strstk_inward, strstk_stock, strstk_stack, strstk_crtdby) VALUES(inwardid, @store, @item, newprod, @mrp, @qty, @qty, @stack, checkid);
            SET newprod = 0;
            SET newrec = 1;
            IF @short = 0 THEN
            	SET delstat = 10;
            ELSE	
            	SET delstat = 5;
            END IF;
            UPDATE invoice_details SET /*invdet_delivered = @store,*/ invdet_deldate = @dated, invdet_delstatus = delstat
            WHERE invdet_id = @refer;
            SET delstat = 0;
        END IF;
  	END WHILE;
    IF newrec = 1 THEN
        SELECT MIN(d.invdet_delstatus), MAX(d.invdet_deldate) INTO minstat, maxdate FROM invoice_details d WHERE d.invdet_invoice = invid AND d.invdet_status > 0;
        SELECT DISTINCT(d.invdet_porder)INTO porder from invoice_details d WHERE d.invdet_invoice=invid AND d.invdet_porder!=0;
        IF minstat = 10 THEN
          	 UPDATE invoices_tbl SET invoice_delstatus = 10, invoice_deldate = maxdate WHERE invoice_id = invid;
        	 UPDATE purchase_orders SET purchord_status=15 WHERE purchord_id= porder;
        ELSEIF minstat = 5 THEN
           	 UPDATE invoices_tbl SET invoice_delstatus = 5, invoice_deldate = maxdate WHERE invoice_id = invid;
        	 UPDATE purchase_orders SET purchord_status=10 WHERE purchord_id= porder;
        END IF;
    END IF;
    /*	IF (SELECT COUNT(*) FROM stockin_expenses x WHERE x.stokexp_refer = invid AND x.stokexp_type = 1) = 0 THEN */
        	SET @text := TRIM(BOTH '##' FROM charges);
  			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 @chid := SUBSTRING_INDEX(@Gstr, '|', -1);
                    ELSE
                		SET @chamount := SUBSTRING_INDEX(@Gstr, '|', -1);
            		END IF;
        			SET @icols := @icols + 1;
      			END WHILE;
                INSERT INTO stockin_expenses(stokexp_refer, stokexp_type, stokexp_chargeon, stokexp_amount)
                VALUES(invid, 1, @chid, @chamount)
                ON DUPLICATE KEY UPDATE stokexp_amount = @chamount, stokexp_status = 1 ;
        	END WHILE;
  	/*	END IF; */
END$$

CREATE  PROCEDURE `addStockist` (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 stkid INT DEFAULT 0;
    DECLARE front TEXT DEFAULT '';
    DECLARE frontlen INT DEFAULT 0;
    DECLARE tempVal TEXT DEFAULT '';
    
	INSERT INTO stockists_tbl 
    (stockist_name, stockist_address, stockist_phones, stockist_email, stockist_website, stockist_contact, 
     stockist_contactno, stockist_contactemail, stockist_contactcell, stockist_whatsapp, stockist_contactat, 
     stockist_regn, stockist_gst, stockist_tin, stockist_remarks, stockist_status, stockist_crtdby)
	VALUES( sname, address, phones, email, website, contact, contactno, conemail, concell, 
           whatsapp, contactat, regn, gstnum, tin, remarks, mstatus, adminid );
    
    SET stkid = LAST_INSERT_ID();
    
    IF stkid > 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 stockist_manufacturers (stockmanu_stockist, stockmanu_company, stockmanu_crtdby) VALUES (stkid, tempVal, 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);
            INSERT INTO stockist_products (stockistprod_stockist, stockistprod_product, stockistprod_crtdby) 
            	VALUES (stkid, tempVal, adminid);
            SET products = INSERT(products, 1, frontlen + 1, '');
        END LOOP;

END IF;
END$$

CREATE  PROCEDURE `addStockTransferOrder` (IN `orderno` VARCHAR(20), IN `orderdate` DATE, IN `storefrom` INT, IN `storeto` INT, IN `transitems` TEXT, IN `adminid` INT, IN `notes` TEXT)   BEGIN
	DECLARE transid, insid INT DEFAULT 0;
    
	INSERT INTO stock_transfers(stocktrans_order, stocktrans_date, stocktrans_strfrom, stocktrans_strto, stocktrans_prprdby, stocktrans_crtdby, stocktrans_notes)
    VALUES(orderno, orderdate, storefrom, storeto, adminid, adminid, notes);
	SET transid = LAST_INSERT_ID();
    
	IF transid > 0 THEN
    	SET @text := TRIM(BOTH '##' FROM transitems);
  		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 @stockid := 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 @batch := SUBSTRING_INDEX(@Gstr, '|', -1);
               	ELSE
                   	SET @expiry := SUBSTRING_INDEX(@Gstr, '|', -1);
               	END IF;
       			SET @icols := @icols + 1;
    		END WHILE;
    		INSERT INTO stocktransfer_details( stockorder_refer, stockorder_item, stockorder_quantity, stockorder_batch, stockorder_expiry ) 
           	VALUES( transid, @stockid, @qty, @batch, @expiry );
            SET insid = LAST_INSERT_ID();
            IF insid > 0 THEN
            	UPDATE stock_inwards SET stockin_reserved = stockin_reserved + @qty 
                WHERE stockin_id = @stockid;
                UPDATE storestock_master SET storestock_reserved = storestock_reserved + @qty 
                WHERE storestock_item = @item AND storestock_store = storefrom;
            END IF;
  		END WHILE;
    END IF;
END$$

CREATE  PROCEDURE `addStockTransferOrderNew` (IN `orderno` VARCHAR(20), IN `orderdate` DATE, IN `storefrom` INT, IN `storeto` INT, IN `transitems` TEXT, IN `adminid` INT, IN `notes` TEXT)   BEGIN
	DECLARE transid, insid,checkid INT DEFAULT 0;
    SELECT user_id INTO checkid FROM users_tbl WHERE user_checkid=adminid ;
	INSERT INTO stock_transfers(stocktrans_order, stocktrans_date, stocktrans_strfrom, stocktrans_strto, stocktrans_prprdby, stocktrans_crtdby, stocktrans_notes)
    VALUES(orderno, orderdate, storefrom, storeto, checkid, checkid, notes);
	SET transid = LAST_INSERT_ID();
	IF transid > 0 THEN
    	SET @text := TRIM(BOTH '##' FROM transitems);
  		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 /* strstk_id of storestock_pricing */
                   	SET @stockid := 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 @batch := SUBSTRING_INDEX(@Gstr, '|', -1);
               	ELSE
                   	SET @expiry := SUBSTRING_INDEX(@Gstr, '|', -1);
               	END IF;
       			SET @icols := @icols + 1;
    		END WHILE;
    		INSERT INTO stocktransfer_details( stockorder_refer, stockorder_item, stockorder_quantity, stockorder_batch, stockorder_expiry )
           	VALUES( transid, @stockid, @qty, @batch, @expiry );
            SET insid = LAST_INSERT_ID();
            IF insid > 0 THEN
            	UPDATE storestock_pricing SET strstk_reserved = strstk_reserved + @qty
                WHERE strstk_id = @stockid;
                UPDATE storestock_master SET storestock_reserved = storestock_reserved + @qty
                WHERE storestock_item = @item AND storestock_store = storefrom;
            END IF;
  		END WHILE;
    END IF;
END$$

CREATE  PROCEDURE `addStockTransferOrderNewTest` (IN `orderno` VARCHAR(20), IN `orderdate` DATE, IN `storefrom` INT, IN `storeto` INT, IN `transitems` TEXT, IN `adminid` INT, IN `notes` TEXT)   BEGIN

    DECLARE done INT DEFAULT 0;

    -- Create temporary table
    DROP TEMPORARY TABLE IF EXISTS temp_stocktransfer_details;

    CREATE TEMPORARY TABLE temp_stocktransfer_details (
        stockorder_item INT,
        stockorder_quantity DECIMAL(10,2),
        stockorder_batch VARCHAR(50),
        stockorder_expiry DATE
    );

    IF transitems IS NOT NULL AND transitems <> '' THEN

        SET @text := TRIM(BOTH '##' FROM transitems);
        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 @stockid := 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 @batch := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSE
                    SET @expiry := SUBSTRING_INDEX(@Gstr, '|', -1);
                END IF;

                SET @icols := @icols + 1;

            END WHILE;

            -- Insert into TEMP table instead of real table
            INSERT INTO temp_stocktransfer_details (
                stockorder_item,
                stockorder_quantity,
                stockorder_batch,
                stockorder_expiry
            )
            VALUES (
                @stockid,
                @qty,
                @batch,
                STR_TO_DATE(@expiry, '%Y-%m-%d')
            );

        END WHILE;

    END IF;

    -- Display result
    SELECT * FROM temp_stocktransfer_details;

    -- Optional: explicitly drop (not required, auto drops after session)
    DROP TEMPORARY TABLE IF EXISTS temp_stocktransfer_details;

END$$

CREATE  PROCEDURE `addStorage` (IN `slabel` VARCHAR(50), IN `stype` INT(11), IN `stemp` VARCHAR(50), IN `shumidity` VARCHAR(50), IN `ssecurity` VARCHAR(50), IN `svolume` INT(11), IN `ssize` VARCHAR(50), IN `sload` VARCHAR(50), IN `sremarks` TEXT, IN `adminid` INT)   BEGIN
INSERT INTO storage_tbl(storage_label, storage_type, storage_temperature, storage_humidity, storage_security, storage_volume, storage_size, storage_load, storage_remarks,storage_crtdby)VALUES(slabel, stype, stemp, shumidity, ssecurity, svolume, ssize, sload, sremarks, adminid);
END$$

CREATE  PROCEDURE `addStore` (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 `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 '';
    
	INSERT INTO stores_tbl    
    ( store_type, store_name, store_address, store_phones, store_mobile, store_email, store_whatsapp, store_contact, store_contactno, store_contactemail, store_contactcell, store_contactwapp, store_contactat, store_regn, store_GST, store_TIN, store_power, store_water, store_location, store_remarks, store_crtdby, store_code, store_license, store_taxstate, store_pan )
	VALUES( stype, sname, address, phones, mobile, email, whatsapp, contact, contactno, conemail, concell, conwapp, contactat, regn, gstnum, tin, power, water, coords, remarks, adminid, scode, license, gstate, pan );
    
    SET distid = LAST_INSERT_ID();
    
    IF distid > 0 THEN
    	/* add 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 (distid, tempVal, adminid);
            SET delareas = INSERT(delareas, 1, frontlen + 1, '');
        END LOOP;
        
        /* Add timimgs */
        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( distid, @day, @sesn,  @tfrom, @tto, adminid );
  		END WHILE;
        
    END IF;
END$$

CREATE  PROCEDURE `addStoreIntend` (IN `intendno` VARCHAR(255), IN `dated` DATE, IN `strfrom` INT, IN `strto` INT, IN `notes` TEXT, IN `ordetails` TEXT, IN `adminid` INT)   BEGIN
	DECLARE ordid, itemcount,checkid INT DEFAULT 0;
    SELECT user_id INTO checkid FROM users_tbl WHERE user_checkid=adminid;
    INSERT INTO intends_tbl(intend_number, intend_date, intend_from, intend_to, intend_notes, intend_preprdby, intend_crtdby,intend_crtdon )
    VALUES(intendno, dated, strfrom, strto, notes, checkid, checkid,CURRENT_TIMESTAMP() );
    SET ordid = LAST_INSERT_ID();
    IF ordid > 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 @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,intdet_delivered )
            VALUES( ordid, @item, @product, @hsn, @qty, @stock,strfrom )
            ON DUPLICATE KEY UPDATE intdet_quantity = (intdet_quantity + @qty);
  		END WHILE;
        UPDATE intends_tbl SET intend_items = (SELECT COUNT(*) FROM intend_details WHERE intdet_id = ordid)
        WHERE intend_id = ordid;
    END IF;
END$$

CREATE  PROCEDURE `addTransferPacket` (IN `packetid` VARCHAR(20), IN `packtype` INT, IN `transorder` INT, IN `storefrom` INT, IN `storeto` INT, IN `notes` TEXT, IN `items` TEXT, IN `adminid` INT)   BEGIN
	DECLARE packid INT DEFAULT 0;
	INSERT INTO transfer_packets(transpack_type, transpack_refer, transpack_packid, transpack_from, transpack_to, transpack_notes, transpack_crtdby) VALUES(packtype, transorder, packetid, storefrom, storeto, notes, adminid);
    SET packid = LAST_INSERT_ID(); 
    
    IF packid > 0 THEN
    	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_items = (SELECT COUNT(*) FROM transferpack_items WHERE transferpack_packet = packid)
        WHERE transpack_id = packid;
    END IF;
    SELECT x.transpack_id, x.transpack_type, x.transpack_refer, x.transpack_packid, x.transpack_from, x.transpack_to, x.transpack_items,
    ( SELECT GROUP_CONCAT(CONCAT(y.transferpack_item, '|', fnGetProductFromPack(w.stockin_item, 0), '|', y.transferpack_qty, '|', w.stockin_batch, '|', w.stockin_expiry) SEPARATOR '##') 
     	FROM transferpack_items y
     	LEFT JOIN stock_inwards w ON w.stockin_id = y.transferpack_item
     	WHERE y.transferpack_packet = packid) AS items
    FROM transfer_packets x
    WHERE x.transpack_id = packid; 
    
END$$

CREATE  PROCEDURE `addTransferPacketNew` (IN `packetid` VARCHAR(20), IN `packtype` INT, IN `transorder` INT, IN `storefrom` INT, IN `storeto` INT, IN `notes` TEXT, IN `items` TEXT, IN `adminid` INT)   BEGIN
	DECLARE packid INT DEFAULT 0;
	INSERT INTO transfer_packets(transpack_type, transpack_refer, transpack_packid, transpack_from, transpack_to, transpack_notes, transpack_crtdby) VALUES(packtype, transorder, packetid, storefrom, storeto, notes, adminid);
    SET packid = LAST_INSERT_ID(); 
    
    IF packid > 0 THEN
    	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);
                ELSEIF @icols = 2 THEN
               		SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
               	ELSE
                   	SET @orditem := SUBSTRING_INDEX(@Gstr, '|', -1);
               	END IF;
        		SET @icols := @icols + 1;
     		END WHILE;
     		INSERT INTO transferpack_items( transferpack_packet, transferpack_item,transferpack_orditem, transferpack_qty, transferpack_packby ) 
           	VALUES( packid, @item, @orditem, @qty, adminid )
            ON DUPLICATE KEY UPDATE transferpack_qty = (transferpack_qty + @qty) ;
  		END WHILE;
        UPDATE transfer_packets 
        SET transpack_items = (SELECT COUNT(*) FROM transferpack_items WHERE transferpack_packet = packid)
        WHERE transpack_id = packid;
    END IF;
    SELECT x.transpack_id, x.transpack_type, x.transpack_refer, x.transpack_packid, x.transpack_from, x.transpack_to, x.transpack_items,
    ( SELECT GROUP_CONCAT(CONCAT(y.transferpack_item, '|', fnGetProductFromPack(w.stockin_item, 0), '|', y.transferpack_qty, '|', w.stockin_batch, '|', w.stockin_expiry) SEPARATOR '##') 
     	FROM transferpack_items y
    	LEFT JOIN storestock_pricing st ON st.strstk_id = y.transferpack_orditem
    	LEFT JOIN stock_inwards w ON w.stockin_id = st.strstk_refer 
     	WHERE y.transferpack_packet = packid) AS items
    FROM transfer_packets x
    WHERE x.transpack_id = packid;   
    
END$$

CREATE  PROCEDURE `addTransferStock` (IN `packetid` INT, IN `supply` VARCHAR(255), IN `charges` VARCHAR(255), IN `adminid` INT, IN `notes` TEXT)   BEGIN 
	DECLARE newrec, inwardid INT DEFAULT 0;
    DECLARE bDone, ordid, paktid, stkitem, initem, pktitems INT DEFAULT 0;
    DECLARE recvd, shrt, frmstor, tostor INT DEFAULT 0;
    DECLARE curs CURSOR FOR SELECT orderid, packetid, stockitem, item, received, short, storefrom, storeto, packitems FROM temp_transfers;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
    
	DROP TEMPORARY TABLE IF EXISTS temp_transfers;
	CREATE TEMPORARY TABLE IF NOT EXISTS temp_transfers AS (SELECT * FROM temptransfer);
    
    INSERT INTO temp_transfers ( packetid, orderid, stockitem, item, product, qty, ordbatch, ordexpiry, qrcode, mrp, ordqty, storefrom, storeto, checkby, receiveby, packitems ) 
    SELECT x.transferpack_packet, t.transpack_refer, x.transferpack_item, p.prodpack_id, p.prodpack_product, x.transferpack_qty, s.stockin_batch, s.stockin_expiry, s.stockin_qrcode, s.stockin_mrp, x.transferpack_qty, t.transpack_from, t.transpack_to, adminid, adminid, t.transpack_items 
    FROM transferpack_items x 
    LEFT JOIN stock_inwards s ON s.stockin_id = x.transferpack_item 
    LEFT JOIN transfer_packets t ON t.transpack_id = x.transferpack_packet 
    LEFT JOIN product_packing p ON p.prodpack_id = s.stockin_item 
    WHERE x.transferpack_packet = packetid; 
 
 	SET @text := TRIM(BOTH '##' FROM supply);
  	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 @short := SUBSTRING_INDEX(@Gstr, '|', -1);
            END IF;
        	SET @icols := @icols + 1;
      	END WHILE;
		UPDATE temp_transfers SET received = @qty, short = @short 
        WHERE stockitem = @item;
    END WHILE;
    
    INSERT INTO stock_inwards (stockin_store, stockin_item, stockin_invref, stockin_mode, stockin_qrcode, stockin_supdate, stockin_mrp, stockin_batch, stockin_expiry, stockin_inward, stockin_short, stockin_balance, stockin_crtdby)
    SELECT storeto, item, orderid, 2, qrcode, CURRENT_DATE(), mrp, ordbatch, ordexpiry, received, short, received, adminid  
    FROM temp_transfers WHERE received > 0;  
    # SELECT * FROM temp_transfers;
    
    OPEN curs;
    SET bDone = 0;
    #REPEAT
    housekeep:LOOP
    	FETCH curs INTO ordid, paktid, stkitem, initem, recvd, shrt, frmstor, tostor, pktitems;
        IF bDone = 1 THEN 
        	LEAVE housekeep;
        END IF;
        # SELECT ordid, paktid, stkitem, initem, recvd, shrt, frmstor, tostor;
        IF recvd > 0 THEN
        	# add store stock pricing
        	
            # update store stocks (source)
            UPDATE stock_inwards SET stockin_transfer = stockin_transfer + recvd, stockin_reserved = stockin_reserved - recvd, stockin_balance = stockin_balance - recvd WHERE stockin_id = initem;
            UPDATE storestock_master SET storestock_available = storestock_available - recvd, storestock_reserved = storestock_reserved - recvd
            WHERE storestock_item = initem AND storestock_store = frmstor;
            # update store stocks (target)
            INSERT INTO storestock_master( storestock_item, storestock_store, storestock_available, storestock_inward )
            VALUES(initem, tostor, recvd, recvd) 
            ON DUPLICATE KEY UPDATE storestock_available = storestock_available + recvd, 
            storestock_inward = storestock_inward + recvd;
            #update transfer item status
            UPDATE transferpack_items SET transferpack_recieved = recvd, transferpack_short = shrt, transferpack_status = 10 WHERE transferpack_packet = paktid AND transferpack_item = stkitem;
        END IF;
    END LOOP housekeep;
    # update transfer status
	IF (SELECT COUNT(*) FROM transferpack_items tri 
        WHERE tri.transferpack_status = 10 AND tri.transferpack_packet = packetid) = pktitems THEN
        	UPDATE transfer_packets SET transpack_status = 15 
            WHERE transpack_id = packetid;
    END IF;
    # update transfer order status
    #UNTIL bDone END REPEAT;
    CLOSE curs;
    DROP TEMPORARY TABLE IF EXISTS temp_transfers;
END$$

CREATE  PROCEDURE `addTransferStockNew` (IN `packetid` INT, IN `supply` VARCHAR(255), IN `charges` VARCHAR(255), IN `adminid` INT, IN `notes` TEXT)   BEGIN 
	DECLARE newrec, inwardid INT DEFAULT 0;
    DECLARE bDone, ordid, paktid, stkitem, initem, pktitems INT DEFAULT 0;
    DECLARE recvd, shrt, frmstor, tostor INT DEFAULT 0;
    DECLARE curs CURSOR FOR SELECT orderid, packetid, stockitem, item, received, short, storefrom, storeto, packitems FROM temp_transfers;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
    
	DROP TEMPORARY TABLE IF EXISTS temp_transfers;
	CREATE TEMPORARY TABLE IF NOT EXISTS temp_transfers AS (SELECT * FROM temptransfer);
    
    INSERT INTO temp_transfers ( packetid, orderid, stockitem, item, product, qty, ordbatch, ordexpiry, qrcode, mrp, ordqty, storefrom, storeto, checkby, receiveby, packitems ) 
    SELECT x.transferpack_packet, t.transpack_refer, x.transferpack_item, p.prodpack_id, p.prodpack_product, x.transferpack_qty, s.stockin_batch, s.stockin_expiry, s.stockin_qrcode, s.stockin_mrp, x.transferpack_qty, t.transpack_from, t.transpack_to, adminid, adminid, t.transpack_items 
    FROM transferpack_items x 
    LEFT JOIN storestock_pricing sp ON sp.strstk_id = x.transferpack_item
    LEFT JOIN stock_inwards s ON s.stockin_id = sp.strstk_refer 
    LEFT JOIN transfer_packets t ON t.transpack_id = x.transferpack_packet 
    LEFT JOIN product_packing p ON p.prodpack_id = s.stockin_item 
    WHERE x.transferpack_packet = packetid; 
 
 	SET @text := TRIM(BOTH '##' FROM supply);
  	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 @short := SUBSTRING_INDEX(@Gstr, '|', -1);
            END IF;
        	SET @icols := @icols + 1;
      	END WHILE;
		UPDATE temp_transfers SET received = @qty, short = @short 
        WHERE stockitem = @item;
    END WHILE;
    
    # SELECT * FROM temp_transfers;
    
    OPEN curs;
    SET bDone = 0;
    housekeep:LOOP
    	FETCH curs INTO ordid, paktid, stkitem, initem, recvd, shrt, frmstor, tostor, pktitems;
        IF bDone = 1 THEN 
        	LEAVE housekeep;
        END IF;
        # SELECT ordid, paktid, stkitem, initem, recvd, shrt, frmstor, tostor;
        IF recvd > 0 THEN
        	# add to store stock pricing
        	INSERT INTO storestock_pricing ( strstk_refer, strstk_store, strstk_item, strstk_product, strstk_msp, strstk_mrp, strstk_cost, strstk_last, strstk_inward, strstk_stock, strstk_crtdby, strstk_minorder, strstk_maxorder, strstk_dealofday, strstk_dealfrom, strstk_dealto, strstk_offer, strstk_offerfrom, strstk_offerto, strstk_priority ) 
            SELECT initem, tostor, stkitem, w.strstk_product, w.strstk_msp, w.strstk_mrp, w.strstk_cost, w.strstk_last, recvd, recvd, adminid, w.strstk_minorder, w.strstk_maxorder, w.strstk_dealofday, w.strstk_dealfrom, w.strstk_dealto, w.strstk_offer, w.strstk_offerfrom, w.strstk_offerto, w.strstk_priority FROM storestock_pricing w WHERE w.strstk_id = strstk_refer;
            SET newrec = LAST_INSERT_ID();
            
            # update store stocks (source)
            UPDATE stock_inwards SET stockin_transfer = stockin_transfer + recvd, stockin_reserved = stockin_reserved - recvd, stockin_balance = stockin_balance - recvd WHERE stockin_id = initem;
            UPDATE storestock_master SET storestock_available = storestock_available - recvd, storestock_reserved = storestock_reserved - recvd
            WHERE storestock_item = initem AND storestock_store = frmstor;
            
            # update store stocks (target)
            INSERT INTO storestock_master( storestock_item, storestock_store, storestock_available, storestock_inward )
            VALUES(initem, tostor, recvd, recvd) 
            ON DUPLICATE KEY UPDATE storestock_available = storestock_available + recvd, 
            storestock_inward = storestock_inward + recvd;
            
            #update transfer item status
            UPDATE transferpack_items SET transferpack_recieved = recvd, transferpack_short = shrt, transferpack_status = 10 WHERE transferpack_packet = paktid AND transferpack_item = stkitem;
        END IF;
    END LOOP housekeep;
    # update transfer status
	IF (SELECT COUNT(*) FROM transferpack_items tri 
        WHERE tri.transferpack_status = 10 AND tri.transferpack_packet = packetid) = pktitems THEN
        	UPDATE transfer_packets SET transpack_status = 15 
            WHERE transpack_id = packetid;
    END IF;
    # update transfer order status
    IF (SELECT COUNT(*) FROM transfer_packets tp 
        WHERE tp.transpack_status < 15 AND tp.transpack_refer = ordid ) = 0 THEN
        	UPDATE stock_transfers SET stocktrans_status = 10 WHERE stocktrans_id = ordid;
    END IF;
    CLOSE curs;
    DROP TEMPORARY TABLE IF EXISTS temp_transfers;
END$$

CREATE  PROCEDURE `addUserProgramRoles` (IN `rolename` VARCHAR(50), IN `prgmids` MEDIUMTEXT, IN `adminid` INT)   begin
insert into user_program(usrprog_name,usrprog_programs,usrprog_crtby) values(rolename,prgmids,adminid);
END$$

CREATE  PROCEDURE `addUsers` (IN `userlogin` VARCHAR(100), IN `userpassword` VARCHAR(100), IN `staffid` INT, IN `staffname` VARCHAR(100), IN `programid` INT, IN `programcontains` TEXT, IN `adminid` INT)   begin

insert into users_tbl(user_login,user_password,user_staffid,user_staffname,user_programid,user_programcontains,user_crtdby) values(userlogin,userpassword,staffid,staffname,programid,programcontains,adminid);
END$$

CREATE  PROCEDURE `addVendorSupply` (IN `vendor` INT, IN `ventype` INT, IN `product` INT, IN `packing` INT, IN `price` DECIMAL(9,2), IN `minq` INT, IN `maxq` INT, IN `eoq` INT, IN `deldays` INT, IN `notes` VARCHAR(255), IN `adminid` INT)   BEGIN
	DECLARE vcount, vstatus, vid INT DEFAULT 0;
	SELECT COUNT(*), x.vendsup_status, x.vendsup_id INTO vcount, vstatus, vid 
    FROM vendor_supplies x 
    WHERE x.vendsup_product = product AND x.vendsup_packing = packing AND x.vendsup_vendor = vendor AND x.vendsup_type = ventype; 
    
    IF vcount = 0 THEN
		INSERT INTO vendor_supplies( vendsup_vendor, vendsup_type, vendsup_product, vendsup_packing, vendsup_price, vendsup_minqty, vendsup_maxqty, vendsup_eoq, vendsup_deliver, vendsup_notes, vendsup_crtdby )
    	VALUES( vendor, ventype, product, packing, price, minq, maxq, eoq, deldays, notes, adminid);
    ELSE
    	UPDATE vendor_supplies SET vendsup_vendor = vendor, vendsup_type = ventype, vendsup_product = product, vendsup_packing = packing, vendsup_price = price, vendsup_minqty = minq, vendsup_maxqty = maxq, vendsup_eoq = eoq, vendsup_deliver = deldays, vendsup_notes = notes, vendsup_updby = adminid WHERE vendsup_id = vid;
    END IF;
END$$

CREATE  PROCEDURE `add_slider` (IN `slider_type` INT, IN `slider_image` VARCHAR(225), IN `slider_product` TEXT, IN `slider_disocunt` INT, IN `slider_sort` INT, IN `slider_disctype` INT)   BEGIN
INSERT INTO `tbl_homepageslier`( `slider_type`, `slider_image`, `slider_product`, `slider_disocunt`,`slider_disctype`, `slider_sort`) VALUES (slider_type, slider_image, slider_product, slider_disocunt,slider_disctype, slider_sort);
END$$

CREATE  PROCEDURE `AllocateProductStock` (IN `p_user_id` INT, IN `order_id` INT)   BEGIN
    -- Declare variables
    DECLARE v_cart_id, v_product_id, v_item_id, v_stock_id, v_required_qty INT;
    DECLARE row_count INT DEFAULT 0;

    -- Create a temporary table to store selected cart items
    CREATE TEMPORARY TABLE IF NOT EXISTS TempUserCart AS
    SELECT cart_id, product_id, prodpack_id, batch_id, quantity
    FROM user_cart
    WHERE user_id = p_user_id AND order_id=0
    AND (quantity > (SELECT (e1.strstk_stock - e1.strstk_reserved) 
                      FROM storestock_pricing e1 
                      WHERE e1.strstk_item = user_cart.prodpack_id 
                      AND e1.strstk_id = user_cart.batch_id AND e1.strstk_product=user_cart.product_id));
                      
                     /* INSERT INTO order_details(ordet_order,ordet_cartid, ordet_productid, ordet_quantity, ordet_producpackid, order_batchid,order_mrp,order_msp,order_disc) SELECT order_id,cart_id,product_id,quantity,prodpack_id,batch_id,e1.strstk_mrp,e1.strstk_msp,e1.strstk_discount FROM user_cart WHERE user_id=p_user_id AND (quantity <= (SELECT (e1.strstk_stock - e1.strstk_reserved) 
                      FROM storestock_pricing e1 
                      WHERE e1.strstk_item = user_cart.prodpack_id 
                      AND e1.strstk_id = user_cart.batch_id AND e1.strstk_product=user_cart.product_id));
*/
INSERT INTO order_details (
    ordet_order, ordet_cartid, ordet_productid, ordet_quantity, 
    ordet_producpackid, order_batchid, order_mrp, order_msp, order_disc
) 
SELECT 
    order_id,cart_id,product_id,quantity,prodpack_id,batch_id, sp.strstk_mrp, sp.strstk_msp, sp.strstk_discount 
FROM user_cart uc 
JOIN storestock_pricing sp 
    ON sp.strstk_item = uc.prodpack_id 
    AND sp.strstk_id = uc.batch_id 
    AND sp.strstk_product = uc.product_id 
WHERE uc.user_id = p_user_id AND uc.order_id=0
AND uc.quantity <= (sp.strstk_stock - sp.strstk_reserved);
    -- Get the number of rows to process
    SELECT COUNT(*) INTO row_count FROM TempUserCart;

    -- Loop through the table using WHILE
    WHILE row_count > 0 DO
        -- Get one row from the table
        SELECT cart_id, product_id, prodpack_id, batch_id, quantity
        INTO v_cart_id, v_product_id, v_item_id, v_stock_id, v_required_qty
        FROM TempUserCart
        LIMIT 1;

      -- Call the stored procedure to generate the temporary table
CALL AddProductStockk(v_product_id, v_item_id, v_stock_id, v_required_qty,order_id,v_cart_id);

        -- Remove processed row
        DELETE FROM TempUserCart WHERE cart_id = v_cart_id;

        -- Update row count
        SELECT COUNT(*) INTO row_count FROM TempUserCart;
    END WHILE;

    -- Cleanup temporary table
    DROP TEMPORARY TABLE IF EXISTS TempUserCart;
   
END$$

CREATE  PROCEDURE `AllocateProductStockk` (IN `p_user_id` INT, IN `order_id` INT)   BEGIN
    -- Declare variables
    DECLARE v_cart_id, v_product_id, v_item_id, v_stock_id, v_required_qty INT;
    DECLARE row_count INT DEFAULT 0;

    -- Create a temporary table to store selected cart items
    CREATE TEMPORARY TABLE IF NOT EXISTS TempUserCart AS
    SELECT cart_id, product_id, prodpack_id, batch_id, quantity
    FROM user_cart
    WHERE user_id = p_user_id AND order_id=order_id
    AND (quantity > (SELECT (e1.strstk_stock - e1.strstk_reserved) 
                      FROM storestock_pricing e1 
                      WHERE e1.strstk_item = user_cart.prodpack_id 
                      AND e1.strstk_id = user_cart.batch_id AND e1.strstk_product=user_cart.product_id));
                      
                     /* INSERT INTO order_details(ordet_order,ordet_cartid, ordet_productid, ordet_quantity, ordet_producpackid, order_batchid,order_mrp,order_msp,order_disc) SELECT order_id,cart_id,product_id,quantity,prodpack_id,batch_id,e1.strstk_mrp,e1.strstk_msp,e1.strstk_discount FROM user_cart WHERE user_id=p_user_id AND (quantity <= (SELECT (e1.strstk_stock - e1.strstk_reserved) 
                      FROM storestock_pricing e1 
                      WHERE e1.strstk_item = user_cart.prodpack_id 
                      AND e1.strstk_id = user_cart.batch_id AND e1.strstk_product=user_cart.product_id));
*/
INSERT INTO order_details (
    ordet_order, ordet_cartid, ordet_productid, ordet_quantity, 
    ordet_producpackid, order_batchid, order_mrp, order_msp, order_disc
) 
SELECT 
    order_id,cart_id,product_id,quantity,prodpack_id,batch_id, sp.strstk_mrp, sp.strstk_msp, sp.strstk_discount 
FROM user_cart uc 
JOIN storestock_pricing sp 
    ON sp.strstk_item = uc.prodpack_id 
    AND sp.strstk_id = uc.batch_id 
    AND sp.strstk_product = uc.product_id 
WHERE uc.user_id = p_user_id AND uc.order_id=order_id
AND uc.quantity <= (sp.strstk_stock - sp.strstk_reserved);
    -- Get the number of rows to process
    SELECT COUNT(*) INTO row_count FROM TempUserCart;

    -- Loop through the table using WHILE
    WHILE row_count > 0 DO
        -- Get one row from the table
        SELECT cart_id, product_id, prodpack_id, batch_id, quantity
        INTO v_cart_id, v_product_id, v_item_id, v_stock_id, v_required_qty
        FROM TempUserCart
        LIMIT 1;

      -- Call the stored procedure to generate the temporary table
CALL AddProductStockk(v_product_id, v_item_id, v_stock_id, v_required_qty,order_id,v_cart_id);

        -- Remove processed row
        DELETE FROM TempUserCart WHERE cart_id = v_cart_id;

        -- Update row count
        SELECT COUNT(*) INTO row_count FROM TempUserCart;
    END WHILE;

    -- Cleanup temporary table
    DROP TEMPORARY TABLE IF EXISTS TempUserCart;
   
END$$

CREATE  PROCEDURE `approveIntend` (IN `intendid` INT, IN `notes` TEXT, IN `stores` TEXT, IN `suppliers` TEXT, IN `secreteid` INT, IN `isfinal` INT)   BEGIN 
	DECLARE uflag, adminid INT DEFAULT 0;
   	SELECT user_id INTO adminid FROM users_tbl  WHERE user_checkid=secreteid;
    INSERT INTO intend_allocations ( intdalloc_intend, intdalloc_notes, intdalloc_crtdby )
    VALUES( intendid, notes, adminid ) 
    ON DUPLICATE KEY UPDATE intdalloc_notes = notes, intdalloc_updby = adminid;
    #IF ROW_COUNT() > 0 THEN
    IF trim(stores) <> '' THEN
    	DELETE FROM intend_allocation_items
    	WHERE intdallocit_intend = intendid AND intdallocit_method = 1 AND intdallocit_status < 5;
    	SET uflag = 1; 
        SET @text := TRIM(BOTH '##' FROM stores);
  		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 @store := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSE
                    SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
                END IF;
        		SET @icols := @icols + 1;
           	END WHILE;
       		#SELECT @item, @store, @qty;
           	/*DELETE FROM intend_allocation_items 
    	    WHERE intend_allocation_items.intdallocit_intend = intendid AND intend_allocation_items.intdallocit_method = 1 and intend_allocation_items.intdallocit_item=@item;*/
            INSERT INTO intend_allocation_items( intdallocit_intend, intdallocit_item, intdallocit_method, intdallocit_source, 				intdallocit_type, intdallocit_quantity ) 
            VALUES( intendid, @item, 1, @store, 0, @qty);
  		END WHILE;
        
       
   	END IF;
        
   	IF trim(suppliers) <> '' THEN
    	SET uflag = 1;
    	DELETE FROM intend_allocation_items 
        WHERE intdallocit_intend = intendid AND intdallocit_method = 2 AND intdallocit_status < 5; 
        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 @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 @vendsid := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 3 THEN
                   	SET @store := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 4 THEN
                   	SET @stype := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSEIF @icols = 5 THEN
                    SET @price  := SUBSTRING_INDEX(@Gstr, '|', -1);
                ELSE
                    SET @qty := SUBSTRING_INDEX(@Gstr, '|', -1);
                END IF;
        		SET @icols := @icols + 1;
                
           	END WHILE;
            /*DELETE FROM intend_allocation_items 
            WHERE intdallocit_intend = intendid AND intdallocit_method = 2 AND intdallocit_item = @item;*/
     		INSERT INTO intend_allocation_items( intdallocit_intend, intdallocit_item,intdallocit_vendsup, intdallocit_method, intdallocit_source, intdallocit_type, intdallocit_quantity,intdallocit_ordrprice) 
            VALUES( intendid, @item,@vendsid, 2, @store, @stype, @qty,@price ) ;
  		END WHILE;
       
        
        END IF;
        
        IF uflag = 1 THEN
        	UPDATE intend_details SET intdet_allotted = 0, intdet_status = 1 
        		WHERE intdet_id = intendid /* AND intdet_status <> 5 */;
			UPDATE intend_details 
        	SET intdet_allotted = (SELECT SUM(y.intdallocit_quantity) FROM intend_allocation_items y 
                WHERE y.intdallocit_intend = intendid AND y.intdallocit_item = intdet_item), 
        		intdet_status = 5, intdet_refer = intendid 
        	WHERE intdet_id = intendid AND intdet_item IN(SELECT intdallocit_item FROM intend_allocation_items WHERE intdallocit_intend = intendid AND intdallocit_status = 1);
        END IF;
        IF isfinal = 1 THEN
        	UPDATE intends_tbl SET intend_status = 5, intend_apprvedby = adminid 
        	WHERE intend_id = intendid;
        END IF;
    #END IF;
END$$

CREATE  PROCEDURE `asignDataForAllDataEntries` (IN `dates` DATE, IN `pharmaname` TEXT, IN `limits` INT)   BEGIN
    DECLARE front TEXT DEFAULT '';
    DECLARE frontlen INT DEFAULT 0;
    DECLARE tempVal TEXT DEFAULT '';

    WHILE pharmaname IS NOT NULL AND LENGTH(TRIM(pharmaname)) > 0 DO
        -- Extract first staff id
        SET front = SUBSTRING_INDEX(pharmaname, ',', 1);
        SET frontlen = LENGTH(front);
        SET tempVal = TRIM(front);

        -- Update "limits" rows for this staff
        UPDATE products_entry_tbl 
        SET assigned_for = tempVal, 
            assigned_date = dates
        WHERE assigned_date IS NULL
        LIMIT limits;

        -- Remove processed staff id from list
        SET pharmaname = INSERT(pharmaname, 1, frontlen + 1, '');
        SET pharmaname = TRIM(BOTH ',' FROM pharmaname);
    END WHILE;
END$$

CREATE  PROCEDURE `asignDataForDataEntries` (IN `in_date` DATE, IN `in_pharmaname` TEXT, IN `in_limits` INT)   BEGIN
    DECLARE idx INT DEFAULT 1;
    DECLARE total INT;
    DECLARE pharma_id VARCHAR(50);

    -- count how many pharmacist IDs are in the list
    SET total = LENGTH(in_pharmaname) - LENGTH(REPLACE(in_pharmaname, ',', '')) + 1;

    WHILE idx <= total DO
        -- extract one pharmacist id
        SET pharma_id = TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(in_pharmaname, ',', idx), ',', -1));

        -- assign rows
        UPDATE products_entry_tbl
        SET assigned_for = pharma_id,
            assigned_date = in_date
        WHERE assigned_date IS NULL
        ORDER BY product_id ASC
        LIMIT in_limits;

        SET idx = idx + 1;
    END WHILE;
END$$

CREATE  PROCEDURE `asignProductDataForDataEntries` (IN `dates` DATE, IN `pharmaname` INT, IN `pdtval` TEXT)   BEGIN
SET @sql = CONCAT(
    'UPDATE products_entry_tbl 
     SET assigned_for=', pharmaname,
    ', assigned_date=''', dates, '''',
    ',assigned_status=1  WHERE product_id IN (', pdtval, ')'
);

PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$

CREATE  PROCEDURE `batchWisePurchaseReturn` (IN `chooseval` INT, IN `batchno` VARCHAR(255), IN `branchid` INT)   BEGIN
IF branchid > 1 THEN
    IF chooseval=1 THEN
      SELECT s.stockin_id,s.stockin_batch,s.stockin_item,s.stockin_damaged,fnGetProductFromPack(s.stockin_item, 0) AS invitem, ii.invoice_amount,i.invdet_taxamt,i.invdet_cst,i.invdet_sst,ii.invoice_vendertype,ii.invoice_vendor,fnGetVendorName(ii.invoice_vendertype, ii.invoice_vendor) AS vendor,s.stockin_expiry,s.stockin_inward AS original_qty,(sp.strstk_stock - sp.strstk_reserved)AS stock, ss.store_id,sp.strstk_msp,sp.strstk_mrp,sp.strstk_discount,i.invdet_cstpc,i.invdet_sstpc, sp.strstk_id,ss.store_code,ss.store_name,ii.invoice_id,ii.invoice_number,ii.invoice_dated ,i.invdet_mrp,i.invdet_ptr,i.invdet_discpc,i.invdet_discount ,(i.invdet_cstpc + i.invdet_sstpc)as total_gst FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=s.stockin_store
    WHERE s.stockin_batch=batchno AND s.stockin_store=branchid AND (sp.strstk_stock - sp.strstk_reserved)>0;
    ELSEIF chooseval=2 THEN
        SELECT s.stockin_id,s.stockin_batch,s.stockin_item,s.stockin_damaged,fnGetProductFromPack(s.stockin_item, 0) AS invitem, ii.invoice_amount,i.invdet_taxamt,i.invdet_cst,i.invdet_sst,ii.invoice_vendertype,ii.invoice_vendor,fnGetVendorName(ii.invoice_vendertype, ii.invoice_vendor) AS vendor,s.stockin_expiry,s.stockin_inward AS original_qty,(sp.strstk_stock - sp.strstk_reserved)AS stock,  ss.store_id,sp.strstk_msp,sp.strstk_mrp,sp.strstk_discount,i.invdet_cstpc,i.invdet_sstpc,  sp.strstk_id,ss.store_code,ss.store_name,ii.invoice_id,ii.invoice_number,ii.invoice_dated,i.invdet_mrp,i.invdet_ptr,i.invdet_discpc,i.invdet_discount,(i.invdet_cstpc + i.invdet_sstpc)as total_gst FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=s.stockin_store
    WHERE i.invdet_wopo=1 AND s.stockin_store=branchid AND (sp.strstk_stock - sp.strstk_reserved)>0;
    ELSEIF chooseval=3 THEN
        SELECT s.stockin_id,s.stockin_batch,s.stockin_item,s.stockin_damaged,fnGetProductFromPack(s.stockin_item, 0) AS invitem, ii.invoice_amount,i.invdet_taxamt,i.invdet_cst,i.invdet_sst,ii.invoice_vendertype,ii.invoice_vendor,fnGetVendorName(ii.invoice_vendertype, ii.invoice_vendor) AS vendor,s.stockin_expiry,s.stockin_inward AS original_qty,(sp.strstk_stock - sp.strstk_reserved)AS stock,  ss.store_id,sp.strstk_msp,sp.strstk_mrp,sp.strstk_discount,i.invdet_cstpc,i.invdet_sstpc,  sp.strstk_id,ss.store_code,ss.store_name,ii.invoice_id,ii.invoice_number,ii.invoice_dated,i.invdet_mrp,i.invdet_ptr,i.invdet_discpc,i.invdet_discount,(i.invdet_cstpc + i.invdet_sstpc)as total_gst FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=s.stockin_store
    WHERE s.stockin_damaged > 0 AND s.stockin_store=branchid AND (sp.strstk_stock - sp.strstk_reserved)>0;
    ELSE
     SELECT s.stockin_id,s.stockin_batch,s.stockin_item,s.stockin_damaged,fnGetProductFromPack(s.stockin_item, 0) AS invitem, ii.invoice_amount,i.invdet_taxamt,i.invdet_cst,i.invdet_sst,ii.invoice_vendertype,ii.invoice_vendor,fnGetVendorName(ii.invoice_vendertype, ii.invoice_vendor) AS vendor,s.stockin_expiry,s.stockin_inward AS original_qty,(sp.strstk_stock - sp.strstk_reserved)AS stock, ss.store_id,  sp.strstk_id,i.invdet_cstpc,i.invdet_sstpc, (i.invdet_cstpc + i.invdet_sstpc)as total_gst,sp.strstk_msp,sp.strstk_mrp,sp.strstk_discount,ss.store_code,ss.store_name,ii.invoice_id,ii.invoice_number,ii.invoice_dated,i.invdet_mrp,i.invdet_ptr,i.invdet_discpc,i.invdet_discount FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=s.stockin_store
    WHERE ( s.stockin_expiry <= DATE_ADD(CURDATE(), INTERVAL 2 MONTH) )AND  (sp.strstk_stock - sp.strstk_reserved)>0 AND s.stockin_store=branchid ORDER BY  ii.invoice_number;
            END IF;
 ELSE
 IF chooseval=1 THEN
      SELECT s.stockin_id,s.stockin_batch,s.stockin_item,s.stockin_damaged,fnGetProductFromPack(s.stockin_item, 0) AS invitem, ii.invoice_amount,i.invdet_taxamt,i.invdet_cst,i.invdet_sst,ii.invoice_vendertype,ii.invoice_vendor,fnGetVendorName(ii.invoice_vendertype, ii.invoice_vendor) AS vendor,s.stockin_expiry,s.stockin_inward AS original_qty,(sp.strstk_stock - sp.strstk_reserved)AS stock, ss.store_id,i.invdet_cstpc,i.invdet_sstpc, (i.invdet_cstpc + i.invdet_sstpc)as total_gst, sp.strstk_msp,sp.strstk_mrp,sp.strstk_discount,sp.strstk_id,ss.store_code,ss.store_name,ii.invoice_id,ii.invoice_number,ii.invoice_dated,i.invdet_mrp,i.invdet_ptr,i.invdet_discpc,i.invdet_discount FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=s.stockin_store
    WHERE s.stockin_batch=batchno AND (sp.strstk_stock - sp.strstk_reserved)>0;
ELSEIF chooseval=2 THEN
        SELECT s.stockin_id,s.stockin_batch,s.stockin_item,s.stockin_damaged,fnGetProductFromPack(s.stockin_item, 0) AS invitem, ii.invoice_amount,i.invdet_taxamt,i.invdet_cst,i.invdet_sst,ii.invoice_vendertype,ii.invoice_vendor,fnGetVendorName(ii.invoice_vendertype, ii.invoice_vendor) AS vendor,s.stockin_expiry,s.stockin_inward AS original_qty,(sp.strstk_stock - sp.strstk_reserved)AS stock,  ss.store_id, sp.strstk_id,i.invdet_cstpc,i.invdet_sstpc,(i.invdet_cstpc + i.invdet_sstpc)as total_gst, sp.strstk_msp,sp.strstk_mrp,sp.strstk_discount,ss.store_code,ss.store_name,ii.invoice_id,ii.invoice_number,ii.invoice_dated,i.invdet_mrp,i.invdet_ptr,i.invdet_discpc,i.invdet_discount FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=sp.strstk_store
    WHERE i.invdet_wopo=1 AND (sp.strstk_stock - sp.strstk_reserved)>0;
ELSEIF chooseval=3 THEN
        SELECT s.stockin_id,s.stockin_batch,s.stockin_item,s.stockin_damaged,fnGetProductFromPack(s.stockin_item, 0) AS invitem, ii.invoice_amount,i.invdet_taxamt,i.invdet_cst,i.invdet_sst,ii.invoice_vendertype,ii.invoice_vendor,fnGetVendorName(ii.invoice_vendertype, ii.invoice_vendor) AS vendor,s.stockin_expiry,s.stockin_inward AS original_qty,(sp.strstk_stock - sp.strstk_reserved)AS stock,  ss.store_id, sp.strstk_id,i.invdet_cstpc,i.invdet_sstpc,(i.invdet_cstpc + i.invdet_sstpc)as total_gst, sp.strstk_msp,sp.strstk_mrp,sp.strstk_discount,ss.store_code,ss.store_name,ii.invoice_id,ii.invoice_number,ii.invoice_dated,i.invdet_mrp,i.invdet_ptr,i.invdet_discpc,i.invdet_discount FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=s.stockin_store
    WHERE s.stockin_damaged != 0 AND (sp.strstk_stock - sp.strstk_reserved)>0;
ELSE
 SELECT s.stockin_id,s.stockin_damaged, s.stockin_batch,s.stockin_item,fnGetProductFromPack(s.stockin_item, 0) AS invitem, ii.invoice_amount,i.invdet_taxamt,i.invdet_cst,i.invdet_sst,ii.invoice_vendertype,ii.invoice_vendor,fnGetVendorName(ii.invoice_vendertype, ii.invoice_vendor) AS vendor,s.stockin_expiry,s.stockin_inward AS original_qty,(sp.strstk_stock - sp.strstk_reserved)AS stock, ss.store_id,sp.strstk_id,sp.strstk_msp,sp.strstk_mrp,sp.strstk_discount,i.invdet_cstpc,i.invdet_sstpc,(i.invdet_cstpc + i.invdet_sstpc)as total_gst, ss.store_code,ss.store_name,ii.invoice_id,ii.invoice_number,ii.invoice_dated,i.invdet_mrp,i.invdet_ptr,i.invdet_discpc,i.invdet_discount FROM stock_inwards s
 JOIN invoice_details i ON i.invdet_id=s.stockin_invref
JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice
 JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
 JOIN stores_tbl ss on ss.store_id=s.stockin_store 
WHERE s.stockin_expiry <= DATE_ADD(CURDATE(), INTERVAL 2 MONTH) AND (sp.strstk_stock - sp.strstk_reserved)>0 ORDER BY s.stockin_expiry;
        END IF;
 END IF ;
END$$

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

CREATE  PROCEDURE `CancelOrderbyPricingID` (IN `strstkid` INT, IN `qty` INT, IN `propackid` INT)   BEGIN
UPDATE storestock_pricing p SET p.strstk_reserved=p.strstk_reserved-qty , p.strstk_stock=p.strstk_stock+qty WHERE p.strstk_id=strstkid;

UPDATE storestock_master m SET m.storestock_reserved= m.storestock_reserved-qty , m.storestock_available=m.storestock_available+qty WHERE m.storestock_item=propackid AND m.storestock_store=storeid;

END$$

CREATE  PROCEDURE `cancelPurchaseOrder` (IN `poid` INT, IN `adminid` INT)   BEGIN
	DECLARE delstat INT DEFAULT 0;
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
    	ROLLBACK;
        SET delstat = 0;
    END;
    IF (SELECT purchord_status FROM purchase_orders WHERE purchord_id = poid) < 5 THEN
        START TRANSACTION;
            UPDATE purchase_orders SET purchord_status = 0, purchord_updby = adminid 
            WHERE purchord_id = poid;
            UPDATE purchase_details SET podetail_status = 0, podetail_updby = adminid
            WHERE podetail_order = poid;
            SET delstat = 1;
        COMMIT;
    END IF;
    SELECT delstat;
END$$

CREATE  PROCEDURE `cancelUserOrderDetailsbyOrderId` (IN `orderId` VARCHAR(200), IN `userid` INT, IN `reason` TEXT)   BEGIN
DECLARE ordid ,ord_ids ,store,item INT DEFAULT 0;
DECLARE resultString ,resultQty ,singleValue,singleQty TEXT;
DECLARE phone VARCHAR(225);

SELECT o.order_id,c.customer_phone INTO ordid,phone  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=0 , o.order_delivery=0, o.order_message=reason, o.orders_cancelled=CURRENT_TIMESTAMP WHERE o.order_orderid=orderId and o.order_customer=userid;
 
 UPDATE order_details o set o.ordet_status=0, o.ordet_active=0, o.order_cancelled=CURRENT_TIMESTAMP WHERE o.ordet_order=ordid;


 SELECT GROUP_CONCAT(c.order_batchid) INTO resultString FROM order_details c WHERE c.ordet_order=ordid ;
    SELECT GROUP_CONCAT(c.ordet_quantity) INTO resultQty FROM order_details c WHERE c.ordet_order=ordid ;
 WHILE resultString IS NOT NULL AND resultString != '' DO
        SET singleValue = SUBSTRING_INDEX(resultString, ',', 1);
        SET singleQty = SUBSTRING_INDEX(resultQty, ',', 1);
        SELECT strstk_store,strstk_item INTO store,item FROM storestock_pricing WHERE strstk_id =singleValue;
        UPDATE storestock_pricing SET strstk_reserved=strstk_reserved-singleQty WHERE strstk_id =singleValue;
        UPDATE storestock_master SET storestock_reserved=storestock_reserved-singleQty WHERE storestock_store = store AND storestock_item =item;
        -- Remove the processed value from resultString
        SET resultString = REPLACE(resultString, CONCAT(singleValue, ','), '');
        SET resultQty = REPLACE(resultQty, CONCAT(singleQty, ','), '');
        IF resultString = singleValue AND resultQty=singleQty  THEN
            SET resultString = '';
            SET resultQty='';
        END IF;
    END WHILE;
 SELECT phone;
END$$

CREATE  PROCEDURE `cancelUserReturnOrdersbyOrderId` (IN `orderId` VARCHAR(200), IN `userid` INT)   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=1  WHERE o.order_orderid=orderId and o.order_customer=userid;
 
DELETE FROM order_return_status_history WHERE order_id=ordid;
 
INSERT INTO `order_return_status_history_tmp`( `order_id`, `return_status`, `return_reason`, `status_date`) VALUES (ordid,0,'deleted',CURRENT_TIMESTAMP);
END$$

CREATE  PROCEDURE `checkDeliveryaddressByphone` (IN `phone` VARCHAR(200), IN `userid` INT)   BEGIN
DECLARE counts int;
IF (userid IS NULL) THEN
IF EXISTS(SELECT 1 FROM customers_tbl c WHERE c.customer_phone=phone and c.customer_type=1)THEN
SELECT 'user' as guest,c.customer_id as user_id FROM customers_tbl c WHERE c.customer_phone=phone and c.customer_type=1;
/*SELECT 'user' as guest;*/
ELSE
SELECT COUNT(*) into counts FROM customers_tbl c WHERE c.customer_phone=phone and c.customer_type=0;
IF(counts=1)THEN
SELECT 1 as guest,c.customer_id as user_id FROM customers_tbl c WHERE c.customer_phone=phone and c.customer_type=0;

SELECT d.delivery_to,d.delivery_email,d.delivery_pin,d.delivery_house,d.delivery_street,d.delivery_landmark,d.delivery_city,d.delivery_state,d.delivery_type FROM delivery_address d JOIN customers_tbl c ON c.customer_id=d.delivery_user WHERE c.customer_type=0 and c.customer_phone=phone and d.delivery_status=1;
ELSE
SELECT 0 as guest;
END IF;
END IF;
ELSE
SELECT 0 as guest;


END IF;



END$$

CREATE  PROCEDURE `checkDuplicate` (IN `itemname` VARCHAR(100), IN `flag` INT)   BEGIN
	DECLARE resp INT DEFAULT 0;
	IF flag = 1 THEN /* invoice number */
    	SELECT COUNT INTO resp FROM invoices_tbl  
        WHERE invoice_number = trim(itemname);
    END IF;
    SELECT resp;
END$$

CREATE  PROCEDURE `checkOfferProduct` (IN `prdid` INT, IN `packid` INT, IN `stockid` INT)   BEGIN
    DECLARE mrp, msp, totalprice, smrp, smsp, disc, sdisc, actualprice DOUBLE DEFAULT 0;
    DECLARE strk INT DEFAULT 0;

    -- Get the pricing details for the given product, pack, and stock ID
    SELECT e1.strstk_mrp, e1.strstk_msp, e1.strstk_discount
    INTO mrp, msp, disc
    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
    LIMIT 1;

    -- Calculate actual price
    SET actualprice = IF(disc != 0, msp, mrp);

    -- Initialize row number variable
    SET @row_number = 0;

    -- Select the best available stock details
    SELECT strstk_mrp, strstk_msp, max_discount, strstk_id
    INTO smrp, smsp, sdisc, strk
    FROM (
        SELECT 
            (@row_number := @row_number + 1) AS virtual_id,
            e1.strstk_mrp, 
            e1.strstk_msp, 
            e1.strstk_discount AS max_discount, 
            e1.strstk_id, 
            e1.strstk_item
        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_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
        LIMIT 1
    ) AS x;

    -- Calculate the total price
    SET totalprice = IF(sdisc != 0, smsp, smrp);
    
    -- Conditional check for price comparison
    IF actualprice > totalprice THEN
        SELECT 1 AS statusVal;
        select x.product_id,x.product_name,x.product_display,x.prodpack_id,x.prodpack_quantity,x.packing_type,
x.measunit_shortname,x.strstk_mrp,x.strstk_msp,x.stockin_batch,x.product_imageurl,x.strstk_discount,x.strstk_id,x.strstk_item  from (SELECT ( @row_numbers := @row_numbers + 1) AS virtual_id,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 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 e.strstk_id=strk ORDER by s.stockin_expiry asc, e.strstk_discount DESC, e.strstk_stock DESC) AS x GROUP BY x.strstk_item;
        
    ELSE
        SELECT 0 AS statusVal;
    END IF;

END$$

CREATE  PROCEDURE `checkPhoneByuserId` (IN `userid` INT)   BEGIN
DECLARE counts int;

IF EXISTS(SELECT 1 FROM customers_tbl c WHERE c.customer_id=userid)THEN
SELECT c.customer_type as type, c.customer_phone as phone FROM customers_tbl c WHERE c.customer_id=userid;
/*SELECT 'user' as guest;*/
ELSE
SELECT null as type, null as phone;
END IF;



END$$

CREATE  PROCEDURE `checkuserByphone` (IN `phone` VARCHAR(200))   BEGIN
DECLARE counts int;

IF EXISTS(SELECT 1 FROM customers_tbl c WHERE c.customer_phone=phone and c.customer_type=1)THEN
SELECT 'user' as guest FROM customers_tbl c WHERE c.customer_phone=phone and c.customer_type=1;
/*SELECT 'user' as guest;*/
ELSE
SELECT COUNT(*) into counts FROM customers_tbl c WHERE c.customer_phone=phone and c.customer_type=0;
IF(counts=1)THEN
SELECT 1 as guest FROM customers_tbl c WHERE c.customer_phone=phone and c.customer_type=0;

ELSE
SELECT 0 as guest;
END IF;
END IF;




END$$

CREATE  PROCEDURE `checkuserByTrackID` (IN `orderId` VARCHAR(255), IN `phone` VARCHAR(255))   BEGIN
DECLARE phoneno VARCHAR(225);
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_phone INTO phoneno 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;
SELECT 1 as users,phoneno as phoneNum;
ELSE
SELECT 0 as users;
END IF;
END$$

CREATE  PROCEDURE `checkUserCredentials` (IN `phone` VARCHAR(50), IN `flag` INT, IN `email` VARCHAR(200))   BEGIN
if flag=2 THEN
IF EXISTS (SELECT 1 FROM customers_tbl c WHERE (c.customer_phone = phone or c.customer_email=email ) and c.customer_type=1 )THEN
SELECT 1 as usr;
ELSE
SELECT 0 as usr;
END IF;
ELSE
SELECT "" as usr;
END IF;
END$$

CREATE  PROCEDURE `checkUserCredentialsbyPhone` (IN `phone` VARCHAR(50))   BEGIN

IF EXISTS (SELECT 1 FROM customers_tbl c WHERE c.customer_phone = phone  and c.customer_type=1 )THEN
SELECT 1 as usr;
ELSE
SELECT 0 as usr;
END IF;

END$$

CREATE  PROCEDURE `checkUserLogin` (IN `username` VARCHAR(100), IN `passwords` VARCHAR(100))   BEGIN

SELECT u.user_id,	u.user_staffid	,u.user_staffname	,u.user_programid	,u.user_programcontains	,u.user_status, s.staff_branch, t.store_name, u.user_checkid, t.store_code FROM users_tbl u LEFT JOIN staff_tbl s ON s.staff_id=u.user_staffid LEFT JOIN stores_tbl t ON t.store_id=s.staff_branch WHERE BINARY u.user_login = username AND BINARY u.user_password = passwords;

END$$

CREATE  PROCEDURE `checkVendorItem` (IN `vtype` INT, IN `vendor` INT, IN `product` INT, IN `packing` INT, IN `qty` INT)   BEGIN
	SELECT COUNT(*) FROM vendor_supplies x 
    LEFT JOIN product_packing p ON p.prodpack_id = x.vendsup_packing
    WHERE x.vendsup_product = product AND x.vendsup_packing = packing 
    AND x.vendsup_type = vtype AND x.vendsup_vendor = vendor 
    AND p.prodpack_quantity = qty;
END$$

CREATE  PROCEDURE `countOfListIntendApproval` (IN `storeid` INT)   BEGIN
IF storeid > 0 THEN
	SELECT COUNT(*) as total
    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 ;
    ELSE
    SELECT COUNT(*) as total
    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 ;
    END IF;
END$$

CREATE  PROCEDURE `countOfNotifications` (IN `storeid` INT)   BEGIN
#count of store intend tranfers
IF storeid > 1 THEN
	SELECT COUNT(*) as total
    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 ;
    ELSE
    SELECT COUNT(*) as total
    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 ;
    END IF;
 #count of stockinward
    IF storeid > 1 THEN
    	SELECT COUNT(*) AS stokin_total
    FROM invoices_tbl x
    WHERE  x.invoice_delstatus=1 AND x.invoice_status=1 AND x.invoice_delstore=storeid ;
    ELSE
    	SELECT COUNT(*) AS stokin_total
    FROM invoices_tbl x
    WHERE x.invoice_delstatus =1 and x.invoice_status=1;
   END IF;
#count of collections
	IF storeid >1 THEN
       SELECT COUNT(*) AS colcn_total
        FROM transfer_packets p
        WHERE p.transpack_status = 1 AND p.transpack_from=storeid;
    ELSE
        SELECT COUNT(*) AS colcn_total
        FROM transfer_packets p WHERE p.transpack_status = 1;
    END IF;
#count of received items
	IF storeid >1 THEN
    SELECT COUNT(*) AS recvd_total FROM transfer_packets t
        WHERE t.transpack_to=storeid AND t.transpack_status >1 AND t.transpack_status <10;
     ELSE
    	 SELECT COUNT(*) AS recvd_total FROM transfer_packets t
            WHERE t.transpack_status >1 AND t.transpack_status <10;
	END IF;
#count of packagings
IF storeid > 1 THEN
   		SELECT COUNT(*) AS pack_total FROM stock_transfers x
    	WHERE x.stocktrans_status = 1 AND x.stocktrans_strfrom=storeid AND (SELECT COUNT(*) FROM transfer_packets p WHERE p.transpack_refer = x.stocktrans_id)=0;
    ELSE
       SELECT COUNT(*) AS pack_total FROM stock_transfers x
    	WHERE x.stocktrans_status = 1 AND (SELECT COUNT(*) FROM transfer_packets p WHERE p.transpack_refer = x.stocktrans_id)=0;
END IF;
#count of approval for warehouse
IF storeid=1 THEN
SELECT COUNT(*) AS aprv_total 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 ;
    ELSE
    SELECT 0 AS aprv_total;
 END IF;
 
 #count of item returns
 IF storeid>1 THEN
  SELECT COUNT(*) AS return_total FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice 
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=sp.strstk_store
    WHERE (s.stockin_expiry <= DATE_ADD(CURDATE(), INTERVAL 2 MONTH)) AND (sp.strstk_stock - sp.strstk_reserved)>0 AND s.stockin_store=storeid ;
ELSE 
    SELECT COUNT(*) AS return_total FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice 
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=sp.strstk_store
    WHERE (s.stockin_expiry <= DATE_ADD(CURDATE(), INTERVAL 2 MONTH)) AND (sp.strstk_stock - sp.strstk_reserved)>0;
END IF ;

#count of item low stock store per day
/*IF storeid>1 THEN 
SELECT COUNT(*) AS low_stock FROM searchlog_tbl s JOIN stores_tbl st on st.store_id=s.search_store WHERE date(s.search_crtdon)=CURRENT_DATE AND s.search_store=storeid GROUP BY s.search_store,s.search_item ORDER BY s.search_crtdon DESC;

ELSE
SELECT COUNT(*) AS low_stock 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 IF;*/

SELECT COUNT(*) AS low_stock FROM(SELECT DISTINCT s.search_store 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) AS sub;

 /*IF storeid>1 THEN
  SELECT COUNT(*) AS return_total FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=sp.strstk_store
    WHERE (s.stockin_expiry <= DATE_ADD(CURDATE(), INTERVAL 2 MONTH)OR s.stockin_damaged>0 OR i.invdet_wopo=1) AND (sp.strstk_stock - sp.strstk_reserved)>0 AND s.stockin_store=storeid ;
ELSE
    SELECT COUNT(*) AS return_total FROM stock_inwards s
    LEFT JOIN invoice_details i ON i.invdet_id=s.stockin_invref
    LEFT JOIN invoices_tbl ii ON ii.invoice_id=i.invdet_invoice
    LEFT JOIN storestock_pricing sp ON sp.strstk_refer=s.stockin_id
    LEFT JOIN stores_tbl ss on ss.store_id=sp.strstk_store
    WHERE (s.stockin_expiry <= DATE_ADD(CURDATE(), INTERVAL 2 MONTH)OR s.stockin_damaged>0 OR i.invdet_wopo=1) AND (sp.strstk_stock - sp.strstk_reserved)>0;
END IF ;*/

END$$

CREATE  PROCEDURE `county_summary` (IN `query` JSON)   BEGIN
	DECLARE i_county varchar(255) default null;
	DECLARE i_year int default null;
	DECLARE i_month int default null;
    
    set i_county = JSON_UNQUOTE(JSON_EXTRACT(query,'$.county'));
set i_year = JSON_EXTRACT(query,'$.year');
set i_month = JSON_EXTRACT(query,'$.month');

SELECT 1, 'test', json_unquote(json_extract(query, '$.name')) AS customer, json_extract(query, '$.age') AS age, json_extract(query, '$.car') AS car;

 if (i_county is not null) && (i_year is not null) && (i_month is not null) then
   select 'loop 1';
 elseif (i_county is not null) && (i_year is not null) then
   select 'loop 2';
 elseif (i_year is not null) && (i_month is not null) then
   select 'loop 3';
 elseif (i_year is not null) then
   select 'loop 4';
 else
   select null as 'no input';
 end if; 
END$$

CREATE  PROCEDURE `createOrderPrescriptionFiles` (IN `p_user_id` INT, IN `p_ordid` VARCHAR(100), IN `p_files` VARCHAR(255), IN `p_phone` VARCHAR(20), IN `p_status` INT)   BEGIN
    
   
        -- Case 2: Only phone number, no files
        INSERT INTO prescription_files(user_id, order_id, file_name,  user_phone,file_status)
        VALUES (p_user_id, p_ordid, p_files, p_phone,p_status);
   
END$$

CREATE  PROCEDURE `createReOrderItemsBYorderID` (IN `orderId` VARCHAR(225))   BEGIN
DECLARE userid INT DEFAULT 0;
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;

INSERT IGNORE INTO `user_cart`(`user_id`, `product_id`, `prodpack_id`, `batch_id`, `quantity`)  (SELECT userid,d.ordet_productid,d.ordet_producpackid,d.order_batchid,d.ordet_quantity FROM order_details d JOIN orders_tbl o ON o.order_id=d.ordet_order WHERE o.order_orderid=orderId);
END$$

CREATE  PROCEDURE `createReOrderPrecriptionItemsBYorderID` (IN `orderId` VARCHAR(225))   BEGIN
DECLARE userid INT DEFAULT 0;
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;

INSERT IGNORE INTO `user_cart`(`user_id`, `product_id`, `prodpack_id`, `batch_id`, `quantity`)  (SELECT userid,d.ordet_productid,d.ordet_producpackid,d.order_batchid,d.ordet_quantity FROM order_details d JOIN orders_tbl o ON o.order_id=d.ordet_order WHERE o.order_orderid=orderId);
END$$

CREATE  PROCEDURE `customerDetails` (IN `mob` VARCHAR(20))   BEGIN
/* customer details fetch*/
SELECT customer_id , customer_number, customer_name, customer_address, customer_phone, customer_gender, customer_age
FROM customers_tbl
WHERE customer_phone = mob;
END$$

CREATE  PROCEDURE `defaultAddCourier` ()   BEGIN
	SELECT x.staff_id, x.staff_code, x.staff_name 
    FROM staff_tbl x 
    WHERE x.staff_status = 1 AND x.staff_role IN(0,1,2)
    ORDER BY x.staff_name;
    
    SELECT y.store_id, y.store_code, y.store_name 
    FROM stores_tbl y 
    WHERE y.store_status = 1 
    ORDER BY y.store_name;
    
    SELECT d.delarea_id, d.delarea_location, d.delarea_pincode
    FROM delivery_areas d 
    WHERE d.delarea_status = 1 
    ORDER BY d.delarea_country, d.delarea_province, d.delarea_district, d.delarea_location;
    
END$$

CREATE  PROCEDURE `defaultAddDealer` ()   BEGIN
	SELECT x.dealer_id, x.dealer_name 
    FROM dealers_tbl x 
    WHERE x.dealer_status = 1 
    ORDER BY x.dealer_name;
END$$

CREATE  PROCEDURE `defaultAddDistributor` ()   BEGIN
	SELECT x.manuf_id, x.manuf_name 
    FROM manufacturers_tbl x 
    WHERE x.manuf_status = 1 
    ORDER BY x.manuf_name;
    
    SELECT d.distri_id, d.distri_name 
    FROM distributors_tbl d 
    WHERE d.distri_status =  1 
    ORDER BY d.distri_name;
END$$

CREATE  PROCEDURE `defaultAddLocation` ()   BEGIN
	SELECT Code, Name 
    FROM country WHERE country.storeok = 1;
    
    SELECT DISTINCT(District) 
    FROM city WHERE CountryCode = 'IND'
    ORDER BY District;
    
    SELECT ID, Name FROM city 
    WHERE District = 'Kerala';
END$$

CREATE  PROCEDURE `defaultAddProduct` ()   BEGIN
	/* Generic Names 
	SELECT genmed_id, genmed_name 
    FROM generic_medicines 
    WHERE genmed_status = 1 
    UNION SELECT 0, 0 
    ORDER BY genmed_name;*/
    
    /* Main categories */
    SELECT prodclass_id, prodclass_name, prodclass_serial 
    FROM product_classes  
    WHERE prodclass_parent = 0 AND prodclass_status = 1 
    UNION ALL SELECT 0, 0, 0 
    ORDER BY prodclass_serial;
    
    /* Basic drug classes 
    SELECT drugclass_id, drugclass_name 
    FROM drug_classifications 
    WHERE drugclass_status = 1 AND drugclass_parent = 0 
    UNION SELECT 0, 0 
    ORDER BY drugclass_name ;*/
    
    /* All Brands */
    SELECT brand_id, brand_name, brand_owner
FROM brands_tbl 
WHERE brand_status = 1 

UNION ALL

SELECT 0, 0, 0 
ORDER BY brand_name;

    
    /* All Manufacturors */
    SELECT 
    m.manuf_id, 
    m.manuf_name, 
    GROUP_CONCAT(b.brand_id SEPARATOR ',') AS brands
FROM manufacturers_tbl m
LEFT JOIN brands_tbl b 
    ON b.brand_owner = m.manuf_id
WHERE m.manuf_status = 1
GROUP BY m.manuf_id, m.manuf_name

UNION ALL

SELECT 0, 'Select Manufacturer', '0'

ORDER BY manuf_name;

    
    /* Ingredients */
    SELECT ingredtype_id, ingredtype_type 
    FROM ingredient_types WHERE ingredtype_status = 1 
    UNION ALL SELECT 0, 0 
    ORDER BY ingredtype_type;
    
    /*SELECT ingred_id, ingred_name, ingred_type, ingredtype_type
    FROM ingredients_tbl  
    LEFT JOIN ingredient_types ON ingredtype_id = ingred_type 
    WHERE ingred_status = 1 
    UNION SELECT 0, 0, 0, 0
    ORDER BY ingred_type, ingred_name; */
    
    /* Packaging types */
    SELECT packing_id, packing_type 
    FROM packing_tbl WHERE packing_status = 1;
    
    /* Measuring units */
    SELECT measunit_id, measunit_name, measunit_shortname 
    FROM measure_units WHERE measunit_status = 1;
    
    /* GST Tax rates */
    SELECT tax_id, tax_group, tax_rate  
    FROM tax_groups WHERE tax_status = 1;
    
   /* Schedule name*/
    SELECT sch_id, sch_name, sch_code FROM schedule_tbl WHERE sch_status=1;
END$$

CREATE  PROCEDURE `defaultAddProducts` ()   BEGIN
	/* Generic Names */
	
    
    /* Main categories */
    SELECT prodclass_id, prodclass_name, prodclass_serial 
    FROM product_classes  
    WHERE prodclass_parent = 0 AND prodclass_status = 1 
    UNION ALL SELECT 0, 0, 0 
    ORDER BY prodclass_serial;
    
    /* Basic drug classes */
    SELECT drugclass_id, drugclass_name 
    FROM drug_classifications 
    WHERE drugclass_status = 1 AND drugclass_parent = 0 
    UNION SELECT 0, 0 
    ORDER BY drugclass_name ;
    SELECT 0 AS brand_id, 0 AS brand_name,0 AS brand_owner;
    /* All Brands 
    SELECT brand_id, brand_name, brand_owner
    FROM brands_tbl WHERE brand_status = 1 
    UNION SELECT 0, 0, 0 
    ORDER BY brand_name;*/
    
    /* All Manufacturors 
    SELECT 
    m.manuf_id, 
    m.manuf_name, 
    GROUP_CONCAT(b.brand_id SEPARATOR ',') AS brands
FROM manufacturers_tbl m
LEFT JOIN brands_tbl b 
    ON b.brand_owner = m.manuf_id
WHERE m.manuf_status = 1
GROUP BY m.manuf_id, m.manuf_name

UNION ALL

SELECT 0, 'Select Manufacturer', '0'

ORDER BY manuf_name;
*/

SELECT 0 AS manuf_id,null AS manuf_name ,0 AS brands;

    
    /* Ingredients */
    SELECT ingredtype_id, ingredtype_type 
    FROM ingredient_types WHERE ingredtype_status = 1 
    UNION ALL SELECT 0, 0 
    ORDER BY ingredtype_type;
    
    /*SELECT ingred_id, ingred_name, ingred_type, ingredtype_type
    FROM ingredients_tbl  
    LEFT JOIN ingredient_types ON ingredtype_id = ingred_type 
    WHERE ingred_status = 1 
    UNION SELECT 0, 0, 0, 0
    ORDER BY ingred_type, ingred_name; */
    
    /* Packaging types */
    SELECT packing_id, packing_type 
    FROM packing_tbl WHERE packing_status = 1;
    
    /* Measuring units */
    SELECT measunit_id, measunit_name, measunit_shortname 
    FROM measure_units WHERE measunit_status = 1;
    
    /* GST Tax rates */
    SELECT tax_id, tax_group, tax_rate  
    FROM tax_groups WHERE tax_status = 1;
    
   /* Schedule name*/
    SELECT sch_id, sch_name, sch_code FROM schedule_tbl WHERE sch_status=1;
END$$

CREATE  PROCEDURE `defaultAddStockist` ()   BEGIN
	SELECT manuf_id, manuf_name 
    FROM manufacturers_tbl 
    WHERE manuf_status = 1 
    ORDER BY manuf_name;
END$$

CREATE  PROCEDURE `defaultAddStore` ()   BEGIN
	SELECT storetype_id, storetype_name 
    FROM store_types  
    WHERE storetype_status = 1; 
    
    SELECT delarea_id, delarea_location, delarea_pincode
    FROM delivery_areas  
    WHERE delarea_status = 1 
    ORDER BY delarea_location;
END$$

CREATE  PROCEDURE `defaultCollections` (IN `adminid` INT, IN `courier` INT, IN `flag` INT, IN `store` INT)   BEGIN
	SELECT x.store_id, x.store_code, x.store_name
    FROM stores_tbl x WHERE x.store_status = 1;
    SELECT c.courier_id, c.courier_name
    FROM couriers_tbl c WHERE c.courier_status = 1
    ORDER BY c.courier_name;
    IF store >1 THEN
    IF flag=1 THEN
        SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status,t.store_contactcell as contact ,pp.transferpack_orditem,pp.transferpack_qty,pp.transferpack_item
        FROM transfer_packets p
        LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from
        LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to
        LEFT JOIN transferpack_items pp ON pp.transferpack_packet=p.transpack_id
        WHERE p.transpack_status = 5 AND p.transpack_from=store GROUP BY p.transpack_packid;
      ELSEIF flag=2 AND store>0 THEN
        SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status,t.store_contactcell as contact ,pp.transferpack_orditem,pp.transferpack_qty,pp.transferpack_item
        FROM transfer_packets p
        LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from
        LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to
        LEFT JOIN transferpack_items pp ON pp.transferpack_packet=p.transpack_id
        WHERE p.transpack_status = 10 AND p.transpack_from=store GROUP BY p.transpack_packid;
    ELSE
       /*SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status, t.store_contactcell as contact ,pp.transferpack_orditem,pp.transferpack_qty,pp.transferpack_item
        FROM transfer_packets p
        LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from
        LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to
        LEFT JOIN transferpack_items pp ON pp.transferpack_packet=p.transpack_id
        WHERE p.transpack_status = 1 AND p.transpack_from=store GROUP BY p.transpack_packid;*/
        SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status,t.store_contactcell as contact ,group_concat(concat(pp.transferpack_orditem,'|',pp.transferpack_qty,'|',p.transpack_from,'|',pp.transferpack_item) SEPARATOR '##') as orderitem,fnGetProductFromPack(pp.transferpack_item, 0) AS item FROM transfer_packets p
        LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from
        LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to
        LEFT JOIN transferpack_items pp ON pp.transferpack_packet=p.transpack_id
        WHERE p.transpack_status = 1 AND p.transpack_from=store GROUP BY p.transpack_packid;
    END IF;
    ELSE
    IF flag=1 THEN
        SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status,t.store_contactcell as contact ,pp.transferpack_orditem,pp.transferpack_qty,pp.transferpack_item
        FROM transfer_packets p
        LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from
        LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to
        LEFT JOIN transferpack_items pp ON pp.transferpack_packet=p.transpack_id
        WHERE p.transpack_status = 5 GROUP BY p.transpack_packid;
      ELSEIF flag=2 THEN
        SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status, t.store_contactcell as contact ,pp.transferpack_orditem,pp.transferpack_qty,pp.transferpack_item
        FROM transfer_packets p
        LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from
        LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to
        LEFT JOIN transferpack_items pp ON pp.transferpack_packet=p.transpack_id
        WHERE p.transpack_status = 10 GROUP BY p.transpack_packid;
    ELSE
        SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status,t.store_contactcell as contact ,group_concat(concat(pp.transferpack_orditem,'|',pp.transferpack_qty,'|',p.transpack_from,'|',pp.transferpack_item) SEPARATOR '##') as orderitem,fnGetProductFromPack(pp.transferpack_item, 0) AS item FROM transfer_packets p LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to LEFT JOIN transferpack_items pp ON pp.transferpack_packet=p.transpack_id WHERE p.transpack_status = 1 group by p.transpack_packid;
    END IF;
   END IF;
END$$

CREATE  PROCEDURE `defaultDeliveries` (IN `adminid` INT, IN `flag` INT, IN `store` INT, IN `courier` INT)   BEGIN
	SELECT x.store_id, x.store_code, x.store_name
    FROM stores_tbl x WHERE x.store_status = 1;
    
    SELECT c.courier_id, c.courier_name 
    FROM couriers_tbl c WHERE c.courier_status = 1 
    ORDER BY c.courier_name;
    
    IF flag=1 AND store>0 THEN
    SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status, 'contact person' as contact 
    FROM transfer_packets p 
    LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from 
    LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to 
    WHERE p.transpack_status = 5 AND p.transpack_from=store;
    
      ELSEIF flag=2 AND store>0 THEN
    SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status, 'contact person' as contact 
    FROM transfer_packets p 
    LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from 
    LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to 
    WHERE p.transpack_status = 10 AND p.transpack_from=store;
    
    ELSEIF flag=3 AND store>0 THEN
    SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status, 'contact person' as contact 
    FROM transfer_packets p 
    LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from 
    LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to 
    WHERE p.transpack_status = 15 AND p.transpack_to=store;
    ELSE 
	SELECT p.transpack_id, p.transpack_packid, p.transpack_from, s.store_name AS frmstore, p.transpack_to, t.store_name AS tostotre, p.transpack_status, 'Contact person' AS contact ,p.transpack_collectby as courier_id , c.courier_name as courier
    FROM transfer_packets p 
    LEFT JOIN stores_tbl s ON s.store_id = p.transpack_from 
    LEFT JOIN stores_tbl t ON t.store_id = p.transpack_to 
    LEFT JOIN couriers_tbl c ON c.courier_id=p.transpack_collectby
    WHERE p.transpack_status = 5;
    
    END IF;
END$$

CREATE  PROCEDURE `defaultpracticelist` ()   BEGIN
	    
 SELECT practice_id, practice_name FROM practicestype_tbl WHERE practice_status =1 UNION SELECT 0,0 ORDER BY practice_name;
 
 SELECT
    d.doctor_id,
    pt.practice_name AS dtype,
    d.doctor_name,
    d.doctor_regno,
    d.doctor_mobile,
    d.doctor_email,
    d.doctor_degrees,
    d.doctor_hospital,
    d.doctor_remarks,
    d.doctor_photo,
    d.doctor_signature,
    d.doctor_datefrom,
    d.doctor_availfrom,
    d.doctor_dateto,
    d.doctor_availto,
    d.doctor_status
FROM
    doctors_tbl d
LEFT JOIN
    practicestype_tbl pt ON pt.practice_id = d.doctor_type 
ORDER BY
    d.doctor_crtdon DESC;
END$$

CREATE  PROCEDURE `defaultProductSettings` ()   BEGIN
	/* Product base classes */
	SELECT p.prodclass_id, p.prodclass_name, p.prodclass_serial, p.prodclass_status, p.prodclass_thumb,(SELECT COUNT(c.prodclass_parent) FROM product_classes c WHERE c.prodclass_parent=p.prodclass_id) AS subcount
    FROM product_classes p WHERE p.prodclass_parent = 0 AND p.prodclass_status = 1
    UNION SELECT 0, 0, 0, 0, 0,0
    ORDER BY prodclass_serial, prodclass_name;
    /* packing types */
    SELECT packing_id, packing_type,packing_sale ,packing_status
    FROM packing_tbl  p
    UNION SELECT 0, 0, 0,0;
    /* measurements */
    SELECT x.measunit_id, x.measunit_name, x.measunit_shortname, x.measunit_status
    FROM measure_units x
    UNION SELECT 0, 0, 0, 0;
END$$

CREATE  PROCEDURE `defaultStockPricing` ()   BEGIN
	SELECT DISTINCT p.product_id, p.product_name, p.product_maincategory, c.prodclass_name, fnGetProductFromPack(x.strstk_item, 0) AS product_name,
    x.strstk_item, (SELECT COUNT(DISTINCT(y.strstk_store)) FROM storestock_pricing y WHERE y.strstk_item = x.strstk_item AND (y.strstk_stock -y.strstk_reserved) > 0) AS storecount,
    (SELECT COUNT(z.strstk_item) FROM storestock_pricing z WHERE z.strstk_item = x.strstk_item AND (z.strstk_stock - z.strstk_reserved) > 0) AS items,
    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-x.strstk_reserved )> 0 AND x.strstk_status = 1
    ORDER BY x.strstk_item;
/*
	SELECT DISTINCT p.product_id, p.product_name, p.product_display, p.product_maincategory, c.prodclass_name,
    (SELECT COUNT(DISTINCT(y.stockin_store)) FROM stock_inwards y WHERE y.stockin_item = x.stockin_item AND y.stockin_balance > 0) AS storecount,
    (SELECT COUNT(z.stockin_item) FROM stock_inwards z WHERE z.stockin_item = x.stockin_item AND z.stockin_balance > 0) AS items,
    0 AS onlines, 0 AS priced
	FROM stock_inwards x
    LEFT JOIN product_packing k ON k.prodpack_id = x.stockin_item
    LEFT JOIN products_tbl p ON p.product_id = k.prodpack_product
    LEFT JOIN product_classes c ON c.prodclass_id = p.product_maincategory
    WHERE x.stockin_balance > 0
    ORDER BY p.product_maincategory, x.stockin_item;  */
    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;
    /*
	SELECT p.product_id, p.product_name, p.product_display, s.store_id, s.store_name,
    x.stockin_id, x.stockin_item,  fnGetProductFromPack(x.stockin_item, 0) AS product,
    x.stockin_store, x.stockin_batch, x.stockin_expiry, x.stockin_balance, d.invdet_mrp
    FROM stock_inwards x
    LEFT JOIN product_packing k ON k.prodpack_id = x.stockin_item
    LEFT JOIN products_tbl p ON p.product_id = k.prodpack_product
    LEFT JOIN invoice_details d ON d.invdet_invoice = x.stockin_invref
    LEFT JOIN stores_tbl s ON s.store_id = x.stockin_store
    WHERE x.stockin_balance > 0
    ORDER BY x.stockin_item; */
END$$

CREATE  PROCEDURE `defaultStockTransfer` ()   BEGIN
	SELECT x.store_id, x.store_name, x.store_address, x.store_location
    FROM stores_tbl x 
    WHERE x.store_status = 1  
    ORDER BY x.store_type, x.store_name;
    
    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 prodclass_seq <> '' 
    ORDER BY seq, cntr,  serial;
END$$

CREATE  PROCEDURE `defaultStockTransferOrders` (IN `storeid` INT)   BEGIN
	SELECT store_id, store_code, store_name 
    FROM stores_tbl WHERE store_status = 1 
    ORDER BY store_name;
       
    IF storeid > 0 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  
    	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;
    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  
    	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;
    END IF;
END$$

CREATE  PROCEDURE `defaultStoreIntend` (IN `storeid` INT)   BEGIN
	SELECT x.store_id, x.store_code, x.store_name 
    FROM stores_tbl x 
    WHERE x.store_status = 1;
    
    SELECT CONCAT('ITD/', s.store_code, '/', (SELECT COUNT(*) + 1 FROM intends_tbl WHERE intend_from = storeid)) AS dummy 
    FROM stores_tbl s WHERE s.store_id = storeid;
END$$

CREATE  PROCEDURE `defaultStoreIntend_0` (IN `storeid` INT)   BEGIN
	SELECT x.store_id, x.store_code, x.store_name 
    FROM stores_tbl x 
    WHERE x.store_status = 1;
    
    SELECT p.product_id, p.product_name, p.product_display 
    FROM products_tbl p 
    WHERE p.product_status = 1 ORDER BY p.product_name;
    
    SELECT CONCAT('ITD/', s.store_code, '/', (SELECT COUNT(*) + 1 FROM intends_tbl WHERE intend_from = storeid)) AS dummy 
    FROM stores_tbl s WHERE s.store_id = storeid;
END$$

CREATE  PROCEDURE `deleteFromPurchaseOrder` (IN `itemid` INT, IN `adminid` INT)   BEGIN
	DECLARE poid, delstatus,qty INT DEFAULT 0;
    DECLARE price DECIMAL(7,2) DEFAULT 0;
    
    SELECT x.podetail_order INTO poid 
    FROM purchase_details x WHERE x.podetail_id = itemid;
    
    IF poid > 0 THEN
    	IF fnGetPurchaseOrderStatus(poid) = 1 THEN
        	SELECT k.podetail_price INTO price FROM purchase_details k WHERE k.podetail_id = itemid;
        	SELECT k.podetail_qty INTO qty FROM purchase_details k WHERE k.podetail_id = itemid;

            START TRANSACTION;
            	DELETE FROM purchase_details WHERE podetail_id = itemid;
                UPDATE purchase_orders SET purchord_amount = (purchord_amount - (price*qty)) WHERE purchord_id = poid;
           	COMMIT;
            SET delstatus = 1;
        END IF;
    END IF;
    
    SELECT delstatus;
END$$

CREATE  PROCEDURE `deleteGalleryItem` (IN `galid` INT)   BEGIN
	DELETE FROM product_gallery WHERE prodgal_id = galid;
    ALTER TABLE product_gallery AUTO_INCREMENT = 1;
END$$

CREATE  PROCEDURE `DeleteMenuBYID` (IN `ids` INT)   BEGIN
DELETE FROM `programs_table` WHERE `progr_id`=ids;
END$$

CREATE  PROCEDURE `deleteProductIngredient` (IN `prodid` INT, IN `ingred` INT)   BEGIN
	DELETE FROM product_ingredients WHERE prodingred_product=prodid and prodingred_ingredient=ingred;
END$$

CREATE  PROCEDURE `deleteProductPacking` (IN `ppackid` INT)   BEGIN
	IF (SELECT COUNT(*) FROM vendor_supplies 
        	WHERE vendsup_packing = ppackid) = 0 THEN
    	DELETE FROM product_packing WHERE prodpack_id = ppackid;
        SELECT 1;
    ELSE
    	SELECT 0;
    END IF;
END$$

CREATE  PROCEDURE `deleteProductSettingsItem` (IN `prsid` INT, IN `setype` INT, IN `adminid` INT)   BEGIN
	DECLARE results, success INT DEFAULT 0;
	IF setype =  1 THEN /* prodcut classes */
    DELETE FROM product_classes WHERE prodclass_id = prsid;
    	IF (SELECT COUNT(*) FROM product_classes x 
        WHERE x.prodclass_parent = prsid) = 0 THEN
        	
            ALTER TABLE product_classes AUTO_INCREMENT = 1;
        END IF;
        SELECT COUNT(*) INTO results FROM product_classes WHERE prodclass_id = prsid;
    ELSEIF setype =  2 THEN  /* packings */
    	DELETE FROM packing_tbl WHERE packing_id = prsid;
        SELECT COUNT(*) INTO results FROM packing_tbl WHERE packing_id  = prsid;
    ELSEIF setype =  3 THEN  /* measures units */   
    	DELETE FROM measure_units WHERE measunit_id = prsid;
        SELECT COUNT(*) INTO results FROM measure_units WHERE measunit_id = prsid;
    END IF;
    
    IF results = 0 THEN
    	SET success = 1;
    END IF;
    SELECT success;
END$$

CREATE  PROCEDURE `deleteVendorPacking` (IN `vsupid` INT)   BEGIN
	DECLARE success, pcount, icount INT DEFAULT 0;
    
    SELECT COUNT(*) INTO pcount 
    FROM purchase_details p WHERE p.podetail_item = vsupid;
    SELECT COUNT(*) INTO icount
    FROM invoice_details n WHERE n.invdet_item = vsupid;
    IF pcount = 0 AND icount = 0 THEN
    	DELETE FROM vendor_supplies WHERE vendsup_id = vsupid;
        SET success = 1;
	END IF;
    SELECT success;
END$$

CREATE  PROCEDURE `doctorName` ()   BEGIN
SELECT d.doctor_id, d.doctor_name FROM doctors_tbl d WHERE doctor_status =1 UNION SELECT 0,0 ORDER BY doctor_name;
SELECT `doctor_id`, `doctor_name`,`doctor_crtdby` FROM `doctors_tbl` ORDER BY doctor_id DESC LIMIT 1;
END$$

CREATE  PROCEDURE `editAddOnInvoice` (IN `invid` INT)   BEGIN
    SELECT x.invoice_id, x.invoice_number, x.invoice_vendertype, x.invoice_vendor, fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) AS vendor, x.invoice_dated, x.invoice_amount, x.invoice_cgst, x.invoice_sgst, x.invoice_payby, x.invoice_payment, x.invoice_paidon, x.invoice_paystatus, x.invoice_delstatus, x.invoice_deldate, x.invoice_notes, x.invoice_status ,x.invoice_vendorgst,x.invoice_delstore,x.invoice_delgst,(SELECT s.store_name FROM stores_tbl s WHERE s.store_id=x.invoice_delstore)AS store_name
    FROM invoices_tbl x WHERE x.invoice_id = invid;
        SELECT y.invdet_id, y.invdet_invoice, y.invdet_porder, p.purchord_ref, p.purchord_date,
    y.invdet_item,( y.invdet_qty+y.invdet_free)AS total_qty, y.invdet_price,   y.invdet_delivered, y.invdet_delstatus, y.invdet_deldate,y.invdet_status,
    fnGetProductFromPack(y.invdet_item, 0) AS invitem, y.invdet_mrp, y.invdet_hsn, y.invdet_ptr, y.invdet_batch, y.invdet_expiry,
    (SELECT GROUP_CONCAT(invfile_url SEPARATOR ',') FROM invoice_files WHERE invfile_invoice = invid) AS urls,(SELECT COUNT(invfile_url) FROM invoice_files WHERE invfile_invoice = invid) AS urlcnt , s.stockin_inward ,s.stockin_short , s.stockin_id
    FROM invoice_details y
    LEFT JOIN purchase_orders p ON p.purchord_id = y.invdet_porder
    LEFT JOIN stock_inwards s ON s.stockin_invref=y.invdet_id
    WHERE y.invdet_invoice = invid AND y.invdet_delstatus=5;
         SELECT y.invdet_id,(SELECT x.invoice_number FROM invoices_tbl x WHERE x.invoice_id=a.addinv_invoice)AS invoice_no,(SELECT x.invoice_dated FROM invoices_tbl x WHERE x.invoice_id=a.addinv_invoice) AS invoice_date , y.invdet_invoice, y.invdet_porder, p.purchord_ref, p.purchord_date,
    y.invdet_item,y.invdet_qty, y.invdet_price,   y.invdet_delivered, y.invdet_delstatus, y.invdet_deldate,y.invdet_status,
    fnGetProductFromPack(y.invdet_item, 0) AS invitem, y.invdet_mrp, y.invdet_hsn, y.invdet_ptr, y.invdet_batch, y.invdet_expiry,(SELECT x.invoice_notes FROM invoices_tbl x WHERE x.invoice_id=a.addinv_invoice)AS invoice_notes,
    (SELECT GROUP_CONCAT(invfile_url SEPARATOR ',') FROM invoice_files WHERE invfile_invoice = a.addinv_invoice) AS urls,(SELECT COUNT(invfile_url) FROM invoice_files WHERE invfile_invoice = invid) AS urlcnt , s.stockin_inward ,s.stockin_short , s.stockin_id
    FROM invoice_details y
    LEFT JOIN purchase_orders p ON p.purchord_id = y.invdet_porder
    LEFT JOIN stock_inwards s ON s.stockin_invref=y.invdet_id
    LEFT JOIN addoninvoice a ON a.addinv_ref=invid
    WHERE y.invdet_invoice = a.addinv_invoice
    GROUP BY y.invdet_item;
END$$

CREATE  PROCEDURE `editAdvertisementDetails` (IN `advtid` INT)   BEGIN
    SELECT a.advt_id,a.advt_type,a.advt_title,a.advt_owner,a.advt_brand, b.brand_name,a.advt_datefrom,a.advt_dateto,a.advt_products,a.advt_maincategories,a.advt_subcategories,a.advt_catgory,
a.advt_content,a.advt_image,a.advt_linkedurl,a.advt_publish,a.advt_status,a.advt_offer,a.advt_hompagestatus,a.advt_maincatstatus,a.advt_subcatstatus,a.advt_catstatus ,p.prodclass_name as maincat ,pp.prodclass_name as subcat ,q.prodclass_name as catname ,d.product_name FROM advertisements_tbl a 
LEFT JOIN product_classes p ON p.prodclass_id=a.advt_maincategories
LEFT JOIN product_classes pp ON pp.prodclass_id=a.advt_subcategories
LEFT JOIN product_classes q ON q.prodclass_id=a.advt_catgory
LEFT JOIN products_tbl d ON d.product_id=a.advt_products
LEFT JOIN brands_tbl b ON b.brand_id=a.advt_brand

 WHERE a.advt_id=advtid ;
 
END$$

CREATE  PROCEDURE `editBrand` (IN `brandid` INT)   BEGIN
	DECLARE manuf INT DEFAULT 0;
    
	SELECT x.brand_id, x.brand_name, x.brand_logo, GROUP_CONCAT(b.brndmanu_id) AS brand_owner, 
    x.brand_remarks, x.brand_status, x.brand_publish  
    FROM brands_tbl x JOIN brand_manufacturer_tbl b ON b.brnd_id=x.brand_id
    WHERE x.brand_id = brandid AND x.brand_status=1 GROUP BY b.brnd_id;
    
    SELECT brand_owner INTO manuf FROM brands_tbl 
    WHERE brand_id = brandid;
    
    SELECT m.manuf_id, m.manuf_name, 
    IF(m.manuf_id = manuf, 1, 0) AS mstatus
    FROM manufacturers_tbl m 
    ORDER BY m.manuf_name;
    
    SELECT p.product_id, p.product_name 
    FROM products_tbl p 
    WHERE p.product_brand = brandid 
    ORDER BY p.product_name;
END$$

CREATE  PROCEDURE `editCourier` (IN `courierid` INT)   BEGIN
	SELECT x.courier_id, x.courier_type, x.courier_staffid, x.courier_name, x.courier_mobile, x.courier_vehicle, x.courier_vehregn, x.courier_contact, x.courier_address, x.courier_phones, x.courier_whatsapp, x.courier_email, x.courier_url, x.courier_gst, x.courier_tin, x.courier_notes, x.courier_rates, x.courier_areas, x.courier_areas, x.courier_collect, x.courier_status
    FROM couriers_tbl x 
    WHERE x.courier_id = courierid;
    
    SELECT s.staff_id, s.staff_code, s.staff_name 
    FROM staff_tbl s 
    WHERE s.staff_status = 1 /* AND s.staff_role IN(0,1,2) */
    ORDER BY s.staff_name;
    
    SELECT y.store_id, y.store_code, y.store_name 
    FROM stores_tbl y 
    WHERE y.store_status = 1 
    ORDER BY y.store_name;
    
    SELECT d.delarea_id, d.delarea_location, d.delarea_pincode
    FROM delivery_areas d 
    WHERE d.delarea_status = 1 
    ORDER BY d.delarea_country, d.delarea_province, d.delarea_district, d.delarea_location;
END$$

CREATE  PROCEDURE `editDealor` (IN `dealerid` INT)   BEGIN
	SELECT x.dealer_id, x.dealer_name, x.dealer_address, x.dealer_phones, x.dealer_email, x.dealer_website, x.dealer_contact, x.dealer_contactno, x.dealer_contactemail, x.dealer_contactcell, x.dealer_whatsapp, x.dealer_contactat, x.dealer_regn, x.dealer_GST, x.dealer_TIN, x.dealer_remarks, x.dealer_status
    FROM dealers_tbl x 
    WHERE x.dealer_id = dealerid;
    
    /* list of dealer with parent status and subdealer status */
    SELECT q.dealer_id, q.dealer_name, (SELECT COUNT(*) FROM subdealers_tbl w WHERE w.subdealer_dealer = dealerid AND w.subdealer_parent = q.dealer_id AND w.subdealer_status = 1) AS isParent, (SELECT COUNT(*) FROM subdealers_tbl z WHERE z.subdealer_parent = dealerid AND z.subdealer_dealer = q.dealer_id AND z.subdealer_status = 1)AS isSubDealer 
    FROM dealers_tbl q 
    WHERE q.dealer_id <> dealerid AND q.dealer_status = 1 
    UNION SELECT 0, 0, 0, 0
    ORDER BY dealer_name;
    
    /* products handled by dealer */
    SELECT d.dealerprod_product, m.product_name
    FROM dealer_products d 
    LEFT JOIN products_tbl m ON m.product_id = d.dealerprod_product 
    WHERE d.dealerprod_dealer = dealerid AND d.dealerprod_status = 1 
    /*GROUP BY m.product_manufacturer */
    ORDER BY product_name;
END$$

CREATE  PROCEDURE `editDistributor` (IN `distrbid` INT)   BEGIN
	SELECT d.distri_id, d.distri_name, d.distri_address, d.distri_phones, d.distri_email, d.distri_website, d.distri_contact, d.distri_contactno, d.distri_contactemail, d.distri_contactcell, d.distri_whatsapp, d.distri_contactat, d.distri_regn, d.distri_GST, d.distri_TIN, d.distri_remarks, d.distri_status 
    FROM distributors_tbl d 
    WHERE d.distri_id = distrbid;
    
    /* list of manufacturers */
	SELECT x.manuf_id, x.manuf_name, 
    (SELECT COUNT(*) FROM distributor_manufacturers k 
     WHERE k.distrimanu_distributor = distrbid AND k.distrimanu_company = x.manuf_id AND k.distrimanu_status = 1) AS dstatus
    FROM manufacturers_tbl x 
    WHERE x.manuf_status = 1 
    UNION SELECT 0, 0, 0
    ORDER BY manuf_name;
    
    /* list of distributors with parent status and subdistributor status */
    SELECT q.distri_id, q.distri_name, (SELECT COUNT(*) FROM subdistributors_tbl w WHERE w.subdistri_distributor = distrbid AND w.subdistri_parent = q.distri_id AND w.subdistri_status = 1) AS isParent, (SELECT COUNT(*) FROM subdistributors_tbl z WHERE z.subdistri_parent = distrbid AND z.subdistri_distributor = q.distri_id AND z.subdistri_status = 1)AS isSubDistributor
    FROM distributors_tbl q 
    WHERE q.distri_id <> distrbid AND q.distri_status = 1 
    UNION SELECT 0, 0, 0, 0
    ORDER BY distri_name;
    
    /* products list with handling status */
    SELECT p.product_id, p.product_name, p.product_manufacturer,
    (SELECT COUNT(*) FROM distributor_products dp WHERE dp.distriprod_distributor = distrbid AND dp.distriprod_product = p.product_id AND dp.distriprod_status = 1) AS pstatus 
    FROM products_tbl p 
    WHERE p.product_status = 1 AND p.product_manufacturer IN( 
        SELECT m.distrimanu_company FROM distributor_manufacturers m 
        WHERE m.distrimanu_distributor = distrbid AND m.distrimanu_company = p.product_manufacturer AND m.distrimanu_status = 1) 
    ORDER BY p.product_manufacturer, p.product_name;
    
    
END$$

CREATE  PROCEDURE `editdoctor` (IN `docid` INT)   BEGIN
SELECT d.doctor_id, d.doctor_type, pt.practice_name as dtype, d.doctor_name, d.doctor_regno, d.doctor_mobile, d.doctor_email, d.doctor_degrees, d.doctor_hospital, d.doctor_remarks, d.doctor_photo, d.doctor_signature, d.doctor_datefrom, d.doctor_availfrom, d.doctor_dateto, d.doctor_availto, d.doctor_status, d.doctor_updby FROM doctors_tbl d LEFT JOIN practicestype_tbl pt ON pt.practice_id= d.doctor_type WHERE d.doctor_id=docid ;

 SELECT practice_id, practice_name FROM practicestype_tbl WHERE practice_status =1 UNION SELECT 0,0 ORDER BY practice_name;
END$$

CREATE  PROCEDURE `editDrugClassification` (IN `drgclsid` INT)   BEGIN
	DECLARE parid INT DEFAULT 0;
    
	SELECT x.drugclass_id, x.drugclass_name, x.drugclass_parent, x.drugclass_uses, x.drugclass_warnings, x.drugclass_precautions, x.drugclass_procedure, x.drugclass_dosage, x.drugclass_missdose, x.drugclass_overdose, x.drugclass_avoids, x.drugclass_sideffects, x.drugclass_interactions, x.drugclass_details, x.drugclass_status, x.drugclass_counter, x.drugclass_seq, fnGetDrugclassParent(x.drugclass_id) AS superparent
    FROM drug_classifications x 
    WHERE x.drugclass_id = drgclsid; 
    
    SET parid = fnGetDrugclassParent(drgclsid);

    SELECT y.drugclass_id, y.drugclass_name, y.drugclass_parent as classparent, parid 
    FROM drug_classifications y 
    WHERE (y.drugclass_parent = 0 OR y.drugclass_parent = parid)
    	AND y.drugclass_status = 1 
    UNION SELECT 0, 0, 0, 0 
    ORDER BY classparent, drugclass_name; 
    
    SELECT f.faq_id, f.faq_question, f.faq_answer, f.faq_status
    FROM faq_table f 
    WHERE f.faq_type = 2 AND f.faq_item = drgclsid 
    ORDER BY f.faq_question;
END$$

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

CREATE  PROCEDURE `editGenericMedicine` (IN `medid` INT)   BEGIN
	SELECT genmed_id, genmed_name, genmed_uses, genmed_working, genmed_sideffects, genmed_remarks, genmed_status
    FROM generic_medicines 
    WHERE genmed_id = medid;
    
    SELECT x.faq_id, x.faq_question, x.faq_answer, x.faq_status 
    FROM faq_table x WHERE x.faq_type = 1 AND x.faq_item = medid
    UNION SELECT 0, 0, 0, 0;
    
    SELECT y.advice_id, y.advice_content, y.advice_status 
    FROM advices_table y WHERE y.advice_type = 1 AND y.advice_item = medid 
    UNION SELECT 0, 0, 0;
END$$

CREATE  PROCEDURE `editIngredient` (IN `ingrid` INT)   BEGIN
	SELECT x.ingred_id, x.ingred_name, x.ingred_type, x.ingred_formula, x.ingred_drugbankid, x.ingred_codes, x.ingred_isactive, x.ingred_drugclasses, x.ingred_notes, x.ingred_status 
    FROM ingredients_tbl x 
    WHERE x.ingred_id = ingrid;
    
    SELECT q.ingredtype_id, q.ingredtype_type
    FROM ingredient_types q 
    WHERE q.ingredtype_status = 1;
    
    
END$$

CREATE  PROCEDURE `editInvoice` (IN `invid` INT)   BEGIN
	DECLARE poids VARCHAR(255) DEFAULT 0;
     
	SELECT x.invoice_id, x.invoice_number, x.invoice_vendertype, x.invoice_vendor, fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) AS vendor, x.invoice_dated, x.invoice_amount, x.invoice_cgst, x.invoice_sgst, x.invoice_payby, x.invoice_payment, x.invoice_paidon, x.invoice_paystatus, x.invoice_delstatus, x.invoice_deldate, x.invoice_notes, x.invoice_status,x.invoice_vendorgst,x.invoice_delgst,(SELECT s.store_name FROM stores_tbl s WHERE s.store_id=x.invoice_delstore) as storename
    FROM invoices_tbl x WHERE x.invoice_id = invid;
    
   /*SELECT DISTINCT  invdet_porder INTO poids FROM invoice_details WHERE invdet_invoice=invid;
 
    SELECT xy.podetail_id, xy.podetail_item, xy.podetail_qty, xy.podetail_price, 
    y.vendsup_product,y.vendsup_packing,q.prodpack_id,w.packing_id, p.product_name, p.product_display, 
    q.prodpack_package, q.prodpack_quantity, q.prodpack_unit, w.packing_type, 
    (SELECT z.purchord_deliverat FROM purchase_orders z WHERE z.purchord_id = xy.podetail_order) AS delat, 
    q.prodpack_hsn
    FROM purchase_details xy 
    LEFT JOIN vendor_supplies y ON y.vendsup_id = xy.podetail_item 
    LEFT JOIN products_tbl p ON p.product_id = y.vendsup_product 
    LEFT JOIN product_packing q ON q.prodpack_id = y.vendsup_packing 
    LEFT JOIN packing_tbl w ON w.packing_id = q.prodpack_package 
    WHERE xy.podetail_order = poids;*/
    
    SELECT GROUP_CONCAT(DISTINCT  invdet_porder) INTO poids FROM invoice_details WHERE invdet_invoice=invid;
    
    SELECT xy.podetail_id, xy.podetail_item, xy.podetail_qty, xy.podetail_price, y.vendsup_product,y.vendsup_packing,q.prodpack_id,w.packing_id, p.product_name, p.product_display, q.prodpack_package, q.prodpack_quantity, q.prodpack_unit, w.packing_type, (SELECT z.purchord_deliverat FROM purchase_orders z WHERE z.purchord_id = xy.podetail_order) AS delat, q.prodpack_hsn FROM purchase_details xy LEFT JOIN vendor_supplies y ON y.vendsup_id = xy.podetail_item LEFT JOIN products_tbl p ON p.product_id = y.vendsup_product LEFT JOIN product_packing q ON q.prodpack_id = y.vendsup_packing LEFT JOIN packing_tbl w ON w.packing_id = q.prodpack_package WHERE FIND_IN_SET(xy.podetail_order, poids);
   
    SELECT  y.invdet_id, y.invdet_invoice, y.invdet_porder, p.purchord_ref, p.purchord_date, 
    y.invdet_item, y.invdet_qty, y.invdet_price, y.invdet_schdisc,  y.invdet_cstpc, y.invdet_cst, y.invdet_sstpc, y.invdet_sst, 
    y.invdet_delivered, y.invdet_delstatus, y.invdet_deldate, y.invdet_status, 
    fnGetProductFromPack(y.invdet_item, 0) AS invitem, y.invdet_mrp, y.invdet_free, y.invdet_hsn, y.invdet_ptr, y.invdet_taxamt, y.invdet_discpc, y.invdet_discount, y.invdet_batch, y.invdet_expiry,  
    (SELECT GROUP_CONCAT(invfile_url SEPARATOR ',') FROM invoice_files WHERE invfile_invoice = invid) AS urls,(SELECT COUNT(invfile_url) FROM invoice_files WHERE invfile_invoice = invid) AS urlcnt
    FROM invoice_details y 
    LEFT JOIN purchase_orders p ON p.purchord_id = y.invdet_porder
    WHERE y.invdet_invoice = invid;
    
    /*SELECT k.invfile_id, k.invfile_url 
    FROM invoice_files k WHERE k.invfile_invoice = invid;*/
END$$

CREATE  PROCEDURE `editLocation` (IN `locid` INT)   BEGIN
	DECLARE cntr, state VARCHAR(20) DEFAULT '';
    DECLARE dist INT DEFAULT 0;
    
	SELECT x.delarea_id, x.delarea_location, x.delarea_pincode, x.delarea_country, x.delarea_province, x.delarea_district, x.delarea_remarks, x.delarea_status
    FROM delivery_areas x 
    WHERE x.delarea_id = locid;
    
    SELECT y.strdelv_store, k.store_name, d.delarea_location
    FROM store_delivery y 
    LEFT JOIN delivery_areas d ON d.delarea_id = y.strdelv_area
    LEFT JOIN stores_tbl k ON k.store_id = y.strdelv_store 
    WHERE y.strdelv_area = locid AND y.strdelv_status = 1
    UNION SELECT 0, 0, 0;
    
    SELECT k.delarea_country, k.delarea_province, k.delarea_district INTO cntr, state, dist
    FROM delivery_areas k WHERE k.delarea_id = locid;
    
    SELECT Code, Name, IF(Code = cntr, 1, 0) AS isCountry  
    FROM country WHERE country.storeok = 1
    UNION SELECT 0, 0,0;
    
    SELECT DISTINCT(District), IF(District = state, 1, 0) AS isState  
    FROM city WHERE CountryCode = cntr
    UNION SELECT 0, 0
    ORDER BY District;
    
    SELECT ID, Name, IF(ID = dist, 1, 0) AS isDistrict
    FROM city WHERE District = state AND dist > 0 
    UNION SELECT 0, 0, 0;
    
END$$

CREATE  PROCEDURE `editManufacturer` (IN `manfid` INT)   BEGIN
	SELECT manuf_id, manuf_name,manuf_code ,manuf_address, manuf_phones, manuf_email, manuf_website, manuf_contact,manuf_contactno, manuf_contactemail, manuf_contactcell, manuf_whatsapp, manuf_contactat, manuf_regn, manuf_remarks, manuf_status
    FROM manufacturers_tbl 
    WHERE manuf_id = manfid;
    
    SELECT x.brand_id, x.brand_name
    FROM brands_tbl x 
    WHERE x.brand_owner = manfid AND x.brand_status = 1 
    UNION SELECT 0, 0;

	SELECT product_id, product_name 
    FROM products_tbl  
    WHERE product_manufacturer = manfid 
    UNION SELECT 0, 0 
    ORDER BY product_name;
    
    SELECT stockmanu_stockist, stockist_name
    FROM stockist_manufacturers 
    LEFT JOIN stockists_tbl ON stockmanu_stockist = stockist_id 
    WHERE stockmanu_company = manfid and stockmanu_status = 1
    UNION SELECT 0, 0 
    ORDER BY stockist_name;
    
    SELECT distrimanu_distributor, distri_name
    FROM distributor_manufacturers  
    LEFT JOIN distributors_tbl ON distri_id = distrimanu_distributor
    WHERE distrimanu_company = manfid and distrimanu_status=1
    UNION SELECT 0, 0 
    ORDER BY distri_name;
    
END$$

CREATE  PROCEDURE `editOrderDetails` (IN `ordid` INT)   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,strid INT,strname VARCHAR(255),strcode VARCHAR(255),orderstatus INT,deliverystatus INT,ordcrton DATETIME,ordproc DATETIME,ordship DATETIME,orddeliv DATETIME, ordcancl DATETIME, ordref DATETIME, remarks TEXT);
SELECT o.order_id,o.order_customer,o.order_orderid,DATE(o.order_date)as dates,o.order_source,o.order_trackid,o.order_remarks,o.order_delivery,d.delivery_to, o.order_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,p.paymt_transid,p.paymt_paidon,p.paymt_paid,o.orders_shipped,o.order_finalshipby  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 JOIN payments_tbl p ON p.paymt_orderid=o.order_id AND p.paymt_userid=o.order_customer

WHERE o.order_id=ordid LIMIT 1;

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 d.ordet_order=ordid;

/*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(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 WHERE d.ordet_order=ordid  GROUP BY ordet_cartid) AS X;*/




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,strid,strname,strcode,orderstatus,deliverystatus,ordcrton,ordproc,ordship,orddeliv,ordcancl,ordref,remarks)
            SELECT p.product_id,fnGetProductFromPack(r.prodpack_id,0)AS 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,e.strstk_store,st.store_name,st.store_code,@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 JOIN stores_tbl st ON st.store_id=e.strstk_store
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$$

CREATE  PROCEDURE `editProduct` (IN `prodid` INT)   BEGIN
	DECLARE genrc, mcat, scat, cat, mdclass, sdclass, dclass INT DEFAULT 0;
    
	SELECT x.product_id, x.product_name, x.product_display, x.product_generic, x.product_maincategory, x.product_subcategory, x.product_category, x.product_manufacturer, x.product_brand, x.product_drugmainclass, x.product_drugsubclass, x.product_drugclass, x.product_classified, x.product_prescrption, x.product_highlights, x.product_information, x.product_working, x.product_howto, x.product_benefits, x.product_specifications, x.product_features, x.product_usage, x.product_precautions, x.product_warnings, x.product_sideffects, x.product_antidot, x.product_interactions, x.product_publish, x.product_sale, x.product_online, x.product_featured, x.product_popular, x.product_taxgroup, x.product_status,x.product_schedule, x.product_approve, x.product_pcontent, p.pharma_name AS pharmaname
    FROM products_tbl x LEFT JOIN pharmacologicalcontent_tbl p ON p.pharma_id = x.product_pcontent
 WHERE x.product_id = prodid;
    
 SELECT p.prodingred_product, p.prodingred_ingredient, p.prodingred_quantity, p.prodingred_unit, p.prodingred_status, t.ingred_name, m.measunit_name, m.measunit_shortname 
    FROM product_ingredients p 
    LEFT JOIN ingredients_tbl t on t.ingred_id=p.prodingred_ingredient
    LEFT JOIN measure_units m ON m.measunit_id = p.prodingred_unit 
    WHERE p.prodingred_product = prodid 
    UNION SELECT 0, 0, 0, 0, 0, 0,0,0;
   
    SELECT k.prodpack_id, k.prodpack_product, k.prodpack_package, k.prodpack_quantity, k.prodpack_unit,p.packing_type , k.prodpack_status, b.measunit_name, b.measunit_shortname, k.prodpack_maxstock, k.prodpack_minstock, k.prodpack_roq, k.prodpack_hsn, k.prodpack_taxgroup  
    FROM product_packing k  
    LEFT JOIN packing_tbl p ON p.packing_id = k.prodpack_package 
    LEFT JOIN measure_units b ON b.measunit_id = k.prodpack_unit 
    WHERE k.prodpack_product = prodid 
    UNION SELECT 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0;
    
    SELECT q.product_generic, q.product_maincategory, q.product_subcategory, q.product_category, q.product_drugmainclass, q.product_drugsubclass, q.product_drugclass INTO genrc, mcat, scat, cat, mdclass, sdclass, dclass 
    FROM products_tbl q WHERE q.product_id = prodid;    
    
   
	/* Generic Names */
	SELECT genmed_id, genmed_name, IF(genrc = genmed_id, 1, 0) AS isgeneric 
    FROM generic_medicines 
    WHERE genmed_status = 1 
    UNION SELECT 0, 0, 0 
    ORDER BY genmed_name;
    
    /* Main categories */
    SELECT prodclass_id, prodclass_name, prodclass_serial,
    IF(prodclass_id = mcat, 1, 0) AS maincat, 
    IF(prodclass_id = scat, 1, 0) AS subcat, 
    IF(prodclass_id = cat, 1, 0) AS cat, prodclass_parent
    FROM product_classes  
    WHERE prodclass_parent IN(0, mcat, scat, cat) AND prodclass_status = 1 
    UNION SELECT 0, 0, 0, 0, 0, 0, 0  
    ORDER BY prodclass_serial;
    
    /* Basic drug classes */
    SELECT drugclass_id, drugclass_name, 
    IF(mdclass = drugclass_id, 1, 0) AS mainclass, 
    IF(sdclass = drugclass_id, 1, 0) AS subclass, 
    IF(dclass = drugclass_id, 1, 0) AS drugclass
    FROM drug_classifications 
    WHERE drugclass_status = 1 AND drugclass_parent in(0, mdclass, sdclass, dclass) 
    UNION SELECT 0, 0, 0, 0, 0  
    ORDER BY drugclass_name;
    
    /* All Brands */
    SELECT brand_id, brand_name, brand_owner
    FROM brands_tbl WHERE brand_status = 1 
    UNION SELECT 0, 0, 0 
    ORDER BY brand_name;
    
    /* All Manufacturors */
    SELECT manuf_id, manuf_name, 
    (SELECT GROUP_CONCAT(brand_id SEPARATOR ',') FROM brands_tbl WHERE brand_owner = manuf_id) AS brands 
    FROM manufacturers_tbl WHERE manuf_status = 1 
    UNION SELECT 0, 0, 0 
    ORDER BY manuf_name;
    
    /* Ingredients */
    SELECT ingredtype_id, ingredtype_type 
    FROM ingredient_types WHERE ingredtype_status = 1 
    UNION SELECT 0, 0 
    ORDER BY ingredtype_type;

	/* Packaging types */
    SELECT packing_id, packing_type 
    FROM packing_tbl WHERE packing_status = 1;
    
    /* Measuring units */
    SELECT measunit_id, measunit_name, measunit_shortname 
    FROM measure_units WHERE measunit_status = 1;
    
    /* GST Tax rates */
    SELECT tax_id, tax_group, tax_rate 
    FROM tax_groups WHERE tax_status = 1;
    
    SELECT sch_id, sch_name, sch_code FROM schedule_tbl WHERE sch_status=1;
    /* faq */
    SELECT f.faq_id, f.faq_question, f.faq_answer, f.faq_status 
    FROM faq_table f WHERE f.faq_type = 3 AND f.faq_item = prodid 
    UNION SELECT 0, 0, 0, 0;
    
    
    /* Suppliers handling the product */
    SELECT stockistprod_stockist AS supplier, stockist_name AS supname, 1 as suptype 
    FROM stockist_products  
    LEFT JOIN stockists_tbl ON stockist_id = stockistprod_stockist 
    WHERE stockistprod_product = prodid AND stockistprod_status = 1
    UNION
    SELECT distriprod_distributor AS supplier, distri_name AS supname, 2 as suptype 
    FROM distributor_products 
    LEFT JOIN distributors_tbl ON distri_id = distriprod_distributor 
    WHERE distriprod_product = prodid AND distriprod_status = 1
    UNION
    SELECT dealerprod_dealer AS supplier, dealer_name AS supname, 3 AS suptype
    FROM dealer_products  
    LEFT JOIN dealers_tbl ON dealer_id = dealerprod_dealer
    WHERE dealerprod_product = prodid AND dealerprod_status = 1; 
    
       /*Pharamacological content*/
    SELECT p.pharma_id, p.pharma_name FROM pharmacologicalcontent_tbl p WHERE p.pharma_status=1;
END$$

CREATE  PROCEDURE `editProductEntryData` (IN `prodid` INT)   BEGIN
	DECLARE genrc, mcat, scat, cat, mdclass, sdclass, dclass INT DEFAULT 0;
     SELECT  x.product_manufacturer INTO @brand
    FROM products_entry_tbl x LEFT JOIN pharmacologicalcontent_tbl p ON p.pharma_id = x.product_pcontent
 WHERE x.product_id = prodid;
    
	SELECT x.product_id, x.product_name, x.product_display, x.product_generic, x.product_maincategory, x.product_subcategory, x.product_category, x.product_manufacturer, x.product_brand, x.product_drugmainclass, x.product_drugsubclass, x.product_drugclass, x.product_classified, x.product_prescrption, x.product_highlights, x.product_information, x.product_working, x.product_howto, x.product_benefits, x.product_specifications, x.product_features, x.product_usage, x.product_precautions, x.product_warnings, x.product_sideffects, x.product_antidot, x.product_interactions, x.product_publish, x.product_sale, x.product_online, x.product_featured, x.product_popular, x.product_taxgroup, x.product_status,x.product_schedule, x.product_approve, x.product_pcontent, p.pharma_name AS pharmaname
    FROM products_entry_tbl x LEFT JOIN pharmacologicalcontent_tbl p ON p.pharma_id = x.product_pcontent
 WHERE x.product_id = prodid;
    
 SELECT p.prodingred_product, p.prodingred_ingredient, p.prodingred_quantity, p.prodingred_unit, p.prodingred_status, t.ingred_name, m.measunit_name, m.measunit_shortname 
    FROM product_ingredients p 
    LEFT JOIN ingredients_tbl t on t.ingred_id=p.prodingred_ingredient
    LEFT JOIN measure_units m ON m.measunit_id = p.prodingred_unit 
    WHERE p.prodingred_product = prodid 
    UNION SELECT 0, 0, 0, 0, 0, 0,0,0;
   
    SELECT k.prodpack_id, k.prodpack_product, k.prodpack_package, k.prodpack_quantity, k.prodpack_unit,p.packing_type , k.prodpack_status, b.measunit_name, b.measunit_shortname, k.prodpack_maxstock, k.prodpack_minstock, k.prodpack_roq, k.prodpack_hsn, b.measunit_id,k.prodpack_taxgroup  
    FROM product_packing k  
    LEFT JOIN packing_tbl p ON p.packing_id = k.prodpack_package 
    LEFT JOIN measure_units b ON b.measunit_id = k.prodpack_unit 
    WHERE k.prodpack_product = prodid 
    UNION SELECT 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0,0;
    
    SELECT q.product_generic, q.product_maincategory, q.product_subcategory, q.product_category, q.product_drugmainclass, q.product_drugsubclass, q.product_drugclass INTO genrc, mcat, scat, cat, mdclass, sdclass, dclass 
    FROM products_entry_tbl q WHERE q.product_id = prodid;    
    
   
	/* Generic Names 
	SELECT genmed_id, genmed_name, IF(genrc = genmed_id, 1, 0) AS isgeneric 
    FROM generic_medicines 
    WHERE genmed_status = 1 
    UNION SELECT 0, 0, 0 
    ORDER BY genmed_name;
    */
    /* Main categories */
    SELECT prodclass_id, prodclass_name, prodclass_serial,
    IF(prodclass_id = mcat, 1, 0) AS maincat, 
    IF(prodclass_id = scat, 1, 0) AS subcat, 
    IF(prodclass_id = cat, 1, 0) AS cat, prodclass_parent
    FROM product_classes  
    WHERE prodclass_parent IN(0, mcat, scat, cat) AND prodclass_status = 1 
    UNION SELECT 0, 0, 0, 0, 0, 0, 0  
    ORDER BY prodclass_serial;
    
    /* Basic drug classes */
    SELECT drugclass_id, drugclass_name, 
    IF(mdclass = drugclass_id, 1, 0) AS mainclass, 
    IF(sdclass = drugclass_id, 1, 0) AS subclass, 
    IF(dclass = drugclass_id, 1, 0) AS drugclass
    FROM drug_classifications 
    WHERE drugclass_status = 1 AND drugclass_parent in(0, mdclass, sdclass, dclass) 
    UNION SELECT 0, 0, 0, 0, 0  
    ORDER BY drugclass_name;
    
    /* All Brands */
     SELECT brand_id, brand_name, brand_owner
    FROM brands_tbl WHERE brand_status = 1 and brand_owner=@brand
    UNION SELECT 0, 0, 0 
    ORDER BY brand_name;
    
    
    /* All Manufacturors */
    /*SELECT manuf_id, manuf_name, 
    (SELECT GROUP_CONCAT(brand_id SEPARATOR ',') FROM brands_tbl WHERE brand_owner = manuf_id) AS brands 
    FROM manufacturers_tbl WHERE manuf_status = 1 
    UNION SELECT 0, 0, 0 
    ORDER BY manuf_name;*/
    
    SELECT 
    m.manuf_id, 
    m.manuf_name, 
    GROUP_CONCAT(b.brand_id SEPARATOR ',') AS brands
FROM manufacturers_tbl m
LEFT JOIN brands_tbl b 
    ON b.brand_owner = m.manuf_id
WHERE m.manuf_status = 1
GROUP BY m.manuf_id, m.manuf_name

UNION ALL

SELECT 0, 'Select Manufacturer', '0'

ORDER BY manuf_name;
    
    /* Ingredients */
    SELECT ingredtype_id, ingredtype_type 
    FROM ingredient_types WHERE ingredtype_status = 1 
    UNION SELECT 0, 0 
    ORDER BY ingredtype_type;

	/* Packaging types */
    SELECT packing_id, packing_type 
    FROM packing_tbl WHERE packing_status = 1;
    
    /* Measuring units */
    SELECT measunit_id, measunit_name, measunit_shortname 
    FROM measure_units WHERE measunit_status = 1;
    
    /* GST Tax rates */
    SELECT tax_id, tax_group, tax_rate 
    FROM tax_groups WHERE tax_status = 1;
    
    SELECT sch_id, sch_name, sch_code FROM schedule_tbl WHERE sch_status=1;
    /* faq */
    SELECT f.faq_id, f.faq_question, f.faq_answer, f.faq_status 
    FROM faq_table f WHERE f.faq_type = 3 AND f.faq_item = prodid 
    UNION SELECT 0, 0, 0, 0;
    
    
    /* Suppliers handling the product */
    SELECT stockistprod_stockist AS supplier, stockist_name AS supname, 1 as suptype 
    FROM stockist_products  
    LEFT JOIN stockists_tbl ON stockist_id = stockistprod_stockist 
    WHERE stockistprod_product = prodid AND stockistprod_status = 1
    UNION
    SELECT distriprod_distributor AS supplier, distri_name AS supname, 2 as suptype 
    FROM distributor_products 
    LEFT JOIN distributors_tbl ON distri_id = distriprod_distributor 
    WHERE distriprod_product = prodid AND distriprod_status = 1
    UNION
    SELECT dealerprod_dealer AS supplier, dealer_name AS supname, 3 AS suptype
    FROM dealer_products  
    LEFT JOIN dealers_tbl ON dealer_id = dealerprod_dealer
    WHERE dealerprod_product = prodid AND dealerprod_status = 1; 
    
      
    #SELECT p.pharma_id, p.pharma_name FROM pharmacologicalcontent_tbl p WHERE p.pharma_status=1;
END$$

CREATE  PROCEDURE `editProductEntryDataNew` (IN `prodid` INT)   BEGIN
	DECLARE genrc, mcat, scat, cat, mdclass, sdclass, dclass INT DEFAULT 0;
     SELECT  x.product_manufacturer INTO @brand
    FROM products_entry_tbl x LEFT JOIN pharmacologicalcontent_tbl p ON p.pharma_id = x.product_pcontent
 WHERE x.product_id = prodid;
    
	SELECT x.product_id, x.product_name, x.product_display, x.product_generic, x.product_maincategory, x.product_subcategory, x.product_category, x.product_manufacturer, x.product_brand, x.product_drugmainclass, x.product_drugsubclass, x.product_drugclass, x.product_classified, x.product_prescrption, x.product_highlights, x.product_information, x.product_working, x.product_howto, x.product_benefits, x.product_specifications, x.product_features, x.product_usage, x.product_precautions, x.product_warnings, x.product_sideffects, x.product_antidot, x.product_interactions, x.product_publish, x.product_sale, x.product_online, x.product_featured, x.product_popular, x.product_taxgroup, x.product_status,x.product_schedule, x.product_approve, x.product_pcontent, p.pharma_name AS pharmaname
    FROM products_entry_tbl x LEFT JOIN pharmacologicalcontent_tbl p ON p.pharma_id = x.product_pcontent
 WHERE x.product_id = prodid;
    
 SELECT p.prodingred_product, p.prodingred_ingredient, p.prodingred_quantity, p.prodingred_unit, p.prodingred_status, t.ingred_name, m.measunit_name, m.measunit_shortname 
    FROM product_ingredients p 
    LEFT JOIN ingredients_tbl t on t.ingred_id=p.prodingred_ingredient
    LEFT JOIN measure_units m ON m.measunit_id = p.prodingred_unit 
    WHERE p.prodingred_product = prodid 
    UNION SELECT 0, 0, 0, 0, 0, 0,0,0;
   
    SELECT k.prodpack_id, k.prodpack_product, k.prodpack_package, k.prodpack_quantity, k.prodpack_unit,p.packing_type , k.prodpack_status, b.measunit_name, b.measunit_shortname, k.prodpack_maxstock, k.prodpack_minstock, k.prodpack_roq, k.prodpack_hsn, b.measunit_id,k.prodpack_taxgroup  
    FROM product_packing k  
    LEFT JOIN packing_tbl p ON p.packing_id = k.prodpack_package 
    LEFT JOIN measure_units b ON b.measunit_id = k.prodpack_unit 
    WHERE k.prodpack_product = prodid 
    UNION SELECT 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0,0;
    
    SELECT q.product_generic, q.product_maincategory, q.product_subcategory, q.product_category, q.product_drugmainclass, q.product_drugsubclass, q.product_drugclass INTO genrc, mcat, scat, cat, mdclass, sdclass, dclass 
    FROM products_entry_tbl q WHERE q.product_id = prodid;    
    
   
	/* Generic Names 
	SELECT genmed_id, genmed_name, IF(genrc = genmed_id, 1, 0) AS isgeneric 
    FROM generic_medicines 
    WHERE genmed_status = 1 
    UNION SELECT 0, 0, 0 
    ORDER BY genmed_name;
    */
    /* Main categories */
    SELECT prodclass_id, prodclass_name, prodclass_serial,
    IF(prodclass_id = mcat, 1, 0) AS maincat, 
    IF(prodclass_id = scat, 1, 0) AS subcat, 
    IF(prodclass_id = cat, 1, 0) AS cat, prodclass_parent
    FROM product_classes  
    WHERE prodclass_parent IN(0, mcat, scat, cat) AND prodclass_status = 1 
    UNION SELECT 0, 0, 0, 0, 0, 0, 0  
    ORDER BY prodclass_serial;
    
    /* Basic drug classes */
    SELECT drugclass_id, drugclass_name, 
    IF(mdclass = drugclass_id, 1, 0) AS mainclass, 
    IF(sdclass = drugclass_id, 1, 0) AS subclass, 
    IF(dclass = drugclass_id, 1, 0) AS drugclass
    FROM drug_classifications 
    WHERE drugclass_status = 1 AND drugclass_parent in(0, mdclass, sdclass, dclass) 
    UNION SELECT 0, 0, 0, 0, 0  
    ORDER BY drugclass_name;
    
    /* All Brands */
     
    SELECT * FROM (SELECT brand_id, brand_name, brndmanu_id as brand_owner
    FROM brands_tbl b JOIN brand_manufacturer_tbl m ON b.brand_id=m.brnd_id  WHERE b.brand_status = 1 and m.brndmanu_id=@brand UNION SELECT 0, 0, 0 ) AS x ORDER BY x.brand_name;
    
    /* All Manufacturors */
   /* SELECT manuf_id, manuf_name, 
    (SELECT GROUP_CONCAT(brand_id SEPARATOR ',') FROM brands_tbl WHERE brand_owner = manuf_id) AS brands 
    FROM manufacturers_tbl WHERE manuf_status = 1 
    UNION SELECT 0, 0, 0 
    ORDER BY manuf_name;
    */
    SELECT 
    m.manuf_id, 
    m.manuf_name, 
    GROUP_CONCAT(b.brnd_id SEPARATOR ',') AS brands
FROM manufacturers_tbl m
LEFT JOIN brand_manufacturer_tbl b 
    ON b.brndmanu_id = m.manuf_id AND b.brndmanu_id=@brand
WHERE m.manuf_status = 1 AND m.manuf_id=@brand
GROUP BY m.manuf_id, m.manuf_name

UNION ALL

SELECT 0, 'Select Manufacturer', '0'

ORDER BY manuf_name;
    
    /* Ingredients */
    SELECT ingredtype_id, ingredtype_type 
    FROM ingredient_types WHERE ingredtype_status = 1 
    UNION SELECT 0, 0 
    ORDER BY ingredtype_type;

	/* Packaging types */
    SELECT packing_id, packing_type 
    FROM packing_tbl WHERE packing_status = 1;
    
    /* Measuring units */
    SELECT measunit_id, measunit_name, measunit_shortname 
    FROM measure_units WHERE measunit_status = 1;
    
    /* GST Tax rates */
    SELECT tax_id, tax_group, tax_rate 
    FROM tax_groups WHERE tax_status = 1;
    
    SELECT sch_id, sch_name, sch_code FROM schedule_tbl WHERE sch_status=1;
    /* faq */
    SELECT f.faq_id, f.faq_question, f.faq_answer, f.faq_status 
    FROM faq_table f WHERE f.faq_type = 3 AND f.faq_item = prodid 
    UNION SELECT 0, 0, 0, 0;
    
    
    /* Suppliers handling the product */
    SELECT stockistprod_stockist AS supplier, stockist_name AS supname, 1 as suptype 
    FROM stockist_products  
    LEFT JOIN stockists_tbl ON stockist_id = stockistprod_stockist 
    WHERE stockistprod_product = prodid AND stockistprod_status = 1
    UNION
    SELECT distriprod_distributor AS supplier, distri_name AS supname, 2 as suptype 
    FROM distributor_products 
    LEFT JOIN distributors_tbl ON distri_id = distriprod_distributor 
    WHERE distriprod_product = prodid AND distriprod_status = 1
    UNION
    SELECT dealerprod_dealer AS supplier, dealer_name AS supname, 3 AS suptype
    FROM dealer_products  
    LEFT JOIN dealers_tbl ON dealer_id = dealerprod_dealer
    WHERE dealerprod_product = prodid AND dealerprod_status = 1; 
    
      
    #SELECT p.pharma_id, p.pharma_name FROM pharmacologicalcontent_tbl p WHERE p.pharma_status=1;
END$$

CREATE  PROCEDURE `editProductStockPricing` (IN `prodid` INT)   BEGIN
	SELECT x.strstk_id, x.strstk_store, x.strstk_item, fnGetProductFromPack(x.strstk_item, 0) AS product,
    s.stockin_batch, s.stockin_expiry, x.strstk_mrp, x.strstk_cost, x.strstk_msp, x.strstk_discount, x.strstk_stock, (x.strstk_stock-x.strstk_reserved) AS stock,
    x.strstk_offer, x.strstk_offerfrom, x.strstk_offerto, x.strstk_dealofday, x.strstk_dealfrom, x.strstk_dealto,
    p.product_name, p.product_display, t.store_name
    FROM storestock_pricing x
    LEFT JOIN stock_inwards s ON s.stockin_id = x.strstk_refer
    LEFT JOIN products_tbl p ON p.product_id = x.strstk_product
    LEFT JOIN stores_tbl t ON t.store_id = x.strstk_store
    WHERE x.strstk_item = prodid AND x.strstk_status = 1 AND x.strstk_stock > 0
    ORDER BY s.stockin_expiry,  x.strstk_store, x.strstk_item ASC;
	/*
   SELECT p.product_id, p.product_name, p.product_display, s.store_id, s.store_name,
    x.stockin_id, x.stockin_item,  fnGetProductFromPack(x.stockin_item, 0) AS product,
    x.stockin_store, x.stockin_batch, x.stockin_expiry, x.stockin_balance, d.invdet_mrp
    FROM stock_inwards x
    LEFT JOIN product_packing k ON k.prodpack_id = x.stockin_item
    LEFT JOIN products_tbl p ON p.product_id = k.prodpack_product
    LEFT JOIN invoice_details d ON d.invdet_invoice = x.stockin_invref
    LEFT JOIN stores_tbl s ON s.store_id = x.stockin_store
    WHERE x.stockin_balance > 0 AND p.product_id = prodid
    ORDER BY x.stockin_item; */
END$$

CREATE  PROCEDURE `editPromotions` (IN `promoid` INT)   BEGIN
	SELECT p.promo_id,p.promo_type,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 WHERE p.promo_id=promoid;
	SELECT pp.promotype_id,pp.promotype_name,pp.promotype_status  FROM promotiontypes_tbl pp WHERE pp.promotype_status > 0;
END$$

CREATE  PROCEDURE `editPurchaseOrder` (IN `poid` INT)   BEGIN
	DECLARE ventype, venid INT DEFAULT 0;
	SELECT purchord_id, purchord_ref, purchord_date, purchord_license, purchord_amount,
    purchord_vendtype, purchord_vendor, fnGetVendorName(purchord_vendtype, purchord_vendor) AS vendor,
    purchord_notes, purchord_supply, purchord_progress,
    purchord_preprdby,(select u.user_staffname from users_tbl u WHERE u.user_id = purchord_preprdby) as preparedbyname, purchord_preprdon, purchord_aprvdby,(select u.user_staffname from users_tbl u WHERE u.user_id = purchord_aprvdby) as aprvdbyname,  purchord_aprvdon,
    purchord_issuedby,(select u.user_staffname from users_tbl u WHERE u.user_id = purchord_issuedby) as issuedbyname,   purchord_issuedon, purchord_status, (select s.staff_signature FROM staff_tbl s LEFT JOIN users_tbl u ON u.user_staffid=s.staff_id WHERE u.user_id = purchord_aprvdby) as aprvdbysign,(select s.staff_signature FROM staff_tbl s LEFT JOIN users_tbl u ON u.user_staffid=s.staff_id WHERE u.user_id = purchord_issuedby) as isuedbysign,
    fnGetVendorContacts(purchord_vendtype, purchord_vendor) AS contacts,
    purchord_deliverat, store_name, purchord_deliverby
    FROM purchase_orders
    LEFT JOIN stores_tbl ON store_id = purchord_deliverat
    WHERE purchord_id = poid;
    
    SELECT podetail_id, podetail_order, podetail_item, x.vendsup_product, p.product_name, x.vendsup_packing, q.packing_type, podetail_qty,
    podetail_price, podetail_status,CONCAT(q.packing_type, ' ', z.prodpack_quantity, ' ', m.measunit_shortname) AS boxunit
    FROM purchase_details
    LEFT JOIN vendor_supplies x ON x.vendsup_id = podetail_item
    LEFT JOIN products_tbl p ON p.product_id = x.vendsup_product
    LEFT JOIN product_packing z ON z.prodpack_id = x.vendsup_packing
    LEFT JOIN packing_tbl q ON q.packing_id = z.prodpack_package
    LEFT JOIN measure_units m ON m.measunit_id =z.prodpack_unit
    WHERE podetail_order = poid;
    SELECT purchord_vendtype, purchord_vendor INTO ventype, venid
    FROM purchase_orders WHERE purchord_id = poid;
   /* IF ventype = 1 THEN
    	SELECT x.stockistprod_product AS pid,a.stockist_email, p.product_name, p.product_display
        FROM stockist_products x
        LEFT JOIN products_tbl p ON p.product_id = x.stockistprod_product
        LEFT JOIN stockists_tbl a ON a.stockist_id= x.stockistprod_stockist
        WHERE x.stockistprod_stockist = venid AND x.stockistprod_status = 1
        ORDER BY p.product_display;
    ELSEIF ventype = 2 THEN
    	SELECT d.distriprod_product AS pid, p.product_name, p.product_display
        FROM distributor_products d
        LEFT JOIN products_tbl p ON p.product_id = d.distriprod_product
        WHERE d.distriprod_distributor = venid AND d.distriprod_status = 1
        ORDER BY p.product_display;
    ELSE
    	SELECT q.dealerprod_product AS pid, p.product_name, p.product_display
        FROM dealer_products q
        LEFT JOIN products_tbl p ON p.product_id = q.dealerprod_product
        WHERE q.dealerprod_dealer = venid AND q.dealerprod_status = 1
        ORDER BY p.product_display;
    END IF; */
    IF ventype = 1 THEN   /* Stockists */
    	SELECT x.stockistprod_product AS pid, p.product_name, p.product_display, 'Stockist' AS suppliertype,s.stockist_GST,p.product_taxgroup
        FROM stockist_products x
        INNER JOIN products_tbl p ON p.product_id = x.stockistprod_product INNER JOIN vendor_supplies v on v.vendsup_product=p.product_id INNER JOIN stockists_tbl s ON s.stockist_id=x.stockistprod_stockist
        WHERE x.stockistprod_stockist = venid AND x.stockistprod_status = 1 AND v.vendsup_vendor = venid AND v.vendsup_type = ventype AND v.vendsup_status = 1
        GROUP BY p.product_display;
    ELSEIF ventype = 2 THEN  /* Distributors */
    	SELECT d.distriprod_product AS pid, p.product_name, p.product_display, '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 = venid AND d.distriprod_status = 1 AND v.vendsup_vendor = venid AND v.vendsup_type = ventype AND v.vendsup_status = 1
        GROUP BY p.product_display;
    ELSE
    	SELECT q.dealerprod_product AS pid, p.product_name, p.product_display, '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 = venid AND q.dealerprod_status = 1 AND v.vendsup_vendor = venid AND v.vendsup_type = ventype AND v.vendsup_status = 1
        GROUP BY p.product_display;
    END IF;
    /* Stores and type of store for new orders */
    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;
END$$

CREATE  PROCEDURE `editScheduleDiscountData` (IN `discid` INT)   BEGIN
 SELECT s.dis_id,s.dis_date,s.dis_store,sb.store_code,sb.store_name, s.dis_mainitem,s.dis_freeitem,s.dis_status,s.dis_note,s.dis_crtdby,s.dis_approvedby FROM schedulediscount_tbl s JOIN stores_tbl sb on sb.store_id=s.dis_store WHERE s.dis_id=discid;
 END$$

CREATE  PROCEDURE `editStockInwardInvoice` (IN `invid` INT)   BEGIN
	SELECT x.invoice_id, x.invoice_number, x.invoice_dated,
    fnGetVendorName(x.invoice_vendertype, x.invoice_vendor) as vendor,
    (SELECT GROUP_CONCAT( DISTINCT(CONCAT(q.purchord_ref, ' Dtd:', DATE_FORMAT(q.purchord_date, '%d-%m-%Y'))) SEPARATOR ',') FROM invoice_details z LEFT JOIN purchase_orders q ON q.purchord_id = z.invdet_porder WHERE z.invdet_invoice = x.invoice_id) AS porders,
    /*(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 , x.invoice_status, x.invoice_delstatus, x.invoice_delnotes,
     (SELECT GROUP_CONCAT( f.invfile_url SEPARATOR ',') FROM invoice_files f
      WHERE f.invfile_invoice = invid AND f.invfile_status = 1) AS fileurls
    FROM invoices_tbl x WHERE x.invoice_id = invid;
    SELECT d.invdet_id, d.invdet_item, fnGetProductFromPack(d.invdet_item, 0) AS invitem, (d.invdet_qty+d.invdet_free)AS tquantity, d.invdet_delivered,
    (SELECT COUNT(*) FROM stock_inwards y WHERE y.stockin_invref = d.invdet_id) AS marked,
    s.stockin_qrcode, s.stockin_supdate, s.stockin_batch, s.stockin_expiry, s.stockin_stack, s.stockin_damaged,
    s.stockin_inward, d.invdet_mrp, s.stockin_mrp, d.invdet_batch, d.invdet_expiry,sb.storage_label
    FROM invoice_details d
    LEFT JOIN stock_inwards s ON s.stockin_invref = d.invdet_id
    LEFT JOIN storage_tbl sb on sb.storage_id=s.stockin_stack
    WHERE d.invdet_invoice = invid;
    SELECT h.handling_id, h.handling_charge, e.stokexp_amount
    FROM handling_charges h
    LEFT JOIN stockin_expenses e ON (e.stokexp_chargeon = h.handling_id AND e.stokexp_type = 1 AND e.stokexp_refer = invid AND e.stokexp_status = 1)
    WHERE h.handling_status = 1;
   # stack selection
   SELECT s.storage_id,s.storage_label,s.storage_status  FROM storage_tbl s WHERE s.storage_status=1;
END$$

CREATE  PROCEDURE `editStockist` (IN `stkid` INT)   BEGIN
	SELECT stockist_id, stockist_name, stockist_address, stockist_phones, stockist_email, stockist_website, stockist_contact, stockist_contactno, stockist_contactemail, stockist_contactcell, stockist_whatsapp, stockist_contactat, stockist_regn, stockist_GST, stockist_TIN, stockist_remarks, stockist_status
    FROM stockists_tbl  
    WHERE stockist_id = stkid;
   
    SELECT manuf_id, manuf_name, 
    (SELECT COUNT(*) FROM stockist_manufacturers  
     WHERE stockmanu_stockist = stkid AND stockmanu_company = manuf_id AND stockmanu_status = 1) AS mstatus 
    FROM manufacturers_tbl  
    WHERE manuf_status = 1 
    UNION SELECT 0, 0, 0
    ORDER BY manuf_name;
   
    SELECT product_id, product_name, product_manufacturer,
    /*(SELECT COUNT(*) FROM stockist_manufacturers WHERE stockmanu_stockist = stkid AND stockmanu_company = product_manufacturer)*/ (SELECT COUNT(*) FROM stockist_products sp WHERE sp.stockistprod_stockist = stkid AND sp.stockistprod_product = product_id AND sp.stockistprod_status=1) AS pstatus
FROM products_tbl
 WHERE product_status = 1 AND product_manufacturer IN(
SELECT s.stockmanu_company FROM stockist_manufacturers s
 WHERE s.stockmanu_stockist = stkid AND s.stockmanu_company =product_manufacturer AND  s.stockmanu_status = 1) 
    ORDER BY product_manufacturer, product_name;
END$$

CREATE  PROCEDURE `editStorage` (IN `strgid` INT)   BEGIN
    SELECT s.storage_id, s.storage_label, s.storage_type, s.storage_temperature, s.storage_humidity, s.storage_security, s.storage_status, s.storage_volume, s.storage_size, s.storage_load, s.storage_remarks, s.storage_crtdby FROM storage_tbl s WHERE s.storage_id=strgid;
        SELECT t.strgtype_id, t.strgtype_type FROM storage_types t WHERE t.strgtype_status=1;
            END$$

CREATE  PROCEDURE `editStore` (IN `storeid` INT)   BEGIN
	SELECT store_id, store_type, store_code, store_name, store_address, store_phones, store_mobile, store_email, store_whatsapp, store_contact, store_contactno, store_contactemail, store_contactcell, store_contactwapp, store_contactat, store_regn, store_GST, store_TIN, store_power, store_water, store_location, store_remarks, store_status,store_license,store_pan,store_taxstate
    FROM stores_tbl WHERE store_id = storeid;
    
    SELECT strtme_day, strtme_session, strtme_from, strtme_to 
    FROM store_timings WHERE strtme_store = storeid AND strtme_status = 1 
    UNION SELECT 0, 0, 0, 0 
    ORDER BY strtme_day, strtme_session;
    
    SELECT storetype_id, storetype_name
    FROM store_types WHERE storetype_status = 1;
    
    SELECT k.delarea_id, k.delarea_location, k.delarea_pincode, (SELECT COUNT(*) FROM store_delivery d WHERE d.strdelv_store = storeid AND d.strdelv_area = k.delarea_id and d.strdelv_status = 1) AS isDelarea 
    FROM delivery_areas k 
    WHERE k.delarea_status = 1 
    ORDER BY k.delarea_location;
END$$

CREATE  PROCEDURE `editStoreIntend` (IN `intendid` INT)   BEGIN
	SELECT x.store_id, x.store_code, x.store_name 
    FROM stores_tbl x 
    WHERE x.store_status = 1;
    
	SELECT x.intend_id, x.intend_number, x.intend_date, x.intend_from, s.store_name, x.intend_to, x.intend_items, x.intend_notes, x.intend_delstatus, x.intend_status
    FROM intends_tbl x 
    LEFT JOIN stores_tbl s ON s.store_id = x.intend_from 
    WHERE x.intend_id = intendid;
    
    SELECT y.intdet_id, y.intdet_product, p.product_name, y.intdet_item, fnGetProductFromPack(y.intdet_item, 0) AS orditem, y.intdet_quantity, y.intdet_stock, y.intdet_hsn, y.intdet_status, y.intdet_allotted, y.intdet_delivered 
    FROM intend_details y 
    LEFT JOIN products_tbl p ON p.product_id = y.intdet_product
    WHERE y.intdet_id = intendid;
END$$

CREATE  PROCEDURE `editVendorSupply` (IN `vensupid` INT)   BEGIN

	SELECT x.vendsup_id, x.vendsup_product, p.product_name, p.product_display, x.vendsup_packing, k.prodpack_package, q.packing_type, k.prodpack_quantity, k.prodpack_unit, m.measunit_shortname, x.vendsup_price, x.vendsup_type, x.vendsup_vendor, x.vendsup_minqty, x.vendsup_maxqty, x.vendsup_eoq, x.vendsup_deliver, x.vendsup_notes, x.vendsup_status 
    FROM vendor_supplies x 
    LEFT JOIN products_tbl p ON p.product_id = x.vendsup_product 
    LEFT JOIN product_packing k ON k.prodpack_id = x.vendsup_packing 
    LEFT JOIN packing_tbl q ON q.packing_id = k.prodpack_package 
    LEFT JOIN measure_units m ON m.measunit_id = k.prodpack_unit 
    WHERE x.vendsup_id = vensupid;
/*    
    SELECT z.packing_id, z.packing_type 
    FROM packing_tbl z WHERE z.packing_status = 1;
*/

END$$

CREATE  PROCEDURE `EntryDataTest` (IN `prodid` INT)   BEGIN


	DECLARE genrc, mcat, scat, cat, mdclass, sdclass, dclass INT DEFAULT 0;
 
   SELECT  x.product_manufacturer INTO @brand
    FROM products_entry_tbl x LEFT JOIN pharmacologicalcontent_tbl p ON p.pharma_id = x.product_pcontent
 WHERE x.product_id = prodid;
    
   
	SELECT x.product_id, x.product_name, x.product_display, x.product_generic, x.product_maincategory, x.product_subcategory, x.product_category, x.product_manufacturer, x.product_brand, x.product_drugmainclass, x.product_drugsubclass, x.product_drugclass, x.product_classified, x.product_prescrption, x.product_highlights, x.product_information, x.product_working, x.product_howto, x.product_benefits, x.product_specifications, x.product_features, x.product_usage, x.product_precautions, x.product_warnings, x.product_sideffects, x.product_antidot, x.product_interactions, x.product_publish, x.product_sale, x.product_online, x.product_featured, x.product_popular, x.product_taxgroup, x.product_status,x.product_schedule, x.product_approve, x.product_pcontent, p.pharma_name AS pharmaname
    FROM products_entry_tbl x LEFT JOIN pharmacologicalcontent_tbl p ON p.pharma_id = x.product_pcontent
 WHERE x.product_id = prodid;
    
 SELECT p.prodingred_product, p.prodingred_ingredient, p.prodingred_quantity, p.prodingred_unit, p.prodingred_status, t.ingred_name, m.measunit_name, m.measunit_shortname 
    FROM product_ingredients p 
    LEFT JOIN ingredients_tbl t on t.ingred_id=p.prodingred_ingredient
    LEFT JOIN measure_units m ON m.measunit_id = p.prodingred_unit 
    WHERE p.prodingred_product = prodid ;
   
   SELECT k.prodpack_id, k.prodpack_product, k.prodpack_package, k.prodpack_quantity, k.prodpack_unit,p.packing_type , k.prodpack_status, b.measunit_name, b.measunit_shortname, k.prodpack_maxstock, k.prodpack_minstock, k.prodpack_roq, k.prodpack_hsn, b.measunit_id,k.prodpack_taxgroup  
    FROM product_packing k  
    LEFT JOIN packing_tbl p ON p.packing_id = k.prodpack_package 
    LEFT JOIN measure_units b ON b.measunit_id = k.prodpack_unit 
    WHERE k.prodpack_product = prodid;
    
    SELECT q.product_generic, q.product_maincategory, q.product_subcategory, q.product_category, q.product_drugmainclass, q.product_drugsubclass, q.product_drugclass INTO genrc, mcat, scat, cat, mdclass, sdclass, dclass 
    FROM products_entry_tbl q WHERE q.product_id = prodid;    
    
   
	
    /* Main categories */
    SELECT prodclass_id, prodclass_name, prodclass_serial,
    IF(prodclass_id = mcat, 1, 0) AS maincat, 
    IF(prodclass_id = scat, 1, 0) AS subcat, 
    IF(prodclass_id = cat, 1, 0) AS cat, prodclass_parent
    FROM product_classes  
    WHERE prodclass_parent IN(0, mcat, scat, cat) AND prodclass_status = 1 
    
    ORDER BY prodclass_serial;
    
    /* Basic drug classes */
    SELECT drugclass_id, drugclass_name, 
    IF(mdclass = drugclass_id, 1, 0) AS mainclass, 
    IF(sdclass = drugclass_id, 1, 0) AS subclass, 
    IF(dclass = drugclass_id, 1, 0) AS drugclass
    FROM drug_classifications 
    WHERE drugclass_status = 1 AND drugclass_parent in(0, mdclass, sdclass, dclass) 
   
    ORDER BY drugclass_name;
    
    /* All Brands  */
     
    SELECT * FROM (SELECT brand_id, brand_name, brndmanu_id as brand_owner
    FROM brands_tbl b JOIN brand_manufacturer_tbl m ON b.brand_id=m.brnd_id  WHERE b.brand_status = 1 and m.brndmanu_id=@brand UNION SELECT 0, 0, 0 ) AS x ORDER BY x.brand_name;

    /* All Manufacturors  */
  
    SELECT 
    m.manuf_id, 
    m.manuf_name, 
    GROUP_CONCAT(b.brnd_id SEPARATOR ',') AS brands
FROM manufacturers_tbl m
LEFT JOIN brand_manufacturer_tbl b 
    ON b.brndmanu_id = m.manuf_id AND b.brndmanu_id=@brand
WHERE m.manuf_status = 1 and m.manuf_id=@brand
GROUP BY m.manuf_id, m.manuf_name

UNION ALL

SELECT 0, 'Select Manufacturer', '0'

ORDER BY manuf_name;

   
    /* Ingredients */
  
    SELECT ingredtype_id, ingredtype_type 
    FROM ingredient_types WHERE ingredtype_status = 1 
   
    ORDER BY ingredtype_type;

	/* Packaging types */
    SELECT packing_id, packing_type 
    FROM packing_tbl WHERE packing_status = 1;
    
    /* Measuring units */
    SELECT measunit_id, measunit_name, measunit_shortname 
    FROM measure_units WHERE measunit_status = 1;
    
    /* GST Tax rates */
    SELECT tax_id, tax_group, tax_rate 
    FROM tax_groups WHERE tax_status = 1;
    
    SELECT sch_id, sch_name, sch_code FROM schedule_tbl WHERE sch_status=1;
    /* faq 
   
    SELECT f.faq_id, f.faq_question, f.faq_answer, f.faq_status 
    FROM faq_table f WHERE f.faq_type = 3 AND f.faq_item = prodid ;
   */
   SELECT null;
    /* Suppliers handling the product */
    SELECT DISTINCT supplier, supname, suptype
FROM (
    SELECT stockistprod_stockist AS supplier, stockist_name AS supname, 1 AS suptype
    FROM stockist_products 
    LEFT JOIN stockists_tbl 
        ON stockist_id = stockistprod_stockist 
    WHERE stockistprod_product = prodid 
      AND stockistprod_status = 1

    UNION ALL

    SELECT distriprod_distributor, distri_name, 2
    FROM distributor_products 
    LEFT JOIN distributors_tbl 
        ON distri_id = distriprod_distributor 
    WHERE distriprod_product = prodid 
      AND distriprod_status = 1

    UNION ALL

    SELECT dealerprod_dealer, dealer_name, 3
    FROM dealer_products  
    LEFT JOIN dealers_tbl 
        ON dealer_id = dealerprod_dealer
    WHERE dealerprod_product = prodid 
      AND dealerprod_status = 1
) AS t;
   /*SELECT stockistprod_stockist AS supplier, stockist_name AS supname, 1 as suptype 
    FROM stockist_products  
    LEFT JOIN stockists_tbl ON stockist_id = stockistprod_stockist 
    WHERE stockistprod_product = prodid AND stockistprod_status = 1
    UNION
    SELECT distriprod_distributor AS supplier, distri_name AS supname, 2 as suptype 
    FROM distributor_products 
    LEFT JOIN distributors_tbl ON distri_id = distriprod_distributor 
    WHERE distriprod_product = prodid AND distriprod_status = 1
    UNION
    SELECT dealerprod_dealer AS supplier, dealer_name AS supname, 3 AS suptype
    FROM dealer_products  
    LEFT JOIN dealers_tbl ON dealer_id = dealerprod_dealer
    WHERE dealerprod_product = prodid AND dealerprod_status = 1;*/ 
    
    
    
   
     
END$$

CREATE  PROCEDURE `exportproducts` ()   begin
/*INSERT INTO `dummyproducts_tbl`( `product_name`, `product_display`,`product_manufacturer`,`product_brand`,`product_generic`,`product_highlights`,`product_information`,`product_benefits`,`product_usage`,`product_precautions`,`product_specifications`,`product_features`,`product_warnings`,`product_antidot`,`product_howto`,`product_working`,`product_maincategory`,`product_crtdby`) SELECT a.PRODUCT_NAME,a.KNOWN_AS,d.manuf_id,b.brand_id,gm.genmed_id,a.HIGLIGHTS,a.INFORMATION,a.BENEFITS,a.USAGES,a.PRECAUTIONS,a.SPECIFICATIONS,a.FEATURES,a.WARNINGS,a.ANTIDOTE,a.HOW_TO_USE,a.WORKING,c.prodclass_id,16 from productnew_tbl a INNER JOIN dummymanufacturers_tbl d on d.manuf_name=a.MANUFACTURER INNER JOIN dummybrands_tbl b on b.brand_name=a.BRAND INNER JOIN dummygeneric_medicines gm ON gm.genmed_name=a.GENERIC_NAME INNER JOIN dummyproductclass c on c.prodclass_name=a.CATEGORY ;*/
INSERT INTO `dummyproducts_tbl`( `product_name`, `product_display`,`product_manufacturer`,`product_brand`,`product_generic`,`product_highlights`,`product_information`,`product_benefits`,`product_usage`,`product_precautions`,`product_specifications`,`product_features`,`product_warnings`,`product_antidot`,`product_howto`,`product_working`,`product_maincategory`,`product_drugmainclass`,`product_drugsubclass`,`product_drugclass`,`product_crtdby`) SELECT a.PRODUCT_NAME,a.KNOWN_AS,d.manuf_id,b.brand_id,gm.genmed_id,a.HIGLIGHTS,a.INFORMATION,a.BENEFITS,a.USAGES,a.PRECAUTIONS,a.SPECIFICATIONS,a.FEATURES,a.WARNINGS,a.ANTIDOTE,a.HOW_TO_USE,a.WORKING,c.prodclass_id,(CASE WHEN v.drugclass_parent=0 THEN v.drugclass_id ELSE v.drugclass_parent END) as parent,(CASE WHEN v.drugclass_parent=0 THEN 0 ELSE v.drugclass_id END) as subid,(CASE WHEN v.drugclass_parent=0 THEN 0 ELSE (SELECT c.drugclass_id from dummydrugclassification c WHERE c.drugclass_parent=subid limit 1) END) as drugid,16 from productnew_tbl a LEFT JOIN dummymanufacturers_tbl d on d.manuf_name=a.MANUFACTURER LEFT JOIN dummybrands_tbl b on b.brand_name=a.BRAND LEFT JOIN dummygeneric_medicines gm ON gm.genmed_name=a.GENERIC_NAME LEFT JOIN dummyproductclass c on c.prodclass_name=a.CATEGORY INNER JOIN dummydrugclassification v on a.CLASSIFIED=v.drugclass_name;

END$$

CREATE  PROCEDURE `export_dummyproduct_ingredients` ()   BEGIN
INSERT INTO `dummyproduct_ingredients`( `prodingred_product`,`prodingred_ingredient`,`prodingred_crtdby`)
 SELECT a.product_id,d.ingred_id,16 FROM dummyproducts_tbl a INNER JOIN productnew_tbl p ON a.product_name=p.PRODUCT_NAME INNER JOIN dummyingredients d ON p.INGREDIENTS=d.ingred_name;
END$$

CREATE  PROCEDURE `fecthcartforguest` (IN `phone` VARCHAR(200))   BEGIN
DECLARE counts,cartcount int;
SELECT COUNT(*) into counts FROM customers_tbl c WHERE c.customer_phone=phone and c.customer_type=0;
IF(counts=1)THEN
SELECT count(*) into cartcount FROM user_cart u  join customers_tbl c on c.customer_id=u.user_id  WHERE c.customer_phone = phone and c.customer_type=0;
IF (cartcount>0)THEN
SELECT 1 as cart;
SELECT u.product_id,u.prodpack_id,u.batch_id , u.quantity FROM user_cart u  join customers_tbl c on c.customer_id=u.user_id  WHERE c.customer_phone = phone and c.customer_type=0;
ELSE
SELECT 0 as cart;
END IF;
ELSE
SELECT 0 as cart;
END IF;
END$$

CREATE  PROCEDURE `fetchCustomerOrderDetailsbyOrderID` (IN `orderid` INT)   BEGIN

SELECT o.order_id,o.order_customer,o.order_orderid,DATE( o.order_date) AS dates,o.order_trackid ,o.order_status,o.order_razorpayid,o.order_subtotal,p.paymt_paid,p.paymt_paidon,p.paymt_transid  FROM orders_tbl o JOIN payments_tbl p ON p.paymt_orderid=o.order_id
WHERE o.order_id=orderid AND p.paymt_status=1;


END$$

CREATE  PROCEDURE `fetchCustomerOrderDetailsbyOrderIDForRefund` (IN `orderid` INT)   BEGIN

SELECT o.order_id,o.order_customer,o.order_orderid,DATE( o.order_date) AS dates,o.order_trackid ,o.order_status,o.order_razorpayid,o.order_subtotal,p.paymt_paid,p.paymt_paidon,p.paymt_transid  FROM orders_tbl o JOIN payments_tbl p ON p.paymt_orderid=o.order_id
WHERE o.order_status=2 AND o.order_id=orderid AND p.paymt_status=1;


END$$

CREATE  PROCEDURE `fetchDataForGDN` (IN `packids` TEXT)   BEGIN
    DECLARE front, TempValue, alltracks, packets TEXT DEFAULT NULL;
   	DECLARE frontlen INT DEFAULT NULL;
    	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 tt.transpack_gdn, t.transferpack_item,fnGetProductFromPack(t.transferpack_item, 0) AS item ,s.stockin_batch,s.stockin_mrp, DATE_FORMAT(tt.transpack_collecton, '%d-%m-%Y') AS gdn_date,  t.transferpack_orditem,t.transferpack_qty ,DATE_FORMAT(s.stockin_expiry, '%d-%m-%Y') AS expiry,i.invdet_hsn,i.invdet_mrp,i.invdet_ptr,i.invdet_expiry,i.invdet_schdisc,i.invdet_cstpc,i.invdet_sstpc,st.store_id,st.store_code,st.store_name FROM transferpack_items t
                JOIN transfer_packets tt ON tt.transpack_id=t.transferpack_packet
                JOIN storestock_pricing p on p.strstk_id=t.transferpack_orditem
                JOIN stock_inwards s ON s.stockin_id=p.strstk_refer
                JOIN invoice_details i ON i.invdet_id=s.stockin_invref
                JOIN stores_tbl st ON st.store_id=tt.transpack_from
                WHERE tt.transpack_id=TempValue;
                SET packids = INSERT(packids, 1, frontlen + 1, '');
                #SET alltracks = CONCAT(alltracks, ',', trackid);
			END LOOP;
END$$

CREATE  PROCEDURE `fetchDataForGrnReceipts` (IN `packid` INT, IN `flag` INT)   BEGIN
IF flag =1 THEN
SELECT t.transpack_id,t.transpack_grn,t.transpack_packid,DATE_FORMAT(t.transpack_receiveon, '%d-%m-%Y') AS grn_date, s.store_name,s.store_code,fnGetProductFromPack(ti.transferpack_item, 0) AS item,p.prodpack_quantity,m.measunit_shortname,i.invdet_mrp,i.invdet_ptr,ss.stockin_batch,DATE_FORMAT(ss.stockin_expiry, '%d-%m-%Y') AS expiry,ti.transferpack_qty
 FROM transfer_packets t
JOIN stores_tbl s ON s.store_id=t.transpack_to
JOIN transferpack_items ti ON ti.transferpack_packet=t.transpack_id
JOIN product_packing p ON p.prodpack_id=ti.transferpack_item
JOIN measure_units m ON m.measunit_id=p.prodpack_unit
JOIN storestock_pricing sp ON sp.strstk_id=ti.transferpack_orditem
JOIN stock_inwards ss ON ss.stockin_id=sp.strstk_refer
JOIN invoice_details i ON i.invdet_id=ss.stockin_invref
WHERE t.transpack_id=packid AND t.transpack_status=10;
END IF;
END$$

CREATE  PROCEDURE `fetchDeliveryAddress` (IN `user_id` INT)   BEGIN
SELECT 
a.delivery_id,a.delivery_to,a.delivery_pin,a.delivery_phone,a.delivery_email,a.delivery_house,a.delivery_street,a.delivery_landmark,a.delivery_city,a.delivery_state,a.delivery_type,a.delivery_status FROM delivery_address a WHERE a.delivery_user=user_id and a.delivery_active=1;
END$$

CREATE  PROCEDURE `Fetchdoc` ()   BEGIN
SELECT `doctor_id`, `doctor_name`,`doctor_crtdby` FROM `doctors_tbl` ORDER BY doctor_id DESC LIMIT 1;
END$$

CREATE  PROCEDURE `FetchnamebyCheckid` (IN `checkid` INT)   BEGIN
SELECT u.user_staffname, u.user_checkid FROM users_tbl u WHERE u.user_checkid=checkid;
/*SELECT u.user_staffname, u.user_checkid FROM users_tbl u WHERE u.user_staffid=checkid;*/
END$$

CREATE  PROCEDURE `fetchproductlistForPacking` (IN `proid` INT)   BEGIN

SELECT p.product_display ,m.measunit_name,m.measunit_shortname, pk.packing_type ,pp.prodpack_quantity ,st.stockin_expiry,sp.strstk_msp,sp.strstk_discount,sp.strstk_mrp from products_tbl p
 JOIN product_packing pp ON pp.prodpack_product=p.product_id
 JOIN packing_tbl pk ON pk.packing_id=pp.prodpack_package
 JOIN measure_units m ON m.measunit_id=pp.prodpack_unit
 JOIN stock_inwards st ON st.stockin_item=pp.prodpack_id
 JOIN storestock_pricing sp on sp.strstk_refer=st.stockin_id
WHERE p.product_id=proid
AND sp.strstk_product = p.product_id
      AND sp.strstk_item = st.stockin_item
      AND sp.strstk_product = proid
      AND p.product_status = 1
      AND m.measunit_status = 1
      AND p.product_online = 1
      AND p.product_publish = 1
      AND pp.prodpack_status = 1
      AND pk.packing_status = 1
      AND st.stockin_expiry >= CURRENT_DATE() ;

END$$

CREATE  PROCEDURE `fetchPurchaseReturnBillData` (IN `billno` INT)   BEGIN
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,
(SELECT GROUP_CONCAT(f.crd_returnurl SEPARATOR ',') FROM purchasereturnfiles_tbl f
      WHERE f.crd_returnbillid = billno) AS fileurls  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,s.store_code,s.store_name,i.invoice_id,i.invoice_number
,ii.invdet_schdisc,(ii.invdet_cstpc+ii.invdet_sstpc)AS totaltax,ii.invdet_discpc,ii.invdet_mrp,ii.invdet_ptr, i.invoice_dated   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 
LEFT JOIN invoice_details ii ON ii.invdet_invoice=i.invoice_id and ii.invdet_item = pp.return_item 
WHERE pp.return_billnum=billno group by pp.returnitem_batch;

END$$

CREATE  PROCEDURE `fileUploadForCreditNote` (IN `retrn_ids` INT, IN `crdurl` VARCHAR(100), IN `adminid` INT)   BEGIN
	INSERT INTO  purchasereturnfiles_tbl( crd_returnbillid,crd_returnurl,crd_crtby )
    VALUES( retrn_ids, crdurl, adminid);
END$$

CREATE  PROCEDURE `fnCreateTransferOrderf` (IN `storefrom` INT, IN `storeto` INT, IN `strorder` TEXT, IN `adminid` 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;
                SELECT 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;
                */
            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;*/
    SELECT ordid;

END$$

CREATE  PROCEDURE `fnCreateTransferOrderTest` (IN `storefrom` INT, IN `storeto` INT, IN `strorder` TEXT, IN `adminid` 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;

        -- Cursor block
        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;
                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;

            CLOSE stcurs;

        END BLOCK2;

    END WHILE;

    -- Final output
    IF TRIM(strtrans) <> '' THEN
        SELECT strtrans;
    END IF;

END$$

CREATE  PROCEDURE `gdnReportByStores` (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 sd.transpack_id,sd.transpack_gdn,DATE_FORMAT(sd.transpack_collecton,'%d-%m-%Y')AS gdndate,fnGetProductFromPack(s.transferpack_item, 0) AS item ,sw.stockin_batch,sw.stockin_expiry,s.transferpack_qty,st.store_code,st.store_name ,sw.stockin_store,sw.stockin_item,sw.stockin_invref ,iv.invdet_hsn,iv.invdet_cstpc,iv.invdet_sstpc,iv.invdet_mrp,iv.invdet_ptr,iv.invdet_batch ,iv.invdet_expiry,u.user_staffname,m.manuf_code,m.manuf_name FROM transfer_packets sd
LEFT JOIN transferpack_items s ON s.transferpack_packet=sd.transpack_id
LEFT JOIN storestock_pricing sp ON sp.strstk_id=s.transferpack_orditem
LEFT JOIN stock_inwards sw ON sw.stockin_id=sp.strstk_refer
LEFT JOIN invoice_details iv ON iv.invdet_id=sw.stockin_invref
LEFT JOIN users_tbl u ON u.user_id=sd.transpack_crtdby
LEFT JOIN products_tbl p ON p.product_id=sp.strstk_product
LEFT JOIN manufacturers_tbl m ON m.manuf_id=p.product_manufacturer
LEFT JOIN stores_tbl st ON st.store_id=sd.transpack_from WHERE sd.transpack_from=storeid and Date(sd.transpack_collecton) BETWEEN fdate AND todate;
END IF;
END IF ;
END$$

CREATE  PROCEDURE `generateInt` (IN `jsorder` JSON, IN `adminid` INT)   BEGIN
	DECLARE i,checkid INT DEFAULT 0;
    DECLARE bDone, oid, ointend, oitem, osource, otarget, olicense, oquantity INT DEFAULT 0;
    DECLARE fromstore, tostore, cntr, numrecs, neworder, orderqty, retorder INT DEFAULT 0;
    DECLARE strOrder, stroids TEXT DEFAULT '';
    DECLARE curs CURSOR FOR SELECT id, intend, item, sourced, target, license, quantity
    	FROM temp_intendorders ORDER BY sourced, target;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
    DROP TEMPORARY TABLE IF EXISTS temp_intendorders;
    SELECT user_id INTO checkid FROM users_tbl WHERE user_checkid=adminid ;
	CREATE TEMPORARY TABLE IF NOT EXISTS temp_intendorders AS (SELECT * FROM tempintendorder);
    WHILE i < json_length(jsorder) DO
  /* SELECT JSON_VALUE(jsorder, CONCAT('$[', i, '].id')) c1;*/
		INSERT INTO `temp_intendorders`(id, intend, item, method, sourced, sourcetype, target, license, quantity, adminid)
   			SELECT JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[', i, '].id'))), JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].intend'))), JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].item'))), 1, JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].source'))), 1, JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].target'))), st.store_license, JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].quantity'))), checkid
    			FROM stores_tbl st WHERE st.store_id = JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[', i, '].target')));
       SET i = i + 1;
    END WHILE;
	#SELECT * FROM temp_intendorders;
    OPEN curs;
    	SELECT FOUND_ROWS() INTO numrecs;
    	takeorder:LOOP
        	FETCH curs INTO oid, ointend, oitem, osource, otarget, olicense, oquantity;
        	IF bDone = 1 THEN
            	LEAVE takeorder;
            END IF;
            IF (osource <> fromstore) OR (otarget <> tostore) THEN
            	IF strOrder <> '' THEN
                	SET retorder = fnCreateTransferOrder(fromstore, tostore, strOrder, adminid);
                    #SELECT retorder;
                    IF retorder > 0 THEN
                    	CALL updateTempIntendOrders(retorder, stroids);
                    END IF;
                    SET stroids = '';
                    SET strOrder = '';
                END IF;
                SET strOrder =  CONCAT(oitem, '|', oquantity);
                SET stroids = oid;
                SET fromstore = osource;
                SET tostore = otarget;
            ELSE
            	SET strOrder = CONCAT(strOrder, '##', oitem, '|', oquantity);
            	SET stroids = CONCAT(stroids, ',', oid);
            END IF;
            SET cntr = cntr + 1;
           	IF cntr = numrecs THEN
           		#update intends table
                IF strOrder <> '' THEN
                    SET retorder = fnCreateTransferOrder(fromstore, tostore, strOrder, adminid);
                    #SELECT retorder;
                    IF retorder > 0 THEN
                    	CALL updateTempIntendOrders(retorder, stroids);
                    END IF;
                    SET stroids = '';
                    SET strOrder = '';
                END IF;
            END IF;
        END LOOP takeorder;
    CLOSE curs;
    #SELECT * FROM temp_intendorders;
    UPDBLOCK:BEGIN
    	DECLARE done, cid, cintd, citem, cref, cqty INT DEFAULT 0;
    	DECLARE intends CURSOR FOR SELECT id, intend, item, ordrefer, quantity FROM temp_intendorders;
    	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
        #SELECT * FROM temp_intendorders;
   		OPEN intends;
        	getRecords: LOOP
            	FETCH intends INTO cid, cintd, citem, cref, cqty;
                #SELECT cid, cintd, citem, cref, cqty;
            	IF done = 1 THEN
            		LEAVE getRecords;
            	END IF;
                IF cref > 0 AND cqty > 0 THEN
                	UPDATE intend_allocation_items
                	SET intdallocit_ordrqty = cqty, intdallocit_ordrefer = cref, intdallocit_ordstatus = 1, intdallocit_status = 5
                	WHERE intdallocit_id = cid;
                    IF( SELECT COUNT(*) FROM intend_allocation_items x
                       WHERE x.intdallocit_intend = cintd AND x.intdallocit_status =1 ) = 0 THEN
                    		UPDATE intend_allocations SET intdalloc_status = 5, intdalloc_updby =checkid
                    		WHERE intdalloc_intend = cintd;
                   	END IF;
            	END IF;
            END LOOP getRecords;
        CLOSE intends;
        #SET done=0;
    END UPDBLOCK;
   
	DROP TEMPORARY TABLE IF EXISTS temp_intendorders;
 	
END$$

CREATE  PROCEDURE `generateIntendPurchaseOrders` (IN `jsorder` JSON, IN `adminid` INT)   BEGIN 
DECLARE i , checkid INT DEFAULT 0;
    DECLARE oprice FLOAT DEFAULT 0;
    DECLARE bDone, oid, ointend, oitem, osource, osourcetype, otarget, olicense, oquantity ,oordmode INT DEFAULT 0;
    DECLARE supplier, tostore,suppliertype, ordermode, cntr, numrecs, neworder, orderqty, retorder  INT DEFAULT 0;
    DECLARE strOrder, stroids TEXT DEFAULT '';
    DECLARE curs CURSOR FOR SELECT id, intend, item, sourced,sourcetype, target, license, quantity,price,ordmode
    	FROM temp_intendorderss ORDER BY sourced,sourcetype, target,ordmode;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
     SELECT user_id INTO checkid FROM users_tbl WHERE user_checkid=adminid ;
    DROP TEMPORARY TABLE IF EXISTS temp_intendorderss;
    
	CREATE TEMPORARY TABLE IF NOT EXISTS temp_intendorderss AS (SELECT * FROM tempintendorder);
      WHILE i < json_length(jsorder) DO 
		INSERT INTO temp_intendorderss(id, intend, item, method, sourced, sourcetype, target, license, quantity,price,ordmode, adminid)
   			SELECT JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].id'))),
            JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].intend'))),
            JSON_UNQUOTE( JSON_EXTRACT(jsorder, CONCAT('$[',i,'].item'))),
            2,
            JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].source'))),
            JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].sourcetype'))),
            JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].target'))),
            13, 
            JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].quantity'))),
            JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].price'))),
            JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].ordmode'))),
            checkid 
    			FROM stores_tbl st WHERE st.store_id =JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[', i, '].target')));
		SET i = i + 1;
    END WHILE;
    #SELECT * FROM temp_intendorderss;
  
     OPEN curs;
   	SELECT FOUND_ROWS() INTO numrecs;
    	takeorder:LOOP
        	FETCH curs INTO oid, ointend, oitem, osource,osourcetype, otarget, olicense, oquantity,oprice,oordmode;
        	IF bDone = 1 THEN
            	LEAVE takeorder;
            END IF;
            IF (osource <> supplier) OR (otarget <> tostore) OR(osourcetype<>suppliertype) OR (oordmode<>ordermode) THEN
            #SELECT strOrder;
            	IF (strOrder != "") THEN        
                #SELECT supplier,suppliertype, tostore,oordmode;
                  SET retorder = fnCreatePurchaseOrder(supplier,suppliertype, tostore, strOrder,ordermode, adminid); 
                  #SELECT retorder;
                  IF retorder > 0 THEN
                  		CALL updateTempIntendPurchaseOrders(retorder, stroids);
                    END IF;                         
                  SET stroids = '';
                  SET strOrder = '';
                END IF;
                	SET strOrder =  CONCAT(oitem, '|', oquantity,'|',oprice);
                	SET stroids = oid;
                	SET supplier = osource;
                    SET suppliertype=osourcetype;
                	SET tostore = otarget;     
                    SET ordermode=oordmode;
                ELSE
            		SET strOrder = CONCAT(strorder, '##', oitem, '|', oquantity, '|',oprice); 
            		SET stroids = CONCAT(stroids, ',', oid);
            END IF;  
                  
             SET cntr = cntr + 1;
              IF cntr = numrecs THEN
                IF strOrder <> '' THEN
                #SELECT supplier,suppliertype, tostore,oordmode;
                  SET retorder =fnCreatePurchaseOrder(supplier,suppliertype, tostore, strOrder,ordermode, adminid);
            /*SELECT retorder,stroids;
            SELECT * FROM temp_intendorderss;*/
                   IF retorder > 0 THEN
                    	CALL updateTempIntendPurchaseOrders(retorder, stroids);  
                    END IF;
                    SET stroids = '';
                    SET strOrder = '';
                END IF;
            END IF;
        END LOOP takeorder;
    CLOSE curs;
    
    UPDBLOCK:BEGIN   
    	DECLARE done, cid, cintd, citem, cref, cqty , odmode INT DEFAULT 0;
    	DECLARE intends CURSOR FOR SELECT id, intend, item, ordrefer, quantity ,ordmode FROM temp_intendorderss;
    	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
   		OPEN intends;
        	getRecords: LOOP
            	FETCH intends INTO cid, cintd, citem, cref, cqty ,odmode;
	#SELECT cid, cintd, citem, cref, cqty ,odmode;
            	IF done = 1 THEN
            		LEAVE getRecords;
            	END IF;
                IF cref > 0 AND cqty > 0 THEN
                	UPDATE intend_allocation_items 
                	SET intdallocit_ordrqty = cqty, intdallocit_ordrefer = cref,intdallocit_ordrmode=odmode, intdallocit_ordstatus = 1, intdallocit_status = 5
                	WHERE intdallocit_id = cid;
                    IF( SELECT COUNT(*) FROM intend_allocation_items x 
                       WHERE x.intdallocit_intend = cintd AND x.intdallocit_status =1 ) = 0 THEN
                    		UPDATE intend_allocations SET intdalloc_status = 5, intdalloc_updby = checkid 
                    		WHERE intdalloc_intend = cintd;
                   	END IF;
            	END IF;
            END LOOP getRecords;
        CLOSE intends;
    END UPDBLOCK;

     DROP TEMPORARY TABLE IF EXISTS temp_intendorderss;
    
  END$$

CREATE  PROCEDURE `generateIntendTransferOrder` (IN `jsorder` JSON, IN `adminid` INT)   BEGIN
	DECLARE i,checkid INT DEFAULT 0;
    DECLARE olicense VARCHAR(50);
    DECLARE bDone, oid, ointend, oitem, osource, otarget,  oquantity INT DEFAULT 0;
    DECLARE fromstore, tostore, cntr, numrecs, neworder, orderqty, retorder INT DEFAULT 0;
    DECLARE strOrder, stroids TEXT DEFAULT '';
    DECLARE curs CURSOR FOR SELECT id, intend, item, sourced, target, license, quantity
    	FROM temp_intendorders ORDER BY sourced, target;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
    DROP TEMPORARY TABLE IF EXISTS temp_intendorders;
    SELECT user_id INTO checkid FROM users_tbl WHERE user_checkid=adminid ;
	CREATE TEMPORARY TABLE IF NOT EXISTS temp_intendorders AS (SELECT * FROM tempintendorder);
    WHILE i < json_length(jsorder) DO
  /* SELECT JSON_VALUE(jsorder, CONCAT('$[', i, '].id')) c1;*/
		INSERT INTO `temp_intendorders`(id, intend, item, method, sourced, sourcetype, target, license, quantity, adminid)
   			SELECT JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[', i, '].id'))), JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].intend'))), JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].item'))), 1, JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].source'))), 1, JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].target'))), st.store_license, JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].quantity'))), checkid
    			FROM stores_tbl st WHERE st.store_id = JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[', i, '].target')));
       SET i = i + 1;
    END WHILE;
	#SELECT * FROM temp_intendorders;
    OPEN curs;
    	SELECT FOUND_ROWS() INTO numrecs;
    	takeorder:LOOP
        	FETCH curs INTO oid, ointend, oitem, osource, otarget, olicense, oquantity;
        	IF bDone = 1 THEN
            	LEAVE takeorder;
            END IF;
            IF (osource <> fromstore) OR (otarget <> tostore) THEN
            	IF strOrder <> '' THEN
                	SET retorder = fnCreateTransferOrder(fromstore, tostore, strOrder, adminid);
                    #SELECT retorder;
                    IF retorder > 0 THEN
                    	CALL updateTempIntendOrders(retorder, stroids);
                    END IF;
                    SET stroids = '';
                    SET strOrder = '';
                END IF;
                SET strOrder =  CONCAT(oitem, '|', oquantity);
                SET stroids = oid;
                SET fromstore = osource;
                SET tostore = otarget;
            ELSE
            	SET strOrder = CONCAT(strOrder, '##', oitem, '|', oquantity);
            	SET stroids = CONCAT(stroids, ',', oid);
            END IF;
            SET cntr = cntr + 1;
           	IF cntr = numrecs THEN
           		#update intends table
                IF strOrder <> '' THEN
                    SET retorder = fnCreateTransferOrder(fromstore, tostore, strOrder, adminid);
                    #SELECT retorder;
                    IF retorder > 0 THEN
                    	CALL updateTempIntendOrders(retorder, stroids);
                    END IF;
                    SET stroids = '';
                    SET strOrder = '';
                END IF;
            END IF;
        END LOOP takeorder;
    CLOSE curs;
    #SELECT * FROM temp_intendorders;
    UPDBLOCK:BEGIN
    	DECLARE done, cid, cintd, citem, cref, cqty INT DEFAULT 0;
    	DECLARE intends CURSOR FOR SELECT id, intend, item, ordrefer, quantity FROM temp_intendorders;
    	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
        #SELECT * FROM temp_intendorders;
   		OPEN intends;
        	getRecords: LOOP
            	FETCH intends INTO cid, cintd, citem, cref, cqty;
                #SELECT cid, cintd, citem, cref, cqty;
            	IF done = 1 THEN
            		LEAVE getRecords;
            	END IF;
                IF cref > 0 AND cqty > 0 THEN
                	UPDATE intend_allocation_items
                	SET intdallocit_ordrqty = cqty, intdallocit_ordrefer = cref, intdallocit_ordstatus = 1, intdallocit_status = 5
                	WHERE intdallocit_id = cid;
                    IF( SELECT COUNT(*) FROM intend_allocation_items x
                       WHERE x.intdallocit_intend = cintd AND x.intdallocit_status =1 ) = 0 THEN
                    		UPDATE intend_allocations SET intdalloc_status = 5, intdalloc_updby =checkid
                    		WHERE intdalloc_intend = cintd;
                   	END IF;
            	END IF;
            END LOOP getRecords;
        CLOSE intends;
        #SET done=0;
    END UPDBLOCK;
	DROP TEMPORARY TABLE IF EXISTS temp_intendorders;
 	
END$$

CREATE  PROCEDURE `generateRandomIntendno` (IN `storeid` INT)   BEGIN

        SELECT CONCAT('IN_', COALESCE((SELECT y.store_code FROM stores_tbl y WHERE y.store_id = storeid), ' '), '_', COALESCE(COUNT(*)+1, 1))	AS nextorder 
        FROM  intends_tbl x 
        WHERE x.intend_from = storeid; 
END$$

CREATE  PROCEDURE `gentest` (IN `jsorder` JSON)   BEGIN
	DECLARE i,checkid INT DEFAULT 0;
    DECLARE bDone, oid, ointend, oitem, osource, otarget, olicense, oquantity INT DEFAULT 0;
    DECLARE fromstore, tostore, cntr, numrecs, neworder, orderqty, retorder INT DEFAULT 0;
    DECLARE strOrder, stroids TEXT DEFAULT '';
    DECLARE curs CURSOR FOR SELECT id, intend, item, sourced, target, license, quantity
    	FROM temp_intendorders ORDER BY sourced, target;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
    DROP TEMPORARY TABLE IF EXISTS temp_intendorders;
	CREATE TEMPORARY TABLE IF NOT EXISTS temp_intendorders AS (SELECT * FROM tempintendorder);
    WHILE i < json_length(jsorder) DO
  /* SELECT JSON_VALUE(jsorder, CONCAT('$[', i, '].id')) c1;*/
		INSERT INTO `temp_intendorders`(id, intend, item, method, sourced, sourcetype, target, license, price,quantity, adminid)
   			SELECT JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[', i, '].id'))), JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].intend'))), JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].item'))), 1, JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].source'))), 1, JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].target'))), st.store_license,0, JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[',i,'].quantity'))), 1
    			FROM stores_tbl st WHERE st.store_id = JSON_UNQUOTE(JSON_EXTRACT(jsorder, CONCAT('$[', i, '].target')));
       SET i = i + 1;
    END WHILE;
SELECT * FROM temp_intendorders;
    
END$$

CREATE  PROCEDURE `getAllBatchItemsPerItem` (IN `itemid` INT)   BEGIN
SELECT s.strstk_id, s.strstk_item ,fnGetProductFromPack(s.strstk_item,0)as items,s.strstk_store,st.store_code,st.store_name,(s.strstk_stock-s.strstk_reserved) AS stock ,s.strstk_msp,s.strstk_discount ,si.stockin_batch,si.stockin_expiry FROM storestock_pricing s
JOIN stores_tbl st ON st.store_id=s.strstk_store
JOIN stock_inwards si ON si.stockin_id=s.strstk_refer
WHERE s.strstk_item=itemid;
END$$

CREATE  PROCEDURE `getAllHelpDeskData` ()   BEGIN

SELECT t.help_id,t.help_icon,t.help_title,t.help_caption FROM tbl_help_desk t ;

SELECT reason_id ,reason_help_id,reason_issue,reason_help  FROM tbl_help_desk_reason WHERE reason_status=1;


END$$

CREATE  PROCEDURE `getAllHomedeliveryData` ()   BEGIN


SELECT h.bill_id,h.bill_no,h.store_id,s.store_code,s.store_name,h.customer_name,h.customer_mob,h.items,h.amount,h.payment_status,h.status FROM homedelivery_tbl h JOIN stores_tbl s on s.store_id=h.store_id ;
END$$

CREATE  PROCEDURE `getAllItemStockForBilling` (IN `storeid` INT, IN `itemid` VARCHAR(200), IN `freeItem` INT)   BEGIN
IF TRIM(itemid) <> '' THEN
    SELECT  CASE WHEN freeItem = x.strstk_item THEN 0 ELSE x.strstk_mrp END AS strstk_mrp,
    CASE WHEN freeItem = x.strstk_item THEN 0 ELSE x.strstk_msp END AS strstk_msp,
    CASE WHEN freeItem = x.strstk_item THEN 0 ELSE x.strstk_discount END AS strstk_discount, x.strstk_id, x.strstk_item, si.stockin_batch, si.stockin_expiry,
         x.strstk_cost, x.strstk_last,
        (x.strstk_stock - x.strstk_reserved) AS available, x.strstk_stack, x.strstk_dealofday AS deal,
        x.strstk_offer AS offer, p.prodpack_hsn, fnGetProductFromPack(x.strstk_item, 1) AS product,
        p.prodpack_roq, MAX(i.invdet_cstpc) AS invdet_cstpc, MAX(i.invdet_sstpc) AS invdet_sstpc,
        m.manuf_code, pt.sch_name AS psch, MAX(a.bill_stock) AS bill_stock, x.strstk_stock,
        p.prodpack_quantity, p.prodpack_unit, p.prodpack_package, t.packing_type, sb.storage_label, bb.billit_item
    FROM storestock_pricing x
    LEFT JOIN stock_inwards si ON si.stockin_id = x.strstk_refer
    LEFT JOIN product_packing p ON p.prodpack_id = x.strstk_item
    LEFT JOIN invoice_details i ON i.invdet_id = si.stockin_invref
    LEFT JOIN products_tbl pr ON pr.product_id = x.strstk_product
    LEFT JOIN manufacturers_tbl m ON pr.product_manufacturer = m.manuf_id
    LEFT JOIN schedule_tbl pt ON pr.product_schedule = pt.sch_id
    LEFT JOIN billstock_tbl a ON a.billstock_item = si.stockin_item
    LEFT JOIN packing_tbl t ON t.packing_id = p.prodpack_package
    LEFT JOIN storage_tbl sb ON sb.storage_id = si.stockin_stack
    LEFT JOIN bill_items bb ON bb.billit_item = x.strstk_item
    WHERE x.strstk_store = storeid
        AND FIND_IN_SET(x.strstk_item, itemid) > 0
    GROUP BY x.strstk_id, x.strstk_item, si.stockin_batch, si.stockin_expiry,
         x.strstk_mrp, x.strstk_msp, x.strstk_discount, x.strstk_cost, x.strstk_last,
         available, x.strstk_stack, deal, offer, p.prodpack_hsn, product, p.prodpack_roq,
         m.manuf_code, pt.sch_name, x.strstk_stock, p.prodpack_quantity, p.prodpack_unit,
         p.prodpack_package, t.packing_type, sb.storage_label;
END IF;
END$$

CREATE  PROCEDURE `getAllOnlinedeliveryData` ()   BEGIN
SELECT o.order_id,o.order_orderid,d.delivery_to,d.delivery_phone,CONCAT(d.delivery_house,',',d.delivery_street,',',d.delivery_landmark,',',d.delivery_city,',',d.delivery_state,'-',d.delivery_pin) AS address,o.orders_delivered,o.order_delivery,(SELECT COUNT(*) FROM order_details od WHERE od.ordet_order=o.order_id) as item_count, p.paymt_paid  FROM orders_tbl o  JOIN customers_tbl c on c.customer_id=o.order_customer JOIN delivery_address d on d.delivery_id=o.order_deliverId  JOIN payments_tbl p on p.paymt_orderid=o.order_id WHERE o.order_delivery=4;

END$$

CREATE  PROCEDURE `getAllPByproductparentclass` (IN `prodparentcls` INT)   begin
select x.product_id,x.product_name,x.product_display,x.product_featured,x.product_popular,x.prodclass_name,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,x.product_prescrption 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,c.prodclass_name,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,p.product_prescrption 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 e.strstk_refer = s.stockin_id join product_classes c on c.prodclass_id = p.product_maincategory
                                                                  
WHERE p.product_maincategory = prodparentcls 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$$

CREATE  PROCEDURE `getAllPendingDataPerDates` (IN `id` INT)   BEGIN
SELECT p.assigned_date,COUNT(p.assigned_for) AS total_count,COUNT(IF(p.product_entry_status = 1, 1, NULL)) AS completed_count
FROM products_entry_tbl p WHERE p.assigned_for =id GROUP BY p.assigned_date
HAVING total_count > completed_count ORDER BY p.assigned_date ASC;

END$$

CREATE  PROCEDURE `getAllPharmasistNames` ()   BEGIN
SELECT u.user_id,u.user_staffid,u.user_staffname,u.user_programid FROM users_tbl u  WHERE u.user_programid=64 AND u.user_status=1 ;

END$$

CREATE  PROCEDURE `getAllProductsByAllBrandId` (IN `brandid` VARCHAR(200), IN `offsets` INT, IN `limits` INT)   begin

SET @sql = CONCAT('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, x.strstk_id, x.strstk_discount 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, e.strstk_id,e.strstk_discount 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_brand IN (',brandid,') 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 LIMIT ',offsets,',',limits,'');

/*if type=0 THEN

SET @sql = CONCAT('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,x.strstk_discount,
 x.strstk_id,x.product_prescrption 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,k.packing_type,m.measunit_name,
m.measunit_shortname,e.strstk_mrp,e.strstk_msp,p.product_prescrption,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,e.strstk_discount, e.strstk_id
FROM products_tbl p

LEFT JOIN product_classes pp ON p.product_subcategory = pp.prodclass_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
 e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
 AND p.product_brand IN (',brandid,')
  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 pp.prodclass_id=',parentId,'
  AND (e.strstk_stock-e.strstk_reserved) > 0 order by e.strstk_offerfrom ASC, s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc 
  ) as x group by x.product_id');
ELSE
SET @sql = CONCAT('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.product_prescrption,
x.measunit_shortname,x.strstk_mrp,x.strstk_msp,x.stockin_batch,x.stockin_expiry,x.strstk_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_prescrption,p.product_display,p.product_featured,p.product_popular,r.prodpack_id,r.prodpack_quantity,r.prodpack_maxstock,r.prodpack_minstock,k.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,e.strstk_discount, e.strstk_id
FROM products_tbl p

LEFT JOIN product_classes pp ON p.product_category = pp.prodclass_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
 e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
 AND p.product_brand IN (',brandid,')
  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 pp.prodclass_id=',parentId,'
  AND (e.strstk_stock-e.strstk_reserved) > 0 order by e.strstk_offerfrom ASC, s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc 
  ) as x group by x.product_id');
END IF;
*/
 PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

/*select x.product_id, x.product_name, x.price_id, x.product_category, x.price_expiry from (SELECT ( @row_number := @row_number + 1) AS virtual_id, p.product_id,p.product_name, b.price_id,p.product_category,b.price_expiry FROM products_tbl p INNER JOIN product_pricing r on r.prodprice_product=p.product_id INNER JOIN prices_tbl b on b.price_pricingid=r.prodprice_id WHERE p.product_sale=1 and p.product_online=1 and p.product_status=1 and b.price_stock>0 and b.price_expiry >= CURDATE() AND p.product_name LIKE concat(product,'%') order by b.price_expiry ASC, b.price_priority ASC ) AS x GROUP BY x.product_id; */

END$$

CREATE  PROCEDURE `getAllProductsByAllBrandIdwithOffers` (IN `brandid` VARCHAR(200), IN `parentId` INT)   begin
DECLARE disc INT DEFAULT 0;
SELECT h.menu_discount INTO disc  from home_menu_offer h WHERE h.menu_category=parentId;

/*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_brand IN (brandid) 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;*/

SET @sql = CONCAT('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.product_prescrption,x.strstk_msp,x.stockin_batch,x.stockin_expiry,x.strstk_stock,x.strstk_stack, x.product_imageurl, x.strstk_id, x.strstk_discount 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,p.product_prescrption,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, e.strstk_id,e.strstk_discount 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_brand IN (',brandid,') 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 and e.strstk_discount<=',disc,' and e.strstk_discount!=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');

 PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

/*select x.product_id, x.product_name, x.price_id, x.product_category, x.price_expiry from (SELECT ( @row_number := @row_number + 1) AS virtual_id, p.product_id,p.product_name, b.price_id,p.product_category,b.price_expiry FROM products_tbl p INNER JOIN product_pricing r on r.prodprice_product=p.product_id INNER JOIN prices_tbl b on b.price_pricingid=r.prodprice_id WHERE p.product_sale=1 and p.product_online=1 and p.product_status=1 and b.price_stock>0 and b.price_expiry >= CURDATE() AND p.product_name LIKE concat(product,'%') order by b.price_expiry ASC, b.price_priority ASC ) AS x GROUP BY x.product_id; */

END$$

CREATE  PROCEDURE `getAllProductsByBrandId` (IN `brandid` INT)   begin
/*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, x.strstk_id, x.strstk_discount 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, e.strstk_id,e.strstk_discount 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_brand = brandid 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;


*/

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,x.strstk_discount,
 x.strstk_id,x.product_prescrption 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,k.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,e.strstk_discount, e.strstk_id,p.product_prescrption
FROM products_tbl p
LEFT 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_brand = brandid 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 e.strstk_offerfrom ASC, s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc 
  ) as x group by x.product_id ;




/*select x.product_id, x.product_name, x.price_id, x.product_category, x.price_expiry from (SELECT ( @row_number := @row_number + 1) AS virtual_id, p.product_id,p.product_name, b.price_id,p.product_category,b.price_expiry FROM products_tbl p INNER JOIN product_pricing r on r.prodprice_product=p.product_id INNER JOIN prices_tbl b on b.price_pricingid=r.prodprice_id WHERE p.product_sale=1 and p.product_online=1 and p.product_status=1 and b.price_stock>0 and b.price_expiry >= CURDATE() AND p.product_name LIKE concat(product,'%') order by b.price_expiry ASC, b.price_priority ASC ) AS x GROUP BY x.product_id; */

END$$

CREATE  PROCEDURE `getAllProductsByDealofDay` ()   begin
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,x.product_prescrption 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,p.product_prescrption 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_dealofday = 1 and p.product_status = 1 and p.product_online = 1 and p.product_publish=1 and e.strstk_dealfrom <= CURRENT_DATE()  and e.strstk_dealto>= CURRENT_DATE() and  s.stockin_expiry >= CURRENT_DATE() and (e.strstk_stock-e.strstk_reserved) > 0 order by e.strstk_dealfrom ASC,s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc) as x group by x.product_id;
/*select x.product_id, x.product_name, x.price_id, x.product_category, x.price_expiry from (SELECT ( @row_number := @row_number + 1) AS virtual_id, p.product_id,p.product_name, b.price_id,p.product_category,b.price_expiry FROM products_tbl p INNER JOIN product_pricing r on r.prodprice_product=p.product_id INNER JOIN prices_tbl b on b.price_pricingid=r.prodprice_id WHERE p.product_sale=1 and p.product_online=1 and p.product_status=1 and b.price_stock>0 and b.price_expiry >= CURDATE() AND p.product_name LIKE concat(product,'%') order by b.price_expiry ASC, b.price_priority ASC ) AS x GROUP BY x.product_id; */
END$$

CREATE  PROCEDURE `getAllProductsByDiscount` ()   begin

SELECT CASE when t.notice_offer!=0 THEN t.notice_offer ELSE 10 END  INTO @discount FROM tbl_notice t ;

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 e.strstk_discount=@discount and s.stockin_expiry >= CURRENT_DATE()   and (e.strstk_stock-e.strstk_reserved) > 0 order by e.strstk_offerfrom ASC,s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc) as x group by x.product_id;
/*select x.product_id, x.product_name, x.price_id, x.product_category, x.price_expiry from (SELECT ( @row_number := @row_number + 1) AS virtual_id, p.product_id,p.product_name, b.price_id,p.product_category,b.price_expiry FROM products_tbl p INNER JOIN product_pricing r on r.prodprice_product=p.product_id INNER JOIN prices_tbl b on b.price_pricingid=r.prodprice_id WHERE p.product_sale=1 and p.product_online=1 and p.product_status=1 and b.price_stock>0 and b.price_expiry >= CURDATE() AND p.product_name LIKE concat(product,'%') order by b.price_expiry ASC, b.price_priority ASC ) AS x GROUP BY x.product_id; */
END$$

CREATE  PROCEDURE `getAllProductsByDiscountwithOffers` (IN `offer` VARCHAR(225), IN `offsets` INT, IN `limits` INT)   begin
DECLARE offerType TEXT;
SELECT h.menu_discount,h.menu_disctype INTO @discount,@disctype FROM home_menu_offer h WHERE h.menu_title=offer;
IF (@disctype = 1) THEN
    SET offerType = CONCAT(' AND e.strstk_discount = ', @discount);
ELSE
    SET offerType = CONCAT(' AND e.strstk_discount <= ', @discount);
END IF;

if offer!="Medicines" THEN
SET @sqlQuery = CONCAT(
    'SELECT *
FROM (
    SELECT
        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,
        p.product_prescrption,
        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,

        ROW_NUMBER() OVER (
            PARTITION BY p.product_id
            ORDER BY
              e.strstk_offerfrom ASC,
              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

    WHERE e.strstk_offer = 1
      AND p.product_status = 1
      AND p.product_online = 1
      AND p.product_publish = 1
      ',offerType,'
      AND e.strstk_discount != 0
      AND s.stockin_expiry >= CURRENT_DATE()
      AND (e.strstk_stock - e.strstk_reserved) > 0
) x
WHERE x.rn = 1
LIMIT ', offsets, ',', limits);

ELSE

SET @sqlQuery = CONCAT(
    'SELECT *
FROM (
    SELECT
        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,
        p.product_prescrption,
        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,

        ROW_NUMBER() OVER (
            PARTITION BY p.product_id
            ORDER BY
              e.strstk_offerfrom ASC,
              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

    WHERE e.strstk_offer = 1
      AND p.product_status = 1
      AND p.product_online = 1
      AND p.product_publish = 1
      ',offerType,'
      AND e.strstk_discount != 0
AND p.product_maincategory=1
      AND s.stockin_expiry >= CURRENT_DATE()
      AND (e.strstk_stock - e.strstk_reserved) > 0

) x
WHERE x.rn = 1
LIMIT ', offsets, ',', limits);
/*
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.product_prescrption,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,p.product_prescrption,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 e.strstk_discount<=@discount and e.strstk_discount!=0 and p.product_maincategory=1 and s.stockin_expiry >= CURRENT_DATE() and (e.strstk_stock-e.strstk_reserved) > 0  order by e.strstk_offerfrom ASC,s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc) as x group by x.product_id LIMIT offsets,limits;*/
END IF;
PREPARE stmt FROM @sqlQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$

CREATE  PROCEDURE `getAllproductsbyLetter` (IN `letter` VARCHAR(200), IN `offsets` INT, IN `limits` INT)   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
    LIMIT offsets, limits;
END$$

CREATE  PROCEDURE `getAllProductsByOffer` ()   begin
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,x.product_prescrption 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,p.product_prescrption 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 e.strstk_offerfrom <= CURRENT_DATE() and e.strstk_offerto>=CURRENT_DATE()  and  s.stockin_expiry >= CURRENT_DATE()   and (e.strstk_stock-e.strstk_reserved) > 0 order by e.strstk_offerfrom ASC,s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc) as x group by x.product_id;
/*select x.product_id, x.product_name, x.price_id, x.product_category, x.price_expiry from (SELECT ( @row_number := @row_number + 1) AS virtual_id, p.product_id,p.product_name, b.price_id,p.product_category,b.price_expiry FROM products_tbl p INNER JOIN product_pricing r on r.prodprice_product=p.product_id INNER JOIN prices_tbl b on b.price_pricingid=r.prodprice_id WHERE p.product_sale=1 and p.product_online=1 and p.product_status=1 and b.price_stock>0 and b.price_expiry >= CURDATE() AND p.product_name LIKE concat(product,'%') order by b.price_expiry ASC, b.price_priority ASC ) AS x GROUP BY x.product_id; */
END$$

CREATE  PROCEDURE `getAllSalesbillsFromDates` (IN `itemid` INT, IN `fromdate` DATE, IN `todate` DATE, IN `storeid` INT)   BEGIN
if storeid>0 THEN
SELECT
    b.bill_id, b.bill_date, b.bill_store, b.bill_no, b.bill_pharmacist, bb.billit_item, bb.billit_name, bb.billit_hsn, bb.billit_mfr, bb.billit_batch, bb.billit_expiry, bb.billit_sched, bb.billit_mrp, bb.billit_discount, bb.billit_rate, bb.billit_qty, bb.billit_amount, bb.billit_cgstpc, bb.billit_cgst, bb.billit_sgstpc, bb.billit_sgst, bb.billit_status, b.bill_customer, b.bill_mobile, b.bill_name, b.bill_age, b.bill_gender, b.bill_address, b.bill_referrer, b.bill_doctor, b.bill_license, 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_paidon, b.bill_payby, b.bill_payref, b.bill_transid, b.bill_balance, b.bill_status
FROM bills_table b
JOIN bill_items bb ON bb.billit_id = b.bill_id
WHERE (itemid IS NULL OR itemid = 0 OR bb.billit_item = itemid)
AND b.bill_date BETWEEN fromdate AND todate AND b.bill_store=storeid GROUP BY b.bill_no ;
ELSE
SELECT
    b.bill_id, b.bill_date, b.bill_store, b.bill_no, b.bill_pharmacist, bb.billit_item, bb.billit_name, bb.billit_hsn, bb.billit_mfr, bb.billit_batch, bb.billit_expiry, bb.billit_sched, bb.billit_mrp, bb.billit_discount, bb.billit_rate, bb.billit_qty, bb.billit_amount, bb.billit_cgstpc, bb.billit_cgst, bb.billit_sgstpc, bb.billit_sgst, bb.billit_status, b.bill_customer, b.bill_mobile, b.bill_name, b.bill_age, b.bill_gender, b.bill_address, b.bill_referrer, b.bill_doctor, b.bill_license, 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_paidon, b.bill_payby, b.bill_payref, b.bill_transid, b.bill_balance, b.bill_status
FROM bills_table b
JOIN bill_items bb ON bb.billit_id = b.bill_id
WHERE (itemid IS NULL OR itemid = 0 OR bb.billit_item = itemid)
AND b.bill_date BETWEEN fromdate AND todate GROUP BY b.bill_no;
END if;
END$$

CREATE  PROCEDURE `getAllScheduleDiscountData` (IN `branchid` INT)   BEGIN
SET SESSION group_concat_max_len = 1000000;
IF branchid>1 THEN
SELECT s.store_id,s.store_code,s.store_name FROM stores_tbl s WHERE s.store_status=1;
SELECT dis_id,(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 dis_store=branchid ORDER BY dis_crtdon DESC ;
ELSE
SELECT s.store_id,s.store_code,s.store_name FROM stores_tbl s WHERE s.store_status=1;
SELECT dis_id,(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 ORDER BY dis_crtdon DESC ;
END IF;
END$$

CREATE  PROCEDURE `getAlltheNotices` ()   BEGIN

 SELECT t.notice_id,t.notice_text,t.notice_offer FROM tbl_notice t ;
 
 SELECT h.menu_id ,h.menu_category,h.menu_icon,h.menu_title,h.menu_caption,h.menu_discount ,h.menu_disctype FROM home_menu_offer h;
 
 SELECT `slider_id`, `slider_type`, `slider_image` FROM tbl_homepageslier h WHERE h.slider_status=1 ORDER BY h.slider_sort ASC;
 
END$$

CREATE  PROCEDURE `getalredyAssignedDataInday` (IN `newdate` DATE)   BEGIN

 SELECT 
       u.user_staffname,
        COUNT(p.assigned_for) AS total_count,
    COUNT(IF(p.product_entry_status = 1, 1, NULL)) AS completed_count FROM products_entry_tbl p
     JOIN users_tbl u
        ON u.user_id=p.assigned_for
       AND date(p.assigned_date)=newdate
    GROUP BY u.user_id,u.user_staffname;

END$$

CREATE  PROCEDURE `getApproveSearch` (IN `storeid` INT, IN `aprvsts` INT)   BEGIN
SELECT i.intend_id, i.intend_number, i.intend_date, i.intend_from, s.store_name AS fromstore, t.store_name AS tostore, i.intend_items FROM intends_tbl i INNER JOIN stores_tbl s ON s.store_id=i.intend_from INNER JOIN stores_tbl t ON t.store_id=i.intend_to WHERE i.intend_status=aprvsts AND i.intend_from = storeid;
END$$

CREATE  PROCEDURE `getAvailablePacking` (IN `prodid` INT)   BEGIN
	SELECT x.prodpack_id, fnGetProductFromPack(x.prodpack_id, 0) AS package, p.packing_type, x.prodpack_quantity, m.measunit_shortname, CONCAT(p.packing_type, ' ', x.prodpack_quantity, ' ', m.measunit_shortname) AS boxunit  
    FROM product_packing x
    LEFT JOIN packing_tbl p ON p.packing_id = x.prodpack_package
    LEFT JOIN measure_units m ON m.measunit_id = x.prodpack_unit 
    WHERE x.prodpack_product = prodid AND x.prodpack_status = 1 
    ORDER BY x.prodpack_package, x.prodpack_quantity;
END$$

CREATE  PROCEDURE `getBillDatabyBillNumnber` (IN `billno` VARCHAR(50))   BEGIN

SELECT b.bill_id,b.bill_date,b.bill_store, b.bill_mobile,b.bill_name,b.bill_netpay,s.store_code,s.store_name , 
(SELECT COUNT(l.billit_item) FROM bill_items l WHERE l.billit_id=b.bill_id )as item_count
FROM bills_table b JOIN stores_tbl s on s.store_id=b.bill_store 
WHERE b.bill_no=billno AND b.bill_delmode=3;
END$$

CREATE  PROCEDURE `getbillItems` (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 `getbrandListbyCategory` (IN `cat` INT, IN `flag` INT)   BEGIN
if flag = 1 then
select b.brand_id,b.brand_name,b.brand_logo from products_tbl p inner join brands_tbl b on p.product_brand = b.brand_id where p.product_category = cat and p.product_publish = 1 and p.product_online = 1 and p.product_status = 1 GROUP BY b.brand_id, b.brand_name;
elseif flag = 2 THEN
select b.brand_id,b.brand_name,b.brand_logo from products_tbl p inner join brands_tbl b on p.product_brand = b.brand_id where p.product_subcategory = cat and p.product_publish = 1 and p.product_online = 1 and p.product_status = 1 GROUP BY b.brand_id,b.brand_name;
elseif flag = 3 THEN
select b.brand_id,b.brand_name,b.brand_logo from products_tbl p inner join brands_tbl b on p.product_brand = b.brand_id where p.product_maincategory = cat and p.product_publish = 1 and p.product_online = 1 and p.product_status = 1 GROUP BY b.brand_id LIMIT 30;
  
end if;
END$$

CREATE  PROCEDURE `getBrandsOfManufacturer` (IN `manfid` INT)   BEGIN
	SELECT brand_id, brand_name 
    FROM brands_tbl 
    WHERE brand_owner = manfid AND brand_status = 1 
    ORDER BY brand_name;
END$$

CREATE  PROCEDURE `getBrandsOfManufacturerbyBrand` (IN `manfid` INT(11), IN `search_term` VARCHAR(225))   BEGIN
IF search_term IS NULL OR search_term = '' THEN
    SELECT brand_id, brand_name 
    FROM brands_tbl 
    WHERE brand_owner = manfid 
      AND brand_status = 1 
    ORDER BY brand_name;
ELSE
    SELECT brand_id, brand_name 
    FROM brands_tbl 
    WHERE brand_name LIKE CONCAT(search_term,'%') 
      AND brand_status = 1 
    ORDER BY brand_name;
END IF;

END$$

CREATE  PROCEDURE `getBrandsOfManufacturerbyBrandNew` (IN `manfid` INT(11), IN `search_term` VARCHAR(225))   BEGIN
IF search_term IS NULL OR search_term = '' THEN
    SELECT brand_id, brand_name 
    FROM brands_tbl b JOIN brand_manufacturer_tbl m ON b.brand_id=m.brnd_id
    WHERE m.brndmanu_id= manfid 
      AND brand_status = 1 
    ORDER BY brand_name;
ELSE
    SELECT brand_id, brand_name 
    FROM brands_tbl 
    WHERE brand_name LIKE CONCAT(search_term,'%') 
      AND brand_status = 1 
    ORDER BY brand_name;
END IF;

END$$

CREATE  PROCEDURE `getBrandsOfManufacturerNew` (IN `manfid` INT)   BEGIN
	SELECT brand_id, brand_name 
    FROM brands_tbl b JOIN brand_manufacturer_tbl m ON b.brand_id=m.brnd_id
    WHERE m.brndmanu_id = manfid AND brand_status = 1 
    ORDER BY brand_name;
END$$

CREATE  PROCEDURE `getCancelOrderDetailsByItems` (IN `branchid` INT)   BEGIN
if branchid=1 THEN
 SELECT o.order_id,c.delivery_to AS customer_name,cd.customer_phone,p.paymt_mode,p.paymt_paid,p.paymt_transid,p.paymnt_currency,p.paymt_paidon,o.order_orderid,o.order_date,o.order_trackid,o.order_status,o.order_delivery,r.refund_razorid,DATE(r.refund_created ) as refund_date,o.order_message, (SELECT COUNT(*) FROM order_details d WHERE d.ordet_order=o.order_id) as total_items FROM orders_tbl o JOIN customers_tbl cd ON cd.customer_id=o.order_customer
JOIN delivery_address c ON c.delivery_user=o.order_customer AND c.delivery_id=o.order_deliverId JOIN payments_tbl p on  p.paymt_orderid=o.order_id LEFT JOIN refund_table r on r.refund_orderid=o.order_id
WHERE o.order_status=0 ORDER BY o.order_id DESC;
ELSE
 SELECT o.order_id,c.delivery_to AS customer_name,cd.customer_phone,p.paymt_mode,p.paymt_paid,p.paymt_transid,p.paymnt_currency,p.paymt_paidon,o.order_orderid,o.order_date,o.order_trackid,o.order_status,o.order_delivery,r.refund_razorid,DATE(r.refund_created ) as refund_date,o.order_message,f.return_status,f.status_date,f.approved_date ,f.pickup_date,f.refund_date as return_date, (SELECT COUNT(*) FROM order_details d WHERE d.ordet_order=o.order_id) as total_items FROM orders_tbl o JOIN customers_tbl cd ON cd.customer_id=o.order_customer
JOIN delivery_address c ON c.delivery_user=o.order_customer AND c.delivery_id=o.order_deliverId JOIN payments_tbl p on  p.paymt_orderid=o.order_id LEFT JOIN refund_table r on r.refund_orderid=o.order_id LEFT JOIN order_return_status_history f ON f.order_id=o.order_id
WHERE o.order_status=2 ORDER BY o.order_id DESC;
END IF;
END$$

CREATE  PROCEDURE `getCancelOrderReasons` ()   BEGIN
SELECT cancel_id,cancel_reason FROM cancelreason_tbl WHERE cancel_status=1;
END$$

CREATE  PROCEDURE `getCartAllDetails` (IN `suppliers` VARCHAR(200))   BEGIN
DROP TEMPORARY TABLE IF EXISTS temp_cartdetails;
CREATE TEMPORARY TABLE temp_cartdetails (
        product_id INT,
        product_name VARCHAR(255),
    product_display VARCHAR(255),
    prodpack_id INT,
    prodpack_quantity INT,
    packing_type VARCHAR(255),
    measunit_shortname VARCHAR(255),
    strstk_mrp DECIMAL(9, 2),
    strstk_msp DECIMAL(9, 2),
    stockin_batch VARCHAR(50),
    product_imageurl VARCHAR(255),
    strstk_discount	DECIMAL(5, 2),
    strstk_id INT,prd_qty INT,stockout INT,product_prescrption INT,invdet_cstpc DECIMAL(9, 2),invdet_sstpc DECIMAL(9, 2));
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);
                     ELSE
                     SET @qty := SUBSTRING_INDEX(@Gstr, ',', -1);
                    
                END IF;
        		SET @icols := @icols + 1;
                
           	END WHILE;
            INSERT INTO temp_cartdetails(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,prd_qty,stockout,product_prescrption,invdet_cstpc,invdet_sstpc) 
            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,@qty,(CASE WHEN (GetProductTotalQuantity(p.product_id,e.strstk_item,e.strstk_id))>0 THEN 1 ELSE 0 END) AS stockout,p.product_prescrption,i.invdet_cstpc, i.invdet_sstpc 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
JOIN invoice_details i ON i.invdet_id = s.stockin_invref
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$$

CREATE  PROCEDURE `getCartDetails` (IN `prodpackid` INT, IN `storestockid` INT)   begin
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,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,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 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 = prodpackid and e.strstk_id = storestockid;


END$$

CREATE  PROCEDURE `getCountOfDataentryperDay` (IN `id` INT)   BEGIN

IF id=222 OR id=223 THEN
SELECT COUNT(assigned_for) AS total_assigned
            FROM products_entry_tbl
            WHERE product_entry_status = 1
            AND assigned_for = id
            AND product_updon >= concat(CURDATE(),' 00:00:00') and product_updon <= concat(CURDATE(),' 23:59:59');
            /*SELECT COUNT(assigned_for) AS total_assigned
            FROM products_entry_tbl
            WHERE product_entry_status = 1
            AND assigned_for = id
            AND DATE(product_updon) = CURDATE(); */
ELSE

            SELECT COUNT(assigned_for) AS total_assigned
            FROM products_entry_tbl
            WHERE product_entry_status = 1
            AND product_updon >= concat(CURDATE(),' 00:00:00') and product_updon <= concat(CURDATE(),' 23:59:59');
END IF;

END$$

CREATE  PROCEDURE `getCourierPacketDetails` (IN `packid` INT)   BEGIN
	SELECT x.transpack_id, x.transpack_type, x.transpack_packid, x.transpack_trackid, x.transpack_collectby, z.courier_name AS coltdby, x.transpack_collecton, x.transpack_deliverby, z.courier_name AS delrdby, x.transpack_deliveron, x.transpack_status, x.transpack_notes
    FROM transfer_packets x
    LEFT JOIN couriers_tbl z ON z.courier_id = x.transpack_collectby /*and z.courier_id = x.transpack_deliverby*/
    LEFT JOIN couriers_tbl q ON q.courier_id = x.transpack_deliverby
    WHERE x.transpack_id = packid;
    SELECT y.transferpack_item, y.transferpack_qty, y.transferpack_packon
    FROM transferpack_items y
    WHERE y.transferpack_packet = packid;
    SELECT p.transferpack_item, p.transferpack_qty, fnGetProductFromPack(si.stockin_item, 0) AS product,
    p.transferpack_packon FROM transferpack_items p
/*    LEFT JOIN stock_inwards s ON s.stockin_item = p.transferpack_item*/
     LEFT JOIN storestock_pricing sp ON sp.strstk_id = p.transferpack_orditem
    LEFT JOIN stock_inwards si ON si.stockin_id = sp.strstk_refer
    LEFT JOIN transfer_packets trp ON trp.transpack_id = p.transferpack_packet
    WHERE p.transferpack_packet = packid;
END$$

CREATE  PROCEDURE `getCustSaleDetails` (IN `storeid` INT, IN `dates` DATE)   BEGIN
IF storeid>1 THEN
SELECT c.customer_id, c.customer_type, c.customer_number, c.customer_name, c.customer_address, c.customer_phone, c.customer_email, c.customer_password, c.customer_gender, c.customer_age, c.customer_country, c.customer_passport, c.customer_premium, c.customer_remarks, c.customer_status, c.customer_crtdon, c.customer_updby, c.customer_updon, b.bill_store ,b.bill_no, s.store_name, b.bill_crtdon, b.bill_payby,b.bill_payref, b.bill_transid, d.doctor_name, o.order_orderid, b.bill_taxable, b.bill_cgst, b.bill_sgst, b.bill_discounts,b.bill_netpay, u.user_staffname, b.bill_pharmacist, m.addr_pin FROM offline_customers_tbl c LEFT JOIN bills_table b ON b.bill_customer = customer_number left join stores_tbl s on s.store_id = b.bill_store LEFT JOIN doctors_tbl d ON d.doctor_id= b.bill_doctor LEFT JOIN orders_tbl o ON o.order_customer= customer_id LEFT JOIN users_tbl u ON u.user_id= b.bill_crtdby  LEFT JOIN address_tbl m ON m.addr_owner=c.customer_id WHERE b.bill_store=storeid AND b.bill_date=dates;
ELSE
SELECT c.customer_id, c.customer_type, c.customer_number, c.customer_name, c.customer_address, c.customer_phone, c.customer_email, c.customer_password, c.customer_gender, c.customer_age, c.customer_country, c.customer_passport, c.customer_premium, c.customer_remarks, c.customer_status, c.customer_crtdon, c.customer_updby, c.customer_updon, b.bill_store ,b.bill_no, s.store_name, b.bill_crtdon, b.bill_payby,b.bill_payref, b.bill_transid, d.doctor_name, o.order_orderid, b.bill_taxable, b.bill_cgst, b.bill_sgst, b.bill_discounts,b.bill_netpay, u.user_staffname, b.bill_pharmacist, m.addr_pin FROM offline_customers_tbl c LEFT JOIN bills_table b ON b.bill_customer = customer_number left join stores_tbl s on s.store_id = b.bill_store LEFT JOIN doctors_tbl d ON d.doctor_id= b.bill_doctor LEFT JOIN orders_tbl o ON o.order_customer= customer_id LEFT JOIN users_tbl u ON u.user_id= b.bill_crtdby  LEFT JOIN address_tbl m ON m.addr_owner=c.customer_id WHERE b.bill_date=dates;
END IF;
END$$

CREATE  PROCEDURE `getDataEntryPerUser` (IN `id` INT)   BEGIN

IF id=222 OR id=223 THEN
SELECT COUNT(*) as dataentry_count FROM products_entry_tbl p WHERE p.product_entry_status=1 AND p.assigned_for=id;
SELECT COUNT(assigned_for) AS total_assigned
            FROM products_entry_tbl
            WHERE product_entry_status = 1
            AND assigned_for = id
            AND product_updon >= concat(CURDATE(),' 00:00:00') and product_updon <= concat(CURDATE(),' 23:59:59');
ELSE
SELECT -1 AS dataentry_count;
           SELECT COUNT(assigned_for) AS total_assigned
            FROM products_entry_tbl
            WHERE product_entry_status = 1
            AND product_updon >= concat(CURDATE(),' 00:00:00') and product_updon <= concat(CURDATE(),' 23:59:59');
END IF;
    
SELECT COUNT(*) as total_count FROM products_entry_tbl p WHERE p.product_entry_status=1;

END$$

CREATE  PROCEDURE `getDeliveryAddressbyId` (IN `userId` INT, IN `id` 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 from delivery_address d WHERE d.delivery_id=id and d.delivery_user=userId;
END$$

CREATE  PROCEDURE `getDetailsbyDates` (IN `storeid` INT, IN `fromdate` DATE, IN `todate` DATE)   BEGIN
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 a.bill_store=2 AND a.bill_date BETWEEN fromdate AND todate order by b.billit_name;
END$$

CREATE  PROCEDURE `getDistributorProductsOfManufacturer` (IN `distrid` 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.distriprod_product FROM distributor_products p 
        WHERE p.distriprod_distributor = distrid AND p.distriprod_product = x.product_id AND p.distriprod_status=1
    )
    AND x.product_status = 1 
    ORDER BY x.product_name;
END$$

CREATE  PROCEDURE `getDistrictsOfState` (IN `state` VARCHAR(20))   BEGIN
	SELECT x.ID, x.Name 
    FROM city x WHERE x.District = TRIM(state)  
    ORDER BY x.Name;
END$$

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

CREATE  PROCEDURE `getExpiredProduct` (IN `storeid` INT)   BEGIN
IF storeid>1 THEN
SELECT a.stockin_store, a.stockin_item, a.stockin_mrp, a.stockin_batch, a.stockin_expiry, a.stockin_stack, b.prodpack_quantity, b.prodpack_unit, c.product_name, c.product_generic, c.product_manufacturer, d.store_name, e.manuf_name, f.genmed_name, g.measunit_shortname, (h.strstk_stock-h.strstk_reserved) AS totalqty, i.invdet_ptr FROM `stock_inwards` a LEFT JOIN product_packing b ON b.prodpack_id=a.stockin_item LEFT JOIN products_tbl c ON c.product_id=b.prodpack_product LEFT JOIN stores_tbl d ON d.store_id=a.stockin_store LEFT JOIN manufacturers_tbl e ON e.manuf_id = c.product_manufacturer LEFT JOIN generic_medicines f ON f.genmed_id= c.product_generic left JOIN measure_units g ON g.measunit_id=b.prodpack_unit LEFT JOIN storestock_pricing h ON h.strstk_item = a.stockin_item LEFT JOIN invoice_details i ON i.invdet_id= a.stockin_id WHERE a.stockin_expiry <= CURDATE() AND a.stockin_store=storeid;
ELSE
SELECT a.stockin_store, a.stockin_item, a.stockin_mrp, a.stockin_batch, a.stockin_expiry, a.stockin_stack, b.prodpack_quantity, b.prodpack_unit, c.product_name, c.product_generic, c.product_manufacturer, d.store_name, e.manuf_name, f.genmed_name, g.measunit_shortname, (h.strstk_stock-h.strstk_reserved) AS totalqty, i.invdet_ptr FROM `stock_inwards` a LEFT JOIN product_packing b ON b.prodpack_id=a.stockin_item LEFT JOIN products_tbl c ON c.product_id=b.prodpack_product LEFT JOIN stores_tbl d ON d.store_id=a.stockin_store LEFT JOIN manufacturers_tbl e ON e.manuf_id = c.product_manufacturer LEFT JOIN generic_medicines f ON f.genmed_id= c.product_generic left JOIN measure_units g ON g.measunit_id=b.prodpack_unit LEFT JOIN storestock_pricing h ON h.strstk_item = a.stockin_item LEFT JOIN invoice_details i ON i.invdet_id= a.stockin_id WHERE a.stockin_expiry <= CURDATE();
END IF;
END$$

CREATE  PROCEDURE `getFilterbyDates` (IN `storeid` INT, IN `fromdate` DATE, IN `todate` DATE)   BEGIN
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 AND a.bill_date BETWEEN fromdate AND todate;
END$$

CREATE  PROCEDURE `getGrnregister` (IN `storeid` INT, IN `fdate` DATE, IN `tdate` DATE)   BEGIN
SELECT s.store_id,s.store_code,s.store_name  FROM stores_tbl s WHERE s.store_status=1;
SELECT t.transpack_packid, t.transpack_to,date(t.transpack_receiveon) AS grn_date,t.transpack_grn, ti.transferpack_item,fnGetProductFromPack(ti.transferpack_item, 0) AS item ,ti.transferpack_orditem, ti.transferpack_qty,sw.stockin_batch,sw.stockin_mrp,sw.stockin_expiry,iv.invdet_cstpc,iv.invdet_sstpc,iv.invdet_mrp,iv.invdet_ptr,iv.invdet_batch ,iv.invdet_expiry,sb.store_code,sb.store_name FROM transfer_packets t
LEFT JOIN transferpack_items ti ON ti.transferpack_packet=t.transpack_id
LEFT JOIN storestock_pricing sp ON sp.strstk_id=ti.transferpack_orditem
LEFT JOIN stock_inwards sw ON sw.stockin_id=sp.strstk_refer
LEFT JOIN invoice_details iv ON iv.invdet_id=sw.stockin_invref
LEFT JOIN stores_tbl sb ON sb.store_id=t.transpack_to
WHERE t.transpack_to=storeid AND date(t.transpack_receiveon) BETWEEN fdate AND tdate AND t.transpack_status=10;
END$$

CREATE  PROCEDURE `getHelpDesk` ()   BEGIN
SELECT * FROM tbl_help_desk h;
END$$

CREATE  PROCEDURE `gethelpDeskIssuesbyIssueId` (IN `title` VARCHAR(225), IN `id` INT)   BEGIN
SELECT r.reason_id,r.reason_issue FROM tbl_help_desk_reason r JOIN tbl_help_desk d ON d.help_id=r.reason_help_id WHERE d.help_title=title AND d.help_id=id;

END$$

CREATE  PROCEDURE `getHomepageadvertisement` ()   BEGIN 

SELECT * FROM advertisements_tbl a WHERE a.advt_hompagestatus = 1 and a.advt_offer=0 AND a.advt_publish = 1 AND a.advt_status =1 AND CURRENT_DATE BETWEEN a.advt_datefrom AND a.advt_dateto;

END$$

CREATE  PROCEDURE `getHourBaseSalesForChart` (IN `storeid` INT, IN `dates` DATE)   BEGIN
IF storeid > 1 THEN
 SELECT 
    CASE
        WHEN HOUR(bill_crtdon) BETWEEN 6 AND 7 THEN '06-08'
        WHEN HOUR(bill_crtdon) BETWEEN 8 AND 9 THEN '08-10'
        WHEN HOUR(bill_crtdon) BETWEEN 10 AND 11 THEN '10-12'
        WHEN HOUR(bill_crtdon) BETWEEN 12 AND 13 THEN '12-14'
        WHEN HOUR(bill_crtdon) BETWEEN 14 AND 15 THEN '14-16'
        WHEN HOUR(bill_crtdon) BETWEEN 16 AND 17 THEN '16-18'
        WHEN HOUR(bill_crtdon) BETWEEN 18 AND 19 THEN '18-20'
        WHEN HOUR(bill_crtdon) BETWEEN 20 AND 21 THEN '20-22'
    END AS time_range,
    SUM(bill_netpay) AS total
FROM bills_table
WHERE 
    DATE(bill_crtdon) = dates
    AND HOUR(bill_crtdon) BETWEEN 6 AND 21 AND bill_store=storeid 
    GROUP BY time_range
ORDER BY time_range;

ELSEIF storeid = 1 THEN
     SELECT 
    CASE
        WHEN HOUR(bill_crtdon) BETWEEN 6 AND 7 THEN '06-08'
        WHEN HOUR(bill_crtdon) BETWEEN 8 AND 9 THEN '08-10'
        WHEN HOUR(bill_crtdon) BETWEEN 10 AND 11 THEN '10-12'
        WHEN HOUR(bill_crtdon) BETWEEN 12 AND 13 THEN '12-14'
        WHEN HOUR(bill_crtdon) BETWEEN 14 AND 15 THEN '14-16'
        WHEN HOUR(bill_crtdon) BETWEEN 16 AND 17 THEN '16-18'
        WHEN HOUR(bill_crtdon) BETWEEN 18 AND 19 THEN '18-20'
        WHEN HOUR(bill_crtdon) BETWEEN 20 AND 21 THEN '20-22'
    END AS time_range,
    SUM(bill_netpay) AS total
FROM bills_table
WHERE 
    DATE(bill_crtdon) = dates
    AND HOUR(bill_crtdon) BETWEEN 6 AND 21 
GROUP BY time_range
ORDER BY time_range;

END IF;

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

CREATE  PROCEDURE `getIngredientsOfType` (IN `typeid` INT)   BEGIN
	SELECT ingred_id, ingred_name 
    FROM ingredients_tbl  
    WHERE ingred_status = 1 AND ingred_type = typeid 
    ORDER BY ingred_name;
END$$

CREATE  PROCEDURE `getIntendAllocations` (IN `intendid` INT, IN `item` INT)   BEGIN
	SELECT x.intdallocit_intend, x.intdallocit_item, x.intdallocit_method, IF(x.intdallocit_method = 1 , s.store_name, fnGetVendorName(x.intdallocit_type, x.intdallocit_source)) AS vendor, x.intdallocit_quantity, x.intdallocit_ordstatus 
    FROM intend_allocation_items x 
    LEFT JOIN stores_tbl s ON s.store_id = x.intdallocit_source 
    WHERE x.intdallocit_intend = intendid AND x.intdallocit_item = item 
    ORDER BY x.intdallocit_method; 
END$$

CREATE  PROCEDURE `getIntendDetails` (IN `intendid` INT)   BEGIN
	SELECT y.intend_id, y.intend_number, y.intend_date, y.intend_from, sf.store_name AS frmstore, y.intend_to, st.store_name AS tostore, y.intend_notes, ia.intdalloc_notes, y.intend_status
    FROM intends_tbl y
    LEFT JOIN stores_tbl st ON st.store_id = y.intend_to
    LEFT JOIN stores_tbl sf ON sf.store_id = y.intend_from
    LEFT JOIN intend_allocations ia ON ia.intdalloc_intend = y.intend_id
    WHERE y.intend_id = intendid;
	
	SELECT x.intdet_id, x.intdet_item, fnGetProductFromPack(pp.prodpack_id, 0) AS package, x.intdet_product, x.intdet_quantity, x.intdet_stock, x.intdet_hsn, x.intdet_status, x.intdet_procby, x.intdet_allotted,
    fnGetStoreStock(0, pp.prodpack_id) AS localstock, fnGetSupplierCountForItem(x.intdet_product) AS storecount,
    (SELECT GROUP_CONCAT(CONCAT(sa.store_name, '|', b.intdallocit_source, '|', b.intdallocit_quantity) SEPARATOR '##') AS storeallocs  FROM intend_allocation_items b
     	LEFT JOIN stores_tbl sa ON sa.store_id = b.intdallocit_source
     	WHERE b.intdallocit_intend = intendid AND b.intdallocit_method = 1 AND b.intdallocit_item = x.intdet_item) AS stores,
    (SELECT GROUP_CONCAT(CONCAT(fnGetVendorName(k.intdallocit_type, k.intdallocit_source), '|', k.intdallocit_vendsup ,'|',k.intdallocit_source,'|',k.intdallocit_type, '|', k.intdallocit_ordrprice, '|', k.intdallocit_quantity) SEPARATOR '##') FROM intend_allocation_items k
     	WHERE k.intdallocit_intend = intendid AND k.intdallocit_method = 2 AND k.intdallocit_item = x.intdet_item) AS suppliers
    FROM intend_details x
    LEFT JOIN product_packing pp ON pp.prodpack_id = x.intdet_item
    LEFT JOIN intends_tbl q ON q.intend_id = x.intdet_id
    WHERE x.intdet_id = intendid;
END$$

CREATE  PROCEDURE `getInvoiceItemDetails` (IN `invitem` INT)   BEGIN
	SELECT x.invdet_item, fnGetProductFromPack(x.invdet_item, 0) AS productpack, p.prodpack_product, p.prodpack_package, x.invdet_qty, x.invdet_free,x.invdet_schdisc, x.invdet_price, x.invdet_hsn, x.invdet_cstpc, x.invdet_cst, x.invdet_sstpc, x.invdet_sst, x.invdet_mrp, x.invdet_ptr, x.invdet_taxamt, x.invdet_discpc, x.invdet_discount, x.invdet_batch, x.invdet_expiry, x.invdet_delstatus, x.invdet_status
    ,p.prodpack_hsn
    FROM invoice_details x
    LEFT JOIN product_packing p ON p.prodpack_id = x.invdet_item
    WHERE x.invdet_id = invitem;
END$$

CREATE  PROCEDURE `getItemdetails` (IN `storeid` INT, IN `itemid` INT)   BEGIN
SELECT s.stockin_id,s.stockin_store, s.stockin_item, pp.prodpack_product,fnGetProductFromPack(s.stockin_item, 0) AS product, s.stockin_batch, s.stockin_expiry, m.strstk_stack,y.storage_label,m.strstk_stock,m.strstk_reserved, (m.strstk_stock-m.strstk_reserved) AS stock FROM stock_inwards s 
LEFT JOIN storestock_pricing m ON m.strstk_item=s.stockin_item and m.strstk_refer = s.stockin_id
LEFT JOIN product_packing pp ON pp.prodpack_id=m.strstk_item 
LEFT JOIN storage_tbl y ON y.storage_id=m.strstk_stack 
LEFT JOIN storestock_pricing w ON w.strstk_refer=s.stockin_id WHERE m.strstk_store =storeid AND s.stockin_item=itemid GROUP by s.stockin_id;
END$$

CREATE  PROCEDURE `getItemreturndetails` (IN `billnum` VARCHAR(100))   BEGIN
SELECT b.ret_itemid, b.ret_item, b.ret_hsn, b.ret_mfr, b.ret_expiry, b.ret_batch, b.ret_sch, b.ret_mrp, b.ret_discount, b.ret_rate, b.ret_qty, b.ret_amount, b.ret_cgst, b.ret_sgst FROM salesretitem_tbl b WHERE b.ret_billnum=billnum;
END$$

CREATE  PROCEDURE `getItemStockForBilling` (IN `storeid` INT, IN `itemid` INT)   BEGIN
	/*SELECT x.strstk_id, x.strstk_item, si.stockin_batch, si.stockin_expiry,
    x.strstk_mrp, x.strstk_msp, x.strstk_discount, x.strstk_cost, x.strstk_last,
    (x.strstk_stock - x.strstk_reserved) AS available, x.strstk_stack, x.strstk_dealofday AS deal,
    x.strstk_offer AS offer, p.prodpack_hsn, fnGetProductFromPack(x.strstk_item, 1) AS product,
    p.prodpack_roq, MAX(i.invdet_cstpc) AS invdet_cstpc, MAX(i.invdet_sstpc) AS invdet_sstpc,
    m.manuf_code, pt.sch_name AS psch, MAX(a.bill_stock) AS bill_stock, x.strstk_stock,
    p.prodpack_quantity, p.prodpack_unit, p.prodpack_package, t.packing_type, sb.storage_label, bb.billit_item
FROM storestock_pricing x
LEFT JOIN stock_inwards si ON si.stockin_id = x.strstk_refer
LEFT JOIN product_packing p ON p.prodpack_id = x.strstk_item
LEFT JOIN invoice_details i ON i.invdet_id = si.stockin_invref
LEFT JOIN products_tbl pr ON pr.product_id = x.strstk_product
LEFT JOIN manufacturers_tbl m ON pr.product_manufacturer = m.manuf_id
LEFT JOIN schedule_tbl pt ON pr.product_schedule = pt.sch_id
LEFT JOIN billstock_tbl a ON a.billstock_item = si.stockin_item
LEFT JOIN packing_tbl t ON t.packing_id = p.prodpack_package
LEFT JOIN storage_tbl sb ON sb.storage_id = si.stockin_stack
LEFT JOIN bill_items bb ON bb.billit_item = x.strstk_item
 WHERE x.strstk_store = storeid AND x.strstk_item = itemid  
GROUP BY x.strstk_id, x.strstk_item, si.stockin_batch, si.stockin_expiry,
         x.strstk_mrp, x.strstk_msp, x.strstk_discount, x.strstk_cost, x.strstk_last,
         available, x.strstk_stack, deal, offer, p.prodpack_hsn, product, p.prodpack_roq,
         m.manuf_code, pt.sch_name, x.strstk_stock, p.prodpack_quantity, p.prodpack_unit,
         p.prodpack_package, t.packing_type, sb.storage_label;*/
         
        (SELECT x.strstk_id, x.strstk_item, si.stockin_batch, si.stockin_expiry,
    x.strstk_mrp, x.strstk_msp, x.strstk_discount, x.strstk_cost, x.strstk_last,
    (x.strstk_stock - x.strstk_reserved) AS available, x.strstk_stack, x.strstk_dealofday AS deal,
    x.strstk_offer AS offer, p.prodpack_hsn, fnGetProductFromPack(x.strstk_item, 1) AS product,
    p.prodpack_roq, MAX(i.invdet_cstpc) AS invdet_cstpc, MAX(i.invdet_sstpc) AS invdet_sstpc,
    m.manuf_code, pt.sch_name AS psch, MAX(a.bill_stock) AS bill_stock, x.strstk_stock,
    p.prodpack_quantity, p.prodpack_unit, p.prodpack_package, t.packing_type, sb.storage_label, bb.billit_item, 0 as rstatus
FROM storestock_pricing x
LEFT JOIN stock_inwards si ON si.stockin_id = x.strstk_refer
LEFT JOIN product_packing p ON p.prodpack_id = x.strstk_item
LEFT JOIN invoice_details i ON i.invdet_id = si.stockin_invref
LEFT JOIN products_tbl pr ON pr.product_id = x.strstk_product
LEFT JOIN manufacturers_tbl m ON pr.product_manufacturer = m.manuf_id
LEFT JOIN schedule_tbl pt ON pr.product_schedule = pt.sch_id
LEFT JOIN billstock_tbl a ON a.billstock_item = si.stockin_item
LEFT JOIN packing_tbl t ON t.packing_id = p.prodpack_package
LEFT JOIN storage_tbl sb ON sb.storage_id = si.stockin_stack
LEFT JOIN bill_items bb ON bb.billit_item = x.strstk_item
 WHERE x.strstk_store = storeid AND x.strstk_item = itemid 
GROUP BY x.strstk_id, x.strstk_item, si.stockin_batch, si.stockin_expiry,
         x.strstk_mrp, x.strstk_msp, x.strstk_discount, x.strstk_cost, x.strstk_last,
         available, x.strstk_stack, deal, offer, p.prodpack_hsn, product, p.prodpack_roq,
         m.manuf_code, pt.sch_name, x.strstk_stock, p.prodpack_quantity, p.prodpack_unit,
         p.prodpack_package, t.packing_type, sb.storage_label)
         
         UNION
         (SELECT x.strstk_id, x.strstk_item, si.stockin_batch, si.stockin_expiry,
    x.strstk_mrp, x.strstk_msp, x.strstk_discount, x.strstk_cost, x.strstk_last,
    ls.LsQty_sqty as available, x.strstk_stack, x.strstk_dealofday AS deal,
    x.strstk_offer AS offer, p.prodpack_hsn, fnGetProductFromPack(x.strstk_item, 1) AS product,
    p.prodpack_roq, MAX(i.invdet_cstpc) AS invdet_cstpc, MAX(i.invdet_sstpc) AS invdet_sstpc,
    m.manuf_code, pt.sch_name AS psch, MAX(a.bill_stock) AS bill_stock, x.strstk_stock,
    p.prodpack_quantity, p.prodpack_unit, p.prodpack_package, 'loose' as packing_type, sb.storage_label, bb.billit_item, 1 as rstatus
FROM storestock_pricing x
LEFT JOIN stock_inwards si ON si.stockin_id = x.strstk_refer

 JOIN looseitemqty_tbl ls ON ls.LsQty_refer = x.strstk_refer
LEFT JOIN product_packing p ON p.prodpack_id = x.strstk_item
LEFT JOIN invoice_details i ON i.invdet_id = si.stockin_invref
LEFT JOIN products_tbl pr ON pr.product_id = x.strstk_product
LEFT JOIN manufacturers_tbl m ON pr.product_manufacturer = m.manuf_id
LEFT JOIN schedule_tbl pt ON pr.product_schedule = pt.sch_id
LEFT JOIN billstock_tbl a ON a.billstock_item = si.stockin_item
LEFT JOIN packing_tbl t ON t.packing_id = p.prodpack_package
LEFT JOIN storage_tbl sb ON sb.storage_id = si.stockin_stack
LEFT JOIN bill_items bb ON bb.billit_item = x.strstk_item
 WHERE x.strstk_store = storeid AND x.strstk_item = itemid
 and ls.LsQty_sqty!=0
GROUP BY x.strstk_id, x.strstk_item, si.stockin_batch, si.stockin_expiry,
         x.strstk_mrp, x.strstk_msp, x.strstk_discount, x.strstk_cost, x.strstk_last,
         available, x.strstk_stack, deal, offer, p.prodpack_hsn, product, p.prodpack_roq,
         m.manuf_code, pt.sch_name, x.strstk_stock, p.prodpack_quantity, p.prodpack_unit,
         p.prodpack_package, t.packing_type, sb.storage_label)
UNION

(SELECT x.strstk_id, x.strstk_item, si.stockin_batch, si.stockin_expiry,
    x.strstk_mrp, x.strstk_msp, x.strstk_discount, x.strstk_cost, x.strstk_last,
    ls.LsQty_sqty as available, x.strstk_stack, x.strstk_dealofday AS deal,
    x.strstk_offer AS offer, p.prodpack_hsn, fnGetProductFromPack(x.strstk_item, 1) AS product,
    p.prodpack_roq, MAX(i.invdet_cstpc) AS invdet_cstpc, MAX(i.invdet_sstpc) AS invdet_sstpc,
    m.manuf_code, pt.sch_name AS psch, MAX(a.bill_stock) AS bill_stock, x.strstk_stock,
    p.prodpack_quantity, p.prodpack_unit, p.prodpack_package, 'return' as packing_type, sb.storage_label, bb.billit_item, 2 as rstatus
FROM storestock_pricing x
LEFT JOIN stock_inwards si ON si.stockin_id = x.strstk_refer

 JOIN looseitreturn_tbl ls ON ls.LsQty_refer = x.strstk_refer
LEFT JOIN product_packing p ON p.prodpack_id = x.strstk_item
LEFT JOIN invoice_details i ON i.invdet_id = si.stockin_invref
LEFT JOIN products_tbl pr ON pr.product_id = x.strstk_product
LEFT JOIN manufacturers_tbl m ON pr.product_manufacturer = m.manuf_id
LEFT JOIN schedule_tbl pt ON pr.product_schedule = pt.sch_id
LEFT JOIN billstock_tbl a ON a.billstock_item = si.stockin_item
LEFT JOIN packing_tbl t ON t.packing_id = p.prodpack_package
LEFT JOIN storage_tbl sb ON sb.storage_id = si.stockin_stack
LEFT JOIN bill_items bb ON bb.billit_item = x.strstk_item
 WHERE x.strstk_store = storeid AND x.strstk_item = itemid
 and ls.LsQty_sqty!=0
GROUP BY x.strstk_id, x.strstk_item, si.stockin_batch, si.stockin_expiry,
         x.strstk_mrp, x.strstk_msp, x.strstk_discount, x.strstk_cost, x.strstk_last,
         available, x.strstk_stack, deal, offer, p.prodpack_hsn, product, p.prodpack_roq,
         m.manuf_code, pt.sch_name, x.strstk_stock, p.prodpack_quantity, p.prodpack_unit,
         p.prodpack_package, t.packing_type, sb.storage_label)
         
         
         
         ORDER BY  strstk_item ASC;
         
END$$

CREATE  PROCEDURE `getLocalStockList` (IN `stkid` INT, IN `intend` INT)   BEGIN
	SELECT x.storestock_store, s.store_name, (x.storestock_available - x.storestock_reserved) AS available, 
    (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.storestock_store AND y.intdallocit_method = 1) AS allotted, x.storestock_min
    FROM storestock_master x 
    LEFT JOIN stores_tbl s ON s.store_id = x.storestock_store 
    WHERE x.storestock_item = stkid AND (x.storestock_available - x.storestock_reserved) > 0
    ORDER BY available;  
END$$

CREATE  PROCEDURE `getmainclassadvertisement` (IN `mainclassid` INT(50), IN `flag` INT)   BEGIN

if flag=1 THEN

SELECT *
FROM advertisements_tbl a
WHERE a.advt_maincategories = mainclassid
  AND a.advt_status = 1
  AND a.advt_publish = 1
  AND a.advt_subcatstatus = 1
  AND CURRENT_DATE BETWEEN a.advt_datefrom AND a.advt_dateto
ORDER BY DATEDIFF(a.advt_dateto, a.advt_datefrom) ASC LIMIT 1;
ELSEIF flag=2 THEN


SELECT *
FROM advertisements_tbl a
WHERE a.advt_subcategories = mainclassid
  AND a.advt_status = 1
  AND a.advt_publish = 1
  AND a.advt_subcatstatus = 1
  AND CURRENT_DATE BETWEEN a.advt_datefrom AND a.advt_dateto
ORDER BY DATEDIFF(a.advt_dateto, a.advt_datefrom) ASC LIMIT 1;
ELSE


SELECT *
FROM advertisements_tbl a
WHERE a.advt_catgory = mainclassid
  AND a.advt_status = 1
  AND a.advt_publish = 1
  AND a.advt_subcatstatus = 1
  AND CURRENT_DATE BETWEEN a.advt_datefrom AND a.advt_dateto
ORDER BY DATEDIFF(a.advt_dateto, a.advt_datefrom) ASC LIMIT 1;
End IF;

END$$

CREATE  PROCEDURE `getmanufcontent` (IN `psearch` TEXT)   BEGIN

SELECT 
    m.manuf_id, 
    m.manuf_name
FROM manufacturers_tbl m

WHERE m.manuf_name LIKE concat ('%',psearch,'%') AND m.manuf_status = 1 

UNION ALL

SELECT 0, 'Select Manufacturer'

ORDER BY manuf_name;

END$$

CREATE  PROCEDURE `getNextTransferOrderNumber` (IN `storeid` INT)   BEGIN
    SELECT CONCAT('TR', COALESCE((SELECT y.store_code FROM stores_tbl y WHERE y.store_id = storeid), ' '), COUNT(*)+1) AS nextorder
    FROM stock_transfers x 
    WHERE x.stocktrans_strfrom = storeid; 
END$$

CREATE  PROCEDURE `getoffersadvertisement` ()   BEGIN

SELECT * FROM advertisements_tbl a WHERE a.advt_offer = 1 AND a.advt_status = 1 AND a.advt_publish = 1 AND a.advt_hompagestatus=1 AND a.advt_offer=1 AND CURRENT_DATE BETWEEN a.advt_datefrom AND a.advt_dateto;

END$$

CREATE  PROCEDURE `getOrderDatabyOrderNumnber` (IN `order_num` VARCHAR(20))   BEGIN

SELECT o.order_id,o.order_orderid,d.delivery_to,d.delivery_phone,o.order_status,o.order_delivery,o.orders_delivered,o.orders_shipped,o.orders_cancelled,p.paymt_status,CONCAT(d.delivery_house,',',d.delivery_street,',',d.delivery_landmark,',',d.delivery_city,',',d.delivery_state,'-',d.delivery_pin) AS address,(SELECT COUNT(od.ordet_order) )as item_count, p.paymt_paid  FROM orders_tbl o  JOIN customers_tbl c on c.customer_id=o.order_customer JOIN delivery_address d on d.delivery_id=o.order_deliverId JOIN order_details od on od.ordet_order=o.order_id JOIN payments_tbl p on p.paymt_orderid=o.order_id WHERE o.order_orderid=order_num ;

END$$

CREATE  PROCEDURE `getPacketDetailsForTransfer` (IN `packetid` INT)   BEGIN
	SELECT x.transpack_id, x.transpack_refer, st.stocktrans_order, st.stocktrans_date, x.transpack_packid, 
    x.transpack_from, sfr.store_name AS strfrom, x.transpack_to, sto.store_name AS strto, 
    x.transpack_items, x.transpack_trackid, x.transpack_collectby, x.transpack_collecton 
    FROM transfer_packets x 
    LEFT JOIN stock_transfers st ON st.stocktrans_id = x.transpack_refer 
    LEFT JOIN stores_tbl sfr ON sfr.store_id = x.transpack_from 
    LEFT JOIN stores_tbl sto ON sto.store_id = x.transpack_to 
    WHERE x.transpack_id = packetid;
    
    SELECT y.transferpack_packet, t.transpack_packid, y.transferpack_item, fnGetProductFromPack(s.stockin_item, 0) AS product, 
    y.transferpack_qty, y.transferpack_recieved, y.transferpack_short, t.transpack_deliveron, 
    t.transpack_notes, y.transferpack_status, s.stockin_batch, s.stockin_expiry, y.transferpack_packon  
    FROM transferpack_items y 
    LEFT JOIN stock_inwards s ON s.stockin_id = y.transferpack_item 
    LEFT JOIN transfer_packets t ON t.transpack_id = y.transferpack_packet 
    WHERE y.transferpack_packet = packetid; 

	SELECT h.handling_id, h.handling_charge, e.stokexp_amount  
    FROM handling_charges h 
    LEFT JOIN stockin_expenses e ON (e.stokexp_chargeon = h.handling_id AND e.stokexp_type = 2 AND e.stokexp_refer = packetid AND e.stokexp_status = 1) 
    WHERE h.handling_status = 1;

END$$

CREATE  PROCEDURE `getPacketDetailsForTransferNew` (IN `packetid` INT)   BEGIN
	SELECT x.transpack_id, x.transpack_refer, st.stocktrans_order, st.stocktrans_date, x.transpack_packid,
    x.transpack_from, sfr.store_name AS strfrom, x.transpack_to, sto.store_name AS strto,
    x.transpack_items, x.transpack_trackid, x.transpack_collectby, x.transpack_collecton
    FROM transfer_packets x
    LEFT JOIN stock_transfers st ON st.stocktrans_id = x.transpack_refer
    LEFT JOIN stores_tbl sfr ON sfr.store_id = x.transpack_from
    LEFT JOIN stores_tbl sto ON sto.store_id = x.transpack_to
    WHERE x.transpack_id = packetid;
    SELECT y.transferpack_packet, t.transpack_packid, y.transferpack_item, fnGetProductFromPack(s.stockin_item, 0) AS product,
    y.transferpack_qty, y.transferpack_recieved, y.transferpack_short, t.transpack_deliveron,
    t.transpack_notes, y.transferpack_status, s.stockin_batch, s.stockin_expiry, y.transferpack_packon
    FROM transferpack_items y
    LEFT JOIN storestock_pricing sp ON sp.strstk_id = y.transferpack_orditem
    LEFT JOIN stock_inwards s ON s.stockin_id = sp.strstk_refer
    LEFT JOIN transfer_packets t ON t.transpack_id = y.transferpack_packet
    WHERE y.transferpack_packet = packetid;
	SELECT h.handling_id, h.handling_charge, e.stokexp_amount
    FROM handling_charges h
    LEFT JOIN stockin_expenses e ON (e.stokexp_chargeon = h.handling_id AND e.stokexp_type = 2 AND e.stokexp_refer = packetid AND e.stokexp_status = 1)
    WHERE h.handling_status = 1;
END$$

CREATE  PROCEDURE `getPacketItems` (IN `packetid` INT)   BEGIN
	SELECT 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, 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 = packetid;
/*
	SELECT p.transferpack_item, p.transferpack_qty, fnGetProductFromPack(s.stockin_item, 0) AS product,
    s.stockin_batch, s.stockin_expiry, t.transpack_packid
    FROM transferpack_items p
    LEFT JOIN stock_inwards s ON s.stockin_id = p.transferpack_item
    LEFT JOIN transfer_packets t ON t.transpack_id = p.transferpack_packet
    WHERE p.transferpack_packet = packetid;
*/
END$$

CREATE  PROCEDURE `getPaymentData` (IN `userId` INT)   BEGIN
DECLARE suppliers  TEXT;
DROP TEMPORARY TABLE IF EXISTS temp_cartdetails;
CREATE TEMPORARY TABLE temp_cartdetails (
    strstk_mrp DECIMAL(9, 2),
    strstk_msp DECIMAL(9, 2),
    strstk_discount	DECIMAL(5, 2),
 prd_qty INT,product_prescrption INT,invdet_cstpc DECIMAL(9, 2),invdet_sstpc DECIMAL(9, 2));
 
 SELECT d.delivery_id as deliveryId FROM delivery_address d WHERE d.delivery_user=userId AND  d.delivery_status=1 AND d.delivery_active=1;
 
SELECT GROUP_CONCAT(CONCAT(prodpack_id, ',', batch_id, ',', quantity) SEPARATOR '##') INTO suppliers
FROM user_cart WHERE user_id =userId AND order_id=0;
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);
                     ELSE
                     SET @qty := SUBSTRING_INDEX(@Gstr, ',', -1);
                END IF;
        		SET @icols := @icols + 1;
           	END WHILE;
            INSERT INTO temp_cartdetails(
    strstk_mrp,
    strstk_msp,
    strstk_discount,
prd_qty,product_prescrption,invdet_cstpc,invdet_sstpc)
            SELECT e.strstk_mrp,e.strstk_msp,e.strstk_discount,@qty,p.product_prescrption,i.invdet_cstpc, i.invdet_sstpc 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 invoice_details i ON i.invdet_id = s.stockin_invref
            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$$

CREATE  PROCEDURE `getPaymentDatabyOrderId` (IN `userId` INT, IN `orderId` VARCHAR(225))   BEGIN
DECLARE suppliers  TEXT;

DROP TEMPORARY TABLE IF EXISTS temp_cartdetails;
CREATE TEMPORARY TABLE temp_cartdetails (
    strstk_mrp DECIMAL(9, 2),
    strstk_msp DECIMAL(9, 2),
    strstk_discount	DECIMAL(5, 2),
 prd_qty INT,product_prescrption INT);
 
 SELECT o.order_id INTO @orderID FROM orders_tbl o WHERE o.order_customer=userId AND o.order_orderid=orderId;
 
 SELECT d.delivery_id as deliveryId FROM delivery_address d WHERE d.delivery_user=userId AND  d.delivery_status=1 AND d.delivery_active=1;
 
SELECT GROUP_CONCAT(CONCAT(prodpack_id, ',', batch_id, ',', quantity) SEPARATOR '##') INTO suppliers
FROM user_cart WHERE user_id =userId AND order_id=@orderID;
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);
                     ELSE
                     SET @qty := SUBSTRING_INDEX(@Gstr, ',', -1);
                END IF;
        		SET @icols := @icols + 1;
           	END WHILE;
            INSERT INTO temp_cartdetails(
    strstk_mrp,
    strstk_msp,
    strstk_discount,
prd_qty,product_prescrption)
            SELECT e.strstk_mrp,e.strstk_msp,e.strstk_discount,@qty,p.product_prescrption 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$$

CREATE  PROCEDURE `getpharmacontent` ()   BEGIN
SELECT * FROM pharmacologicalcontent_tbl WHERE pharma_status=1 limit 10;
END$$

CREATE  PROCEDURE `getPOitemsForInvoce` (IN `porder` INT)   BEGIN
	SELECT x.podetail_id, x.podetail_item, x.podetail_qty, x.podetail_price, 
    y.vendsup_product,y.vendsup_packing,q.prodpack_id,w.packing_id, p.product_name, p.product_display, 
    q.prodpack_package, q.prodpack_quantity, q.prodpack_unit, w.packing_type, 
    (SELECT z.purchord_deliverat FROM purchase_orders z WHERE z.purchord_id = x.podetail_order) AS delat, 
    q.prodpack_hsn
    FROM purchase_details x 
    LEFT JOIN vendor_supplies y ON y.vendsup_id = x.podetail_item 
    LEFT JOIN products_tbl p ON p.product_id = y.vendsup_product 
    LEFT JOIN product_packing q ON q.prodpack_id = y.vendsup_packing 
    LEFT JOIN packing_tbl w ON w.packing_id = q.prodpack_package 
    WHERE x.podetail_order = porder and ((select count(*) from invoice_details id WHERE id.invdet_porder = porder and id.invdet_item = q.prodpack_id) = 0) ;
END$$

CREATE  PROCEDURE `getPreviousreturnedbill` (IN `returndate` DATE, IN `storeid` INT)   BEGIN
if storeid>1 THEN
SELECT a.salesret_id, a.salesret_billnum, a.salesret_Taxamt, a.salesret_cgst, a.salesret_sgst, a.salesret_netpay, b.ret_itemid, b.ret_item, c.bill_store, DATE_FORMAT(a.salesret_crtdon, '%d-%m-%y') AS billdate, d.store_name, b.ret_hsn, b.ret_mfr, b.ret_expiry, b.ret_batch, b.ret_sch, b.ret_mrp, b.ret_discount, b.ret_rate, b.ret_qty, b.ret_amount, b.ret_cgst, b.ret_sgst FROM salesreturn_tbl a LEFT JOIN salesretitem_tbl b ON b.ret_billnum=a.salesret_billnum LEFT JOIN bills_table c ON c.bill_no=a.salesret_billnum LEFT JOIN stores_tbl d ON d.store_id=c.bill_store WHERE a.salesret_crtdon>=returndate AND c.bill_store=storeid GROUP BY a.salesret_billnum;
ELSE
SELECT a.salesret_id, a.salesret_billnum, a.salesret_Taxamt, a.salesret_cgst, a.salesret_sgst, a.salesret_netpay, b.ret_itemid, b.ret_item, c.bill_store, DATE_FORMAT(a.salesret_crtdon, '%d-%m-%y') AS billdate, d.store_name, b.ret_hsn, b.ret_mfr, b.ret_expiry, b.ret_batch, b.ret_sch, b.ret_mrp, b.ret_discount, b.ret_rate, b.ret_qty, b.ret_amount, b.ret_cgst, b.ret_sgst FROM salesreturn_tbl a LEFT JOIN salesretitem_tbl b ON b.ret_billnum=a.salesret_billnum LEFT JOIN bills_table c ON c.bill_no=a.salesret_billnum LEFT JOIN stores_tbl d ON d.store_id=c.bill_store WHERE a.salesret_crtdon>=returndate GROUP BY a.salesret_billnum;
END IF;
END$$

CREATE  PROCEDURE `getproductBycategories` (IN `pidcat` INT, IN `offsets` INT, IN `limits` INT, IN `brandid` VARCHAR(200))   BEGIN
if(brandid="")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,x.strstk_discount,
 x.strstk_id,x.product_prescrption 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,k.packing_type,m.measunit_name,
m.measunit_shortname,e.strstk_mrp,e.strstk_msp,p.product_prescrption,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,e.strstk_discount, e.strstk_id
FROM products_tbl p

LEFT JOIN product_classes pp ON p.product_maincategory = pp.prodclass_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
 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 pp.prodclass_id = pidcat
  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 LIMIT offsets,limits;


ELSE


SET @sql = CONCAT('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,x.strstk_discount,
 x.strstk_id,x.product_prescrption 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,k.packing_type,m.measunit_name,
m.measunit_shortname,e.strstk_mrp,e.strstk_msp,p.product_prescrption,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,e.strstk_discount, e.strstk_id
FROM products_tbl p

LEFT JOIN product_classes pp ON p.product_maincategory = pp.prodclass_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
 e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
 AND p.product_brand IN (',brandid,')
  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 pp.prodclass_id = ',pidcat,'
  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 LIMIT ',offsets,',',limits,'');

 PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;


END IF;
END$$

CREATE  PROCEDURE `getproductBycategorieswithOffers` (IN `pidcat` INT, IN `offsets` INT, IN `limits` INT, IN `brandid` VARCHAR(200))   BEGIN
DECLARE disc INT DEFAULT 0;
SELECT h.menu_discount INTO disc  from home_menu_offer h WHERE h.menu_category=pidcat;

if(brandid="")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,x.strstk_discount,
 x.strstk_id,x.product_prescrption 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,k.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,e.strstk_discount, 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
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
 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 pp.prodclass_id = pidcat
  AND e.strstk_discount<=disc
  AND e.strstk_discount!=0
  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 LIMIT offsets,limits ;
  
 ELSE
 
 SET @sql = CONCAT('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,x.strstk_discount,
 x.strstk_id,x.product_prescrption 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,k.packing_type,m.measunit_name,
m.measunit_shortname,e.strstk_mrp,e.strstk_msp,p.product_prescrption,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,e.strstk_discount, e.strstk_id
FROM products_tbl p

LEFT JOIN product_classes pp ON p.product_maincategory = pp.prodclass_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
 e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
 AND p.product_brand IN (',brandid,')
  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 pp.prodclass_id =', pidcat,'
  AND e.strstk_discount<=',disc,'
  AND e.strstk_discount!=0
  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 LIMIT ',offsets,',',limits,'');

 PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
  
  END IF;
END$$

CREATE  PROCEDURE `getproductBycategorieswithOffersold` (IN `pidcat` INT)   BEGIN
DECLARE disc INT DEFAULT 0;
SELECT h.menu_discount INTO disc  from home_menu_offer h WHERE h.menu_category=pidcat;
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.product_prescrption,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,x.strstk_discount,
 x.strstk_id from (SELECT ( @row_number := @row_number + 1) AS virtual_id,p.product_id,p.product_name,p.product_prescrption,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,e.strstk_discount, e.strstk_id from products_tbl p join product_classes pc on pc.prodclass_id = p.product_maincategory 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_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 and pc.prodclass_id = pidcat AND e.strstk_discount<=disc and e.strstk_discount!=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 `getProductClassCategorytDetails` (IN `pidcat` INT, IN `offsets` INT, IN `limits` INT, IN `brandid` VARCHAR(200))   BEGIN
if brandid="" 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.product_prescrption,
x.measunit_shortname,x.strstk_mrp,x.strstk_msp,x.stockin_batch,x.stockin_expiry,x.strstk_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,k.packing_type,m.measunit_name,
m.measunit_shortname,e.strstk_mrp,e.strstk_msp,s.stockin_batch,p.product_prescrption,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,e.strstk_discount, e.strstk_id
FROM products_tbl p

LEFT JOIN product_classes pp ON p.product_category = pp.prodclass_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
 e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
AND pp.prodclass_id = pidcat 
  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 
  ) as x group by x.product_id;
  
  ELSE
  
  SET @sql = CONCAT('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.product_prescrption,
x.measunit_shortname,x.strstk_mrp,x.strstk_msp,x.stockin_batch,x.stockin_expiry,x.strstk_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_prescrption,p.product_display,p.product_featured,p.product_popular,r.prodpack_id,r.prodpack_quantity,r.prodpack_maxstock,r.prodpack_minstock,k.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,e.strstk_discount, e.strstk_id
FROM products_tbl p

LEFT JOIN product_classes pp ON p.product_category = pp.prodclass_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
 e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
 AND p.product_brand IN (',brandid,')
  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 pp.prodclass_id=',pidcat,'
  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');

 PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
  
  
  END if;
  
END$$

CREATE  PROCEDURE `getProductClassCategorytDetailswithOffers` (IN `pidcat` INT, IN `parentId` INT)   BEGIN
DECLARE disc INT DEFAULT 0;
SELECT h.menu_discount INTO disc  from home_menu_offer h WHERE h.menu_category=parentId;

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,x.strstk_discount, x.strstk_id,x.product_prescrption 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,e.strstk_discount, e.strstk_id,p.product_prescrption from products_tbl p join product_classes pc on pc.prodclass_id = p.product_category 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_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 and pc.prodclass_id = pidcat  AND e.strstk_discount<=disc and e.strstk_discount!=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 `getProductClassSubcatDetails` (IN `pid` INT, IN `offsets` INT, IN `limits` INT, IN `brandid` VARCHAR(200))   BEGIN

SELECT p.prodclass_id,p.prodclass_parent,p.prodclass_name,p.prodclass_thumb from product_classes p WHERE p.prodclass_parent=pid and p.prodclass_status=1 order by p.prodclass_serial;

/*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,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_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_classes pc on pc.prodclass_id = p.product_subcategory 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_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 and pc.prodclass_id = pid order by s.stockin_expiry asc, e.strstk_discount desc, (e.strstk_stock-e.strstk_reserved) desc) as x group by x.product_id;

*/

if(brandid="")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,x.strstk_discount,
 x.strstk_id,x.product_prescrption 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,k.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,e.strstk_discount, 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_subcategory = pp.prodclass_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
 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 pp.prodclass_id = pid
  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 LIMIT offsets,limits ;
  
 ELSE
 
 SET @sql = CONCAT('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,x.strstk_discount,
 x.strstk_id,x.product_prescrption 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,k.packing_type,m.measunit_name,
m.measunit_shortname,e.strstk_mrp,e.strstk_msp,p.product_prescrption,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,e.strstk_discount, e.strstk_id
FROM products_tbl p

LEFT JOIN product_classes pp ON p.product_subcategory = pp.prodclass_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
 e.strstk_product = p.product_id
  AND e.strstk_item = s.stockin_item
 AND p.product_brand IN (',brandid,')
  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 pp.prodclass_id=',pid,'
  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 LIMIT ',offsets,',',limits,'');

 PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
  
  END IF;
END$$

CREATE  PROCEDURE `getProductDataBySearchForAssign` (IN `searchs` TEXT)   BEGIN
	SELECT p.product_id, p.product_name
    FROM  products_entry_tbl p 
    WHERE p.product_name LIKE CONCAT(searchs , '%') AND p.assigned_status=0
    ORDER BY p.product_name;
  
END$$

CREATE  PROCEDURE `getProductDataBySearchForSlider` (IN `searchs` TEXT)   BEGIN
    SELECT p.product_id, p.product_name
    FROM  products_tbl p 
    WHERE p.product_name LIKE CONCAT(searchs , '%') AND p.product_publish=1
    ORDER BY p.product_name;
END$$

CREATE  PROCEDURE `getProductdetailsByAd` (IN `advid` INT)   begin
/*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,
  r.prodpack_maxstock,
  r.prodpack_minstock,
  t.packing_type,
  m.measunit_name,
  m.measunit_shortname,

  MAX(e.strstk_mrp) AS strstk_mrp,
  MAX(e.strstk_msp) AS strstk_msp,
  MIN(s.stockin_expiry) AS stockin_expiry,
  SUM(e.strstk_stock - e.strstk_reserved) AS available_stock,
  MAX(e.strstk_discount) AS strstk_discount,
  MAX(e.strstk_id) AS 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 advertisements_tbl a ON a.advt_products = p.product_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

WHERE a.advt_id = advid
  AND p.product_status = 1
  AND p.product_online = 1
  AND p.product_publish = 1
  AND e.strstk_discount != 0
  AND s.stockin_expiry >= CURRENT_DATE()
  AND (e.strstk_stock - e.strstk_reserved) > 0

GROUP BY r.prodpack_id
ORDER BY stockin_expiry ASC, strstk_discount DESC;
*/
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 products_tbl p
    JOIN advertisements_tbl a ON a.advt_products = p.product_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

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

