-- Table structure for table `tbl_review_and_rate_like_dislike`
--

CREATE TABLE `tbl_review_and_rate_like_dislike` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `fidreview_and_rate` bigint(20) NOT NULL,
  `fstatus` varchar(50) NOT NULL,
  `fInsertTime` timestamp NULL DEFAULT current_timestamp(),
  `fidwebuser` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `aaaa` (`fidreview_and_rate`,`fidwebuser`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `tbl_review_and_rate_like_dislike`
--

INSERT INTO `tbl_review_and_rate_like_dislike` (`id`, `fidreview_and_rate`, `fstatus`, `fInsertTime`, `fidwebuser`) VALUES (8,42,'like','2023-07-31 19:06:36',22),(9,43,'like','2023-08-05 20:58:33',26),(10,44,'like','2023-08-05 20:59:08',26),(11,45,'like','2023-08-05 20:59:13',26),(12,46,'like','2023-08-05 20:59:23',26),(13,47,'like','2023-08-05 20:59:28',26),(14,48,'like','2023-08-05 20:59:33',26),(15,49,'like','2023-08-05 20:59:39',26),(16,50,'like','2023-08-05 20:59:45',26),(17,51,'like','2023-08-05 20:59:51',26),(18,52,'like','2023-08-05 20:59:55',26),(19,53,'like','2023-08-05 21:00:07',26),(20,66,'zero','2023-11-30 09:34:13',58),(21,59,'zero','2023-12-06 09:17:12',58),(22,289,'like','2023-12-30 08:16:30',29),(23,350,'like','2024-03-19 13:58:54',117),(24,350,'like','2024-05-15 12:30:05',146),(25,150,'like','2024-05-19 07:23:01',144),(26,306,'like','2024-09-17 22:10:20',29);

--
-- Table structure for table `tbl_unsubscribe`
--

CREATE TABLE `tbl_unsubscribe` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `url` varchar(405) DEFAULT NULL,
  `source` varchar(45) DEFAULT NULL,
  `title` varchar(45) DEFAULT NULL,
  `code` varchar(50) DEFAULT NULL,
  `visitorinfo` longtext DEFAULT NULL,
  `insertTime` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `tbl_unsubscribe`
--


--
-- Table structure for table `tbl_utm`
--

CREATE TABLE `tbl_utm` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `url` varchar(405) DEFAULT NULL,
  `source` varchar(45) DEFAULT NULL,
  `title` varchar(45) DEFAULT NULL,
  `code` varchar(50) DEFAULT NULL,
  `visitorinfo` longtext DEFAULT NULL,
  `insertTime` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `tbl_utm`
--


--
-- Table structure for table `tblholidays`
--

CREATE TABLE `tblholidays` (
  `FldId` int(11) NOT NULL AUTO_INCREMENT,
  `FldTitle` varchar(200) NOT NULL,
  `FldDate` datetime NOT NULL,
  `Flddeleted` tinyint(1) NOT NULL DEFAULT 0,
  `FldHostName` varchar(100) NOT NULL DEFAULT 'webhost',
  `FldInsertTime` timestamp NOT NULL DEFAULT current_timestamp(),
  `FldInsertUser` varchar(50) NOT NULL DEFAULT 'webuser',
  PRIMARY KEY (`FldId`) USING BTREE,
  UNIQUE KEY `IX_TblHolidays` (`FldDate`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=58 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;

--
-- Dumping data for table `tblholidays`
--

INSERT INTO `tblholidays` (`FldId`, `FldTitle`, `FldDate`, `Flddeleted`, `FldHostName`, `FldInsertTime`, `FldInsertUser`) VALUES (20,'۳ مهر رحلت رسول اکرم؛شهادت امام حسن مجتبی علیه السلام [ ٢٨ صفر ]','2022-09-25 00:00:00',0,'WEBHOST','2022-10-08 10:30:35','voipmani_general@localhost'),(21,'۵ مهر شهادت امام رضا علیه السلام [ ٣٠ صفر ]','2022-09-27 00:00:00',0,'WEBHOST','2022-10-08 11:28:19','voipmani_general@localhost'),(22,'ddddddddd','2022-10-18 00:00:00',0,'WEBHOST','2022-10-08 13:32:31','voipmani_general@localhost'),(24,' ولادت حضرت امام علی علیه السلام (تعطیل)','2023-02-03 00:00:00',0,'webhost','2023-01-30 14:02:43','webuser'),(25,'پيروزي انقلاب اسلامي ايران و سقوط نظام شاهنشاهي (تعطيل)','2023-02-11 00:00:00',0,'webhost','2023-01-30 14:03:01','webuser'),(26,'مبعث حضرت رسول اکرم صلی الله علیه و آله (تعطیل)','2023-02-18 00:00:00',0,'webhost','2023-01-30 14:04:56','webuser'),(27,'ولادت حضرت قائم عجل الله تعالی فرجه (تعطیل)','2023-03-08 00:00:00',0,'webhost','2023-01-30 14:05:41','webuser'),(28,' روز ملي شدن صنعت نفت ايران  (تعطيل)','2023-03-20 00:00:00',0,'webhost','2023-01-30 14:05:57','webuser'),(29,'آغاز نوروز (تعطيل)','2023-03-21 00:00:00',0,'webhost','2023-01-30 14:06:53','webuser'),(30,' عيد نوروز (تعطيل)','2023-03-22 00:00:00',0,'webhost','2023-01-30 14:07:21','webuser'),(31,'عيد نوروز (تعطيل)  ','2023-03-23 00:00:00',0,'webhost','2023-01-30 14:07:39','webuser'),(32,'عيد نوروز (تعطيل)','2023-03-24 00:00:00',0,'webhost','2023-01-30 14:07:51','webuser'),(33,'روز جمهوري اسلامي ايران (تعطيل)','2023-04-01 00:00:00',0,'webhost','2023-01-30 14:08:07','webuser'),(34,'روز طبیعت (تعطیل)','2023-04-02 00:00:00',0,'webhost','2023-01-30 14:08:21','webuser'),(35,'شهادت حضرت امام علی علیه السلام (تعطیل)','2023-04-12 00:00:00',0,'webhost','2023-01-30 14:08:48','webuser'),(36,'عید سعید فطر(تعطیل)','2023-04-22 00:00:00',0,'webhost','2023-01-30 14:09:06','webuser'),(37,' تعطیل به مناسبت عید سعید فطر','2023-04-23 00:00:00',0,'webhost','2023-01-30 14:09:30','webuser'),(38,'شهادت حضرت امام جعفر صادق علیه السلام (تعطیل)','2023-05-16 00:00:00',0,'webhost','2023-01-30 14:09:48','webuser'),(39,' رحلت حضرت امام خميني (رحمه الله عليه) رهبركبير انقلاب و بنيانگذار جمهوري اسلامي ايران _  انتخاب حضرت آيت الله امام خامنه اي به رهبري  (تعطيل)','2023-06-04 00:00:00',0,'webhost','2023-01-30 14:10:07','webuser'),(40,'قیام خونین 15 خرداد (تعطیل)','2023-06-05 00:00:00',0,'webhost','2023-01-30 14:10:22','webuser'),(41,' عيد سعيد قربان (تعطيل)','2023-06-29 00:00:00',0,'webhost','2023-01-30 14:10:41','webuser'),(42,'عيد سعيد غدیر خم (تعطيل)','2023-07-07 00:00:00',0,'webhost','2023-01-30 14:10:58','webuser'),(43,'تاسوعای حسینی (تعطیل)','2023-07-27 00:00:00',0,'webhost','2023-01-30 14:11:14','webuser'),(44,'عاشورای حسینی (تعطیل)','2023-07-28 00:00:00',0,'webhost','2023-01-30 14:11:32','webuser'),(45,'اربعین حسینی (تعطیل)','2023-09-06 00:00:00',0,'webhost','2023-01-30 14:11:51','webuser'),(46,' رحلت حضرت رسول اکرم صلی الله علیه و آله_ شهادت حضرت امام حسن مجتبی علیه السلام (تعطیل)','2023-09-14 00:00:00',0,'webhost','2023-01-30 14:12:08','webuser'),(47,'شهادت حضرت امام رضا علیه السلام (تعطیل)','2023-09-16 00:00:00',0,'webhost','2023-01-30 14:12:25','webuser'),(48,'شهادت حضرت امام حسن عسکری علیه السلام  و آغاز امامت حضرت ولی عصر (عج)(تعطیل)','2023-09-24 00:00:00',0,'webhost','2023-01-30 14:12:42','webuser'),(49,' ولادت حضرت رسول اكرم صلي الله عليه و آله  و روز اخلاق و مهرورزي _ ولادت حضرت امام جعفر صادق عليه السلام مؤسس مذهب جعفري (تعطيل)','2023-10-03 00:00:00',0,'webhost','2023-01-30 14:13:00','webuser'),(50,' شهادت حضرت فاطمه زهرا سلام الله عليها (تعطيل)','2023-12-17 00:00:00',0,'webhost','2023-01-30 14:13:21','webuser'),(51,'ولادت حضرت امام علی علیه السلام (تعطیل)','2024-01-25 00:00:00',0,'webhost','2023-01-30 14:13:41','webuser'),(52,' مبعث حضرت رسول اکرم صلی الله علیه و آله (تعطیل)','2024-02-08 00:00:00',0,'webhost','2023-01-30 14:13:57','webuser'),(53,'پيروزي انقلاب اسلامي ايران و سقوط نظام شاهنشاهي (تعطيل)','2024-02-11 00:00:00',0,'webhost','2023-01-30 14:14:18','webuser'),(54,' ولادت حضرت قائم عجل الله تعالی فرجه (تعطیل)','2024-02-25 00:00:00',0,'webhost','2023-01-30 14:15:03','webuser'),(55,' روز ملي شدن صنعت نفت ايران  (تعطيل)','2024-03-19 00:00:00',0,'webhost','2023-01-30 14:15:31','webuser'),(56,'222222222','2023-01-29 00:00:00',0,'webhost','2023-02-04 22:05:02','webuser'),(57,'wwwwww','2023-02-04 00:00:00',0,'webhost','2023-02-04 22:05:30','webuser');

--
-- Table structure for table `tblinstagram`
--

CREATE TABLE `tblinstagram` (
  `id` int(21) NOT NULL AUTO_INCREMENT,
  `media_url` varchar(2500) DEFAULT NULL,
  `permalink` varchar(2500) DEFAULT NULL,
  `is_shared_to_feed` tinyint(2) DEFAULT NULL,
  `media_type` varchar(2500) DEFAULT NULL,
  `timestamp` varchar(2500) DEFAULT '0',
  `InsertTime` timestamp NULL DEFAULT current_timestamp(),
  `localmedia` varchar(2500) DEFAULT NULL,
  `postid` varchar(245) DEFAULT NULL,
  `caption` varchar(2545) DEFAULT NULL,
  `parentid` varchar(245) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=37335 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `tblinstagram`
--
 

--
-- Table structure for table `tblsounds`
--

CREATE TABLE `tblsounds` (
  `FldId` int(11) NOT NULL AUTO_INCREMENT,
  `FldUserName` varchar(50) NOT NULL,
  `FldPass` varchar(200) NOT NULL,
  `Fldname` varchar(50) NOT NULL,
  `FldLastName` varchar(50) DEFAULT NULL,
  `FldType` tinyint(3) unsigned DEFAULT NULL,
  `FldExtension` varchar(50) DEFAULT NULL,
  `FldInsertTime` timestamp NULL DEFAULT current_timestamp(),
  `FldDeleted` tinyint(1) DEFAULT 0,
  `FldHostName` varchar(50) DEFAULT NULL,
  `FldIsAdmin` tinyint(1) DEFAULT 0,
  `FldIsActive` tinyint(1) DEFAULT 1,
  `FldMobile` varchar(50) DEFAULT NULL,
  `FldEmail` varchar(50) DEFAULT NULL,
  `FldNeddChangePass` tinyint(1) DEFAULT 0,
  PRIMARY KEY (`FldId`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;

--
-- Dumping data for table `tblsounds`
--


--
-- Table structure for table `tbluserlogininfo`
--

CREATE TABLE `tbluserlogininfo` (
  `FldId` int(11) NOT NULL AUTO_INCREMENT,
  `FldIdUser` int(11) DEFAULT NULL,
  `FldUserName` varchar(50) DEFAULT NULL,
  `FldPass` varchar(200) DEFAULT NULL,
  `FldIp` varchar(50) DEFAULT NULL,
  `FldIsAdmin` varchar(50) DEFAULT '0',
  `FldIsActive` varchar(50) DEFAULT '1',
  `FldResultStatus` varchar(50) DEFAULT NULL,
  `FldDeleted` tinyint(1) NOT NULL DEFAULT 0,
  `FldInsertTime` timestamp NULL DEFAULT current_timestamp(),
  `FldHostName` varchar(50) DEFAULT NULL,
  `FldInsertUser` varchar(50) DEFAULT NULL,
  `roles` varchar(405) DEFAULT NULL,
  `fagent` varchar(1500) DEFAULT NULL,
  PRIMARY KEY (`FldId`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1206 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;

--
-- Dumping data for table `tbluserlogininfo`
--
 

--
-- Table structure for table `tblusers`
--

CREATE TABLE `tblusers` (
  `FldId` int(11) NOT NULL AUTO_INCREMENT,
  `FldUserName` varchar(50) NOT NULL,
  `FldPass` varchar(200) NOT NULL,
  `Fldname` varchar(50) NOT NULL,
  `FldLastName` varchar(50) DEFAULT NULL,
  `FldType` tinyint(3) unsigned NOT NULL DEFAULT 4,
  `FldExtension` varchar(50) DEFAULT NULL,
  `FldInsertTime` timestamp NULL DEFAULT current_timestamp(),
  `FldDeleted` tinyint(1) DEFAULT 0,
  `FldHostName` varchar(50) DEFAULT NULL,
  `FldIsAdmin` tinyint(1) DEFAULT 0,
  `FldIsActive` tinyint(1) DEFAULT 1,
  `FldMobile` varchar(50) DEFAULT NULL,
  `FldEmail` varchar(50) DEFAULT NULL,
  `FldNeddChangePass` tinyint(1) DEFAULT 0,
  `FldInsertUser` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`FldId`) USING BTREE,
  UNIQUE KEY `IX_TblUsers` (`FldId`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;

--
-- Dumping data for table `tblusers`
--


--
-- Table structure for table `tblvoipserverinfo`
--

CREATE TABLE `tblvoipserverinfo` (
  `fldid` int(11) NOT NULL,
  `FldType` varchar(50) DEFAULT NULL,
  `FldUser` varchar(50) DEFAULT NULL,
  `FldPass` varchar(50) DEFAULT NULL,
  `FldPort` varchar(50) DEFAULT NULL,
  `FldIpServerVoip` varchar(50) DEFAULT NULL,
  `FldHostName` varchar(100) NOT NULL,
  `FldDeleted` tinyint(1) NOT NULL DEFAULT 0,
  `FldInsertTime` timestamp NOT NULL DEFAULT current_timestamp(),
  `FldInsertUser` varchar(50) NOT NULL,
  PRIMARY KEY (`fldid`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;

--
-- Dumping data for table `tblvoipserverinfo`
--


--
-- Table structure for table `tblwebsettingsportall`
--

CREATE TABLE `tblwebsettingsportall` (
  `FldId` int(11) NOT NULL AUTO_INCREMENT,
  `FldKey` varchar(150) NOT NULL,
  `FldValue` longtext DEFAULT NULL,
  `FldOldValue` longtext DEFAULT NULL,
  `FldShowInSettings` tinyint(1) NOT NULL DEFAULT 0,
  `FldType` int(10) NOT NULL DEFAULT 0,
  PRIMARY KEY (`FldId`),
  UNIQUE KEY `uniqKey` (`FldKey`)
) ENGINE=InnoDB AUTO_INCREMENT=2793 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `tblwebsettingsportall`
--

INSERT INTO `tblwebsettingsportall` (`FldId`, `FldKey`, `FldValue`, `FldOldValue`, `FldShowInSettings`, `FldType`) VALUES (1,'nobatAgreementRule','','',0,0),(2,'PortallFirstPageLogoAdress','/images/icons/android-chrome-512x512.png','',0,0),(4,'PortallTell','09128983015','',0,0),(7,'PortallSiteDescription','09128983015 وحید پوربیرام یک سایت ساز برای طراحی و راه اندازی سامانه های فروشگاه آنلاین و سامانه های نوبت دهی اینترنتی می باشد.','',0,0),(8,'PortallRegisterAgreementRuleHTMLFull','','',0,0),(9,'PortallLoginPageDescreption',' در صورت بروز مشکل با آیدی           <a          class=\"mx-1 color-primary-500\"          href=\"https://t.me/vahidpur\"          target=\"_blank\"        >       تلگرام        </a>         ما در ارتباط باشید\n ','',0,0),(10,'getFastNobat','1','',0,0),(11,'showTodayNobat','1','',0,0),(12,'showTimeNobat','0','',0,0),(20,'HomePageHeader','','',0,0),(24,'AppDirectLink','/app/code-man store.apk','',0,0),(25,'AudioNobatActive','1','',0,0),(28,'PortallFooter','     تمام حقوق مادی و معنوی این وب سایت متعلق به           <a href=\"/\">کـــدمــن</a> میباشد .','',0,0),(29,'PortallSiteName','فروشگاه دمو','',0,0),(34,'HomePageWellcomeMSG','','',0,0),(36,'AppBazarLink','https://cafebazaar.ir/app/io.gonative.android.ddokqx','',0,0),(37,'AppMyketLink','','',0,0),(38,'AppSectionDesc','','',0,0),(43,'canRegister','1','',0,0),(45,'PortallSecoundLogoAdress','','',0,0),(46,'PortallMobile','09128983015','',0,0),(51,'DeactiveUserMessage','کاربر گرامی، در نسخه دمو حساب های ایجاد شده بعد از 48 ساعت غیر غعال میشود، در صورت تمایل به فعالسازی مجدد در قسمت پرسش و پاسخ یا تیکت اطلاع دهید تا حساب کاربری شما فعال شود.','',0,0),(52,'SHOW_ABOUT','1','',0,0),(54,'SHOW_CONTACTUS','1','',0,0),(62,'MAP_SRC','','',0,0),(63,'CONTACTUS_PAGE_TYPE','94','',0,0),(64,'ABOUT_PAGE_TYPE','153','',0,0),(65,'HOME_PAGE_TYPE','45','',0,0),(70,'SITE_KEYWORD','فروشگاه ساز,اسکریپت فروشگاهی','',0,0),(71,'SHOW_LOGIN_CAPCHA','0','',0,0),(72,'TELEGRAM','vahidpur','',0,0),(73,'WHATSAPP',' ','',0,0),(74,'INSTAGRAM','code_man_ir','',0,0),(75,'TWITTER',' ','',0,0),(76,'ABOVE_FOTTER_TXT','','',0,0),(77,'E_NAMAD','<a\n  referrerpolicy=\"origin\"\n  target=\"_blank\"\n  href=\"https://trustseal.enamad.ir/?id=test&amp;Code=test\"\n  ><img\n    referrerpolicy=\"origin\"\n    src=\"/fix_img/namad01.png\"\n    alt=\"\"\n    style=\"cursor: pointer\"\n    id=\"test\"  class=\" m-1 th1 op-70 r-20d \"\n/></a>\n','',0,0),(78,'S_NAMAD','<a\n  referrerpolicy=\"origin\"\n  target=\"_blank\"\n  href=\"https://trustseal.enamad.ir/?id=test&amp;Code=test\"\n  ><img\n    referrerpolicy=\"origin\"\n    src=\"/fix_img/namad03.png\"\n    alt=\"\"\n    style=\"cursor: pointer\"\n    id=\"test\"  class=\" m-1 th1 op-70 r-20d \"\n/></a>','',0,0),(79,'EMAIL_F','vahidpur@gmail.com','',0,0),(80,'PRODUCTS_PAGE_TYPE','2','',0,0),(86,'SHOW_PRODUCTS','1','',0,0),(91,'SHOW_POSTS','1','',0,0),(92,'POSTS_PAGE_TYPE','158','',0,0),(93,'ALLOWSEND_CRASHINFO','1','',0,0),(94,'THM_COLOR_MAIN','{\"color_p_500\":\"#1c1ca0ff\",\"color_p_700\":\"#111179ff\",\"color_p_300\":\"#4f4fd2ff\",\"color_s_500\":\"#4c8119ff\",\"color_s_700\":\"#345411ff\",\"color_s_300\":\"#69a92dff\",\"dashbord_admin\":\"#ffffffff\",\"dashbord_user\":\"#f1f1f1ff\",\"dashbord_seller\":\"#e5e5e5ff\",\"fontMain\":\"Vazir\",\"fontDashboard\":\"IRANYekan\",\"thm1_body\":\"#f7ffff\",\"page_bg_color\":\"#ffffffff\",\"header_bg_color\":\"#ffffffff\"}','',0,0),(95,'SHOW_CHAT','0','',0,0),(96,'SHOW_CHAT_APICODE','taqFJU','',0,0),(98,'GOOGLE_TAG_HEAD','','',0,0),(99,'GOOGLE_TAG_BODY','','',0,0),(100,'DEBUGMODE','0','',0,0),(101,'URL_STORE','store','',0,0),(102,'URL_BLOG','blog','',0,0),(103,'URL_ABOUT','about','',0,0),(104,'URL_CONTACTUS','contact','',0,0),(105,'HEADER_TYPE','0','',0,0),(106,'SHOW_HEADER','0','',0,0),(107,'FOOTER_TYPE','0','',0,0),(108,'SHOW_FOOTER','0','',0,0),(109,'MENUE_TYPE','0','',0,0),(110,'SHOW_MENUE','0','',0,0),(111,'GOOGLE_TAG_DISABLE','1','',0,0),(112,'SMS_OPERATOR','5','',0,0),(113,'SMS_USERNAME','vahidpur','',0,0),(114,'SMSCODE_ERASAL_USER_PASS','449698','',0,0),(115,'SMSCODE_FAALSAZI_HESAB','662416','',0,0),(116,'SMSCODE_SABT_NOBAT','','',0,0),(117,'SMSCODE_TAEED','900157','',0,0),(118,'SMSCODE_YADAVARI_NOBAT','','',0,0),(119,'VERIFY_METHOD','sms','',0,0),(120,'SHOW_Coming_Soon','0','',0,0),(121,'SOON_TYPE','159','',0,0),(122,'PWA','0','',0,0),(123,'POST_COMMENT','1',NULL,0,0),(124,'ABOUT_PAGE_HTML',NULL,NULL,0,1),(125,'EMAILCODE_ERASAL_USER_PASS',NULL,NULL,0,0),(126,'EMAILCODE_FAALSAZI_HESAB',NULL,NULL,0,0),(127,'EMAILCODE_SABT_NOBAT',NULL,NULL,0,0),(128,'EMAILCODE_TAEED',NULL,NULL,0,0),(129,'EMAILCODE_YADAVARI_NOBAT',NULL,NULL,0,0),(130,'SMSCODE_SABT_NOBAT_TOADMIN','',NULL,0,0),(131,'SITE_MAIN_BANER_IMGS','[]',NULL,0,0),(132,'VALIDATE_CODEMELI','',NULL,0,0),(133,'INSTAGRAM_PAGE','code_man_ir',NULL,0,0),(134,'INSTAGRAM_TOKEN','IGQVJXeE9FSkVHR2FlT2l0Vk96ZAmFBbjBocDFld2JJcjl2cDhVM2N3YnRzaWFqdlVHTWlqY0NVU3FPZAnJDTmFzSWFUVERHSk5HVDZAMRFc0ZAHVOWEVpa3dhcW1SWjBudkM5c0NFRXplYi1oQXpRT2pTOQZDZD',NULL,0,0),(135,'SHOW_INSTAGRAM','1',NULL,0,0),(136,'TINYMCEEDITOR_APIKEY','e9ymwibv3wmv72orcghcwa4ue31bx645v9417a7172c5s3ar',NULL,0,0),(138,'FOOTER_GRIDFLOW','0',NULL,0,0),(139,'FOOTER_CLOCK',NULL,NULL,0,0),(142,'HIDE_CODE_MAN_LINKS','1',NULL,0,0),(143,'PWA_SETTINGS','{\"background\":\"#ff6a38ff\",\"theme_color\":\"#54BBED\",\"appName\":\"کدمن\",\"appShortName\":\"کدمن\",\"appDescription\":\"فروشگاه اینترنتی\",\"appleStatusBarStyle\":\"black-translucent\",\"display\":\"standalone\",\"orientation\":\"any\",\"icons\":{\"android\":1,\"appleIcon\":0,\"appleStartup\":0,\"favicons\":1,\"windows\":0,\"yandex\":0}}',NULL,0,0),(144,'USER_ADDRESS_MAP_SETTINGS','{\"api_neshan_web\":\"web.ec6af4eb8e294180b2be957570da79a9\",\"api_neshan_servise\":\"service.622332cab9574c74a9901dea54af1797\",\"api_mapbox\":\"pk.eyJ1IjoidmFoaWRwdXIiLCJhIjoiY2xrcDFieWtrMXcxdjNlcDQ2bTBhMmlvZiJ9.ZZDXGaOUnIfGZ8UpWpj69Q\",\"style_url_mapbox\":\"mapbox://styles/vahidpur/clkozs69801jz01qw50uac9cp\",\"map_Acive\":1,\"neshan_ConvertPointToAddress_Active\":1,\"ActiveWebApi\":\"NESHAN\",\"lat\":\"51.338189\",\"lng\":\"35.699648\"}',NULL,0,0),(145,'FAST_LOGIN','1',NULL,0,0),(146,'SITE_CONDITIONS_PAGE','https://voip-man.ir/',NULL,0,0),(147,'SITE_RULES_PAGE','https://voip-man.ir/',NULL,0,0),(148,'USER_DASH_LAYOUT','[{\"ftype\":\"HTML\",\"insetTime\":1708806734624,\"list\":[],\"count\":0,\"fid_brand\":0,\"fidForm\":0,\"fidCateg\":0,\"odoData\":[],\"elementName\":\"ویرایشگر\",\"settings\":{},\"TOP_MNU\":{},\"TEXTSLIDER\":{},\"imageGrid\":{},\"title\":\"\",\"class1\":\"\",\"DEactive_SECTION\":1,\"class2\":\"\",\"class3\":\"\",\"class4\":\"\",\"lg_size\":1,\"UserPanelContainer\":0,\"AccordionPanel\":0,\"sm_size\":1,\"tabularList\":\"\",\"simplemode\":0,\"cardmode1\":0,\"cardmode2\":0,\"StoreSwip\":[],\"catags\":0,\"compacted\":0,\"onlyImage\":0,\"circleimage\":0,\"gridmode\":0,\"gridmode2\":false,\"amazing_image\":[],\"bg_color\":\" \",\"html\":\"\",\"script\":\"\",\"layouts_html_id\":49}]',NULL,0,0),(149,'FAQ_FIX_SITE','',NULL,0,0),(150,'SHOWLOADING','1',NULL,0,0),(151,'SHOWLOGOINLOADING','1',NULL,0,0),(152,'MAIN_TITLE','فروشگاه دمو 💢',NULL,0,0),(153,'SMSCODE_ORDER_REGISTER','992361',NULL,0,0),(154,'SMSCODE_NEW_TICKET','',NULL,0,0),(155,'SMSCODE_TICKET_ANSWER','',NULL,0,0),(156,'SMSCODE_EXREQUEST_ACCEPT','',NULL,0,0),(157,'SMSCODE_EXREQUEST_RECEIVED','',NULL,0,0),(158,'SMSCODE_ORDER_STATUS_CHANGE','',NULL,0,0),(159,'SMSCODE_EXREQUEST_REJECTED','',NULL,0,0),(160,'SMSCODE_ORDER_REGISTER_ADMIN','',NULL,0,0),(162,'SMSCODE_ORDER_POST_INFO','',NULL,0,0),(190,'SHOWMOBILE_INHEADER','038-31124',NULL,0,0),(198,'filename','/images/icons/android-chrome-512x512.png',NULL,0,0),(199,'path','../voip-man.ir',NULL,0,0),(200,'handleIndexUpdate','1',NULL,0,0),(256,'SMSCODE_FAIL_ONLINE_PAY','',NULL,0,0),(262,'SMSCODE_WALLET_DEPOSITE_USER','',NULL,0,0),(263,'SMSCODE_WALLET_DEPOSITE_ADMIN','',NULL,0,0),(264,'SMSCODE_WALLET_CHANGE_BY_ADMIN_FOR_USER','',NULL,0,0),(271,'SMS_APICODE','mluYaNykily6zlL9HgSaLWHeQeBj14ZYyCdn4zXVlNtgh8B8BIQiu4PcKzNDvyFl',NULL,0,0),(272,'SMS_LINE_NUMBER','30007732003764',NULL,0,0),(436,'SELLER_DASH_LAYOUT','[{\"ftype\":\"HTML\",\"insetTime\":1701959397618,\"list\":[],\"count\":0,\"fid_brand\":0,\"fidForm\":0,\"fidCateg\":0,\"odoData\":[],\"elementName\":\"ویرایشگر\",\"settings\":{},\"TOP_MNU\":{},\"TEXTSLIDER\":{},\"imageGrid\":{},\"title\":\"\",\"class1\":\"\",\"DEactive_SECTION\":1,\"class2\":\"\",\"class3\":\"\",\"class4\":\"\",\"lg_size\":1,\"UserPanelContainer\":0,\"AccordionPanel\":false,\"sm_size\":true,\"tabularList\":\"\",\"simplemode\":false,\"cardmode1\":false,\"cardmode2\":false,\"StoreSwip\":[],\"catags\":false,\"compacted\":false,\"onlyImage\":false,\"circleimage\":false,\"gridmode\":false,\"gridmode2\":false,\"amazing_image\":[],\"bg_color\":\" \",\"html\":\"\",\"script\":\"\",\"layouts_html_id\":44}]',NULL,0,0),(559,'FORCE_GET_USER_INFO_REGISTER_TIME','0',NULL,0,0),(562,'LOGIN_BY_PASSWORD_FOR_REGISTERED_USERS','1',NULL,0,0),(586,'GIFT_USER_BY_REGISTER','2000000',NULL,0,0),(587,'GIFT_USER_BY_FIRST_REVIEW','1000000',NULL,0,0),(588,'GIFT_USER_BY_FIRST_ORDER_BY_WALLET','3000000',NULL,0,0),(711,'SHOWLOADING_REFRESH','1',NULL,0,0),(734,'NOINDEXMODE','',NULL,0,0),(1104,'SITE_ADMINS_MOBILES','',NULL,0,0),(1124,'NOCACHEVIEWDATA','',NULL,0,0),(1260,'SMSCODE_ORDER_PAY_LINK','',NULL,0,0),(1272,'SMSCODE_TICKET_ADMINTOUSER','',NULL,0,0),(1292,'CUSTOM_META_TAGS_INDEXFILE','',NULL,0,0),(1303,'HIDE_CODE_MAN_EXTRACOMMENTS','',NULL,0,0),(1377,'SHOE_WWW_IN_URL','',NULL,0,0),(1426,'TOP_FIXNAV_CIRCLE','1',NULL,0,0),(1427,'BUTTOM_FIXNAV_CIRCLE','1',NULL,0,0),(1798,'notShowEndSupport','',NULL,0,0),(1871,'HOME_HEADER_URI','',NULL,0,0),(1922,'NOTFOUND_REDIRECT_TO_HOME','',NULL,0,0),(2005,'HEADERINFO','{\"mobile\":{\"BanerFix_h\":35,\"Header_h\":68,\"_p\":2},\"desktop\":{\"MenueBar_h\":51,\"_p\":6,\"Header_h\":68,\"BanerFix_h\":60}}',NULL,0,0),(2006,'HEADER_THEME_DESCKTOP','theme-1',NULL,0,0),(2007,'HEADER_THEME_MOBILE','theme-1',NULL,0,0),(2009,'BUTTOM_FIXNAV_SHOW_TITLE','1',NULL,0,0),(2078,'BOTTOM_NAVBAR_THEME_MOBILE','theme-1',NULL,0,0),(2379,'FOOTER_SHOW_DEFAULT_TH','1',NULL,0,0),(2569,'UserComplateInfoImage','',NULL,0,0),(2674,'SOCIAL_NETWORKS_THEME','theme-1',NULL,0,0),(2685,'BALE','vahidpur',NULL,0,0),(2686,'EITA','',NULL,0,0),(2687,'ROBIKA','',NULL,0,0);

--
-- Table structure for table `tblwebusers`
--

CREATE TABLE `tblwebusers` (
  `FldId` bigint(20) NOT NULL AUTO_INCREMENT,
  `fmnulist` longtext DEFAULT NULL,
  `FldUsername` varchar(50) NOT NULL,
  `FldMobile` varchar(200) NOT NULL,
  `FldEmail` varchar(200) DEFAULT NULL,
  `FldNationalCode` varchar(20) DEFAULT NULL,
  `FldPassword` longtext NOT NULL,
  `FldIdLevel1` smallint(6) DEFAULT 0,
  `FldActivation` tinyint(1) NOT NULL DEFAULT 1,
  `FldPasswordChangeDate` timestamp NOT NULL DEFAULT current_timestamp(),
  `FldLastLogin` timestamp NOT NULL DEFAULT current_timestamp(),
  `FldCommitedInfo` tinyint(1) NOT NULL DEFAULT 0,
  `FldDateFldCommitedInfo` datetime(6) DEFAULT NULL,
  `FldInsertTime` timestamp NULL DEFAULT current_timestamp(),
  `FldDeleted` tinyint(1) DEFAULT 0,
  `FldNeedPassChange` tinyint(1) NOT NULL DEFAULT 0,
  `FldIsAdmin` tinyint(1) NOT NULL DEFAULT 1,
  `FldEmailVerifyInfo` varchar(405) NOT NULL DEFAULT 'NO',
  `FldName` varchar(145) DEFAULT 'کاربر',
  `FldLastName` varchar(145) DEFAULT 'جدید',
  `FldMobile2` varchar(45) DEFAULT NULL,
  `FldTelManzel` varchar(45) DEFAULT NULL,
  `fldAdress` varchar(245) DEFAULT 'نامشخص',
  `FldSex` varchar(145) DEFAULT NULL,
  `Fldvoicepath` varchar(245) DEFAULT '',
  `FldFlag` int(11) DEFAULT 0,
  `FldTypeUser` varchar(45) DEFAULT 'owner',
  `FldMobileVerifyInfo` varchar(405) NOT NULL DEFAULT 'NO',
  `fname_og` varchar(445) DEFAULT NULL,
  `fencode_og` varchar(45) DEFAULT NULL,
  `fsabtNo_og` varchar(45) DEFAULT NULL,
  `faddress_og` varchar(1045) DEFAULT NULL,
  `ftell_og` varchar(45) DEFAULT NULL,
  `fshenaseMeli_og` varchar(45) DEFAULT NULL,
  `FldIsSeller` tinyint(1) DEFAULT NULL,
  `FldHoughui` tinyint(1) DEFAULT NULL,
  `flastLoginIp` varchar(45) DEFAULT NULL,
  `fcode` varchar(145) DEFAULT NULL,
  PRIMARY KEY (`FldId`),
  UNIQUE KEY `FldMobile_UNIQUE` (`FldMobile`),
  UNIQUE KEY `FldUsername_UNIQUE` (`FldUsername`),
  UNIQUE KEY `FldEmail_UNIQUE` (`FldEmail`)
) ENGINE=InnoDB AUTO_INCREMENT=244 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;

--
-- Dumping data for table `tblwebusers`
--
 

--
-- Table structure for table `telegramlog`
--

CREATE TABLE `telegramlog` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `fresult` longtext NOT NULL,
  `frefid` bigint(20) NOT NULL,
  `ftype` varchar(45) NOT NULL,
  `fmessageid` varchar(405) NOT NULL,
  `fchatid` varchar(405) NOT NULL,
  `inserttime` timestamp NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `telegramlog`
--


--
-- Table structure for table `tempactivatecode`
--

CREATE TABLE `tempactivatecode` (
  `FldId` bigint(20) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) DEFAULT NULL,
  `tell` varchar(50) DEFAULT NULL,
  `G_code` varchar(50) DEFAULT NULL,
  `insertTime` timestamp NOT NULL DEFAULT current_timestamp(),
  `result` varchar(900) DEFAULT NULL,
  `message` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`FldId`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=608 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;

--
-- Dumping data for table `tempactivatecode`
--
 

--
-- Table structure for table `transactions`
--

CREATE TABLE `transactions` (
  `ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `TransactionCode` varchar(900) NOT NULL,
  `ClientFirstName` varchar(900) NOT NULL,
  `ClientLastName` varchar(900) NOT NULL,
  `ClientEmail` varchar(900) NOT NULL,
  `ClientPhone` varchar(900) NOT NULL,
  `ClientAmount` varchar(900) NOT NULL,
  `ClientDescription` varchar(900) NOT NULL,
  `payDate` varchar(900) NOT NULL,
  `PID` varchar(900) NOT NULL,
  `IDRef` bigint(30) DEFAULT NULL,
  `Result` varchar(405) DEFAULT NULL,
  `IDCustomer` int(11) NOT NULL DEFAULT 0,
  `IDLevel1` int(11) NOT NULL DEFAULT 0,
  `ResultData` longtext DEFAULT NULL,
  `PG` varchar(45) DEFAULT NULL,
  `STATUS` int(11) DEFAULT NULL,
  `ftype` varchar(145) NOT NULL DEFAULT 'nobat',
  `finserttime` timestamp NULL DEFAULT current_timestamp(),
  `fextra` longtext DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `transactions`
-- 

--
-- Table structure for table `trim_url_manager`
--

CREATE TABLE `trim_url_manager` (
  `id` int(25) NOT NULL AUTO_INCREMENT,
  `fredirect_to` varchar(3000) NOT NULL,
  `inserttime` timestamp NULL DEFAULT current_timestamp(),
  `fviewCount` int(20) DEFAULT 0,
  `fcode` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `fcode_UNIQUE` (`fcode`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `trim_url_manager`
--


--
-- Table structure for table `user_favorite`
--

CREATE TABLE `user_favorite` (
  `id` int(25) NOT NULL AUTO_INCREMENT,
  `idwebuser` int(25) NOT NULL,
  `idproduct` int(25) NOT NULL,
  `type` varchar(100) NOT NULL DEFAULT 'product',
  `inserttime` timestamp NULL DEFAULT current_timestamp(),
  `fidVariantProduct` int(25) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `index2` (`idwebuser`,`idproduct`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `user_favorite`
--

 
--
-- Table structure for table `visitors_search_history`
--

CREATE TABLE `visitors_search_history` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `fiduser` bigint(20) DEFAULT NULL,
  `fresult_json` longtext DEFAULT NULL,
  `inserttime` timestamp NULL DEFAULT current_timestamp(),
  `fsearch` varchar(2500) DEFAULT NULL,
  `fcount` int(11) DEFAULT 0,
  `fip` varchar(45) DEFAULT NULL,
  `fresultCount` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=293 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `visitors_search_history`
--

 

--
-- Table structure for table `voip_man_lic_tmp`
--

CREATE TABLE `voip_man_lic_tmp` (
  `vl` longtext DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;

--
-- Dumping data for table `voip_man_lic_tmp`
--


--
-- Table structure for table `wallet`
--

CREATE TABLE `wallet` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `fidwebuser` bigint(20) DEFAULT NULL,
  `fdeposit` bigint(20) DEFAULT NULL,
  `fwithdrawal` bigint(20) DEFAULT NULL,
  `finserttime` timestamp NOT NULL DEFAULT current_timestamp(),
  `fdesc` longtext DEFAULT NULL,
  `fextra` longtext DEFAULT NULL,
  `fref` varchar(2045) DEFAULT NULL,
  `ftype_ref` varchar(545) DEFAULT NULL,
  `finsertedUser` bigint(20) NOT NULL,
  `finsertedUserFullName` varchar(545) NOT NULL,
  `fdeleted` tinyint(3) NOT NULL DEFAULT 0,
  `fdeleteduser` varchar(545) DEFAULT NULL,
  `fdeletedUserId` bigint(20) DEFAULT NULL,
  `ftranUID` varchar(945) DEFAULT NULL,
  `fidtransaction` varchar(945) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=231 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `wallet`
--
 

--
-- Table structure for table `webuser_bill_address`
--

CREATE TABLE `webuser_bill_address` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `fid_province_cities` int(11) NOT NULL,
  `inserttime` timestamp NULL DEFAULT current_timestamp(),
  `fplak` varchar(45) DEFAULT NULL,
  `fvahed` varchar(45) DEFAULT NULL,
  `fpostalcode` varchar(15) DEFAULT NULL,
  `fname` varchar(145) DEFAULT NULL,
  `fmobile` varchar(45) DEFAULT NULL,
  `flastname` varchar(245) DEFAULT NULL,
  `fstreet` varchar(945) DEFAULT NULL,
  `fdeleted` tinyint(3) DEFAULT 0,
  `factive` tinyint(3) DEFAULT 1,
  `fidwebuser` bigint(20) NOT NULL,
  `fdefault` tinyint(3) DEFAULT NULL,
  `fmapCenter` varchar(145) DEFAULT NULL,
  `fmapAddress` longtext DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=55 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `webuser_bill_address`
--
 

--
-- Table structure for table `webuser_seened`
--

CREATE TABLE `webuser_seened` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `ftype` varchar(50) DEFAULT NULL,
  `updatetime` timestamp NOT NULL DEFAULT current_timestamp(),
  `fref` bigint(20) NOT NULL,
  `idwebuser` int(11) NOT NULL,
  `fcount` int(11) DEFAULT 1,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniqueview` (`ftype`,`fref`,`idwebuser`)
) ENGINE=InnoDB AUTO_INCREMENT=4045 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `webuser_seened`
--
 

--
-- Dumping events for database 'voipmani_db2_demo2'
--

--
-- Dumping routines for database 'voipmani_db2_demo2'
--
/*!50003 DROP FUNCTION IF EXISTS `fConvertTimeToInt` */;
DELIMITER ;;
CREATE  FUNCTION `fConvertTimeToInt`(`ch` VARCHAR(6)) RETURNS int(11)
BEGIN
  DECLARE _Result integer;
  SET _Result =  (select ROUND(  ( time_to_sec(ch)/60)  , 0) ) ;
  RETURN _Result  ;
 
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `FFFFCONVERTMILLADYTOGHAMARY` */;
DELIMITER ;;
CREATE  FUNCTION `FFFFCONVERTMILLADYTOGHAMARY`(`dateInput` DATETIME) RETURNS varchar(30) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
  DECLARE _Result varchar(30);
  if length(trim(dateInput))  <4  then
   return '';
  end if;
  if dateInput is null then
   return '';
  end if;
  if  IFNULL(DAYNAME(dateInput) , '') = '' then
 return '';
end if;
  SET _Result = pdate(dateInput);
  RETURN _Result  ;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `FFFFCONVERTMILLADYTOGHAMARY_BYNULL` */;
DELIMITER ;;
CREATE  FUNCTION `FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`dateInput` varchar(50)) RETURNS varchar(30) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
  DECLARE _Result varchar(30);
 
 if dateInput = 'Invalid Date' then
  return null;
 end if;
 set _Result = ( select CASE
    WHEN dateInput is not null and length(trim(dateInput))  > 8 THEN ffffConvertMilladyToGHamary( dateInput)
    ELSE null
END   ) ;
 
  RETURN _Result  ;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `fMilladyToShamsi_ByTime` */;
DELIMITER ;;
CREATE  FUNCTION `fMilladyToShamsi_ByTime`(`dateInput` DATETIME) RETURNS varchar(30) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
  DECLARE _Result varchar(20);
  if  IFNULL(DAYNAME(dateInput) , '') = '' then
 return '';
end if;
  SET _Result = pdate(dateInput);
  RETURN _Result  ;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `fMilladyToShamsi_NoTime` */;
DELIMITER ;;
CREATE  FUNCTION `fMilladyToShamsi_NoTime`(`dateInput` DATETIME) RETURNS varchar(40) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
  DECLARE _Result varchar(20);
  if  IFNULL(DAYNAME(dateInput) , '') = '' then
 return '';
end if;
  SET _Result = pdate(dateInput);
  RETURN _Result  ;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `fNameConvert` */;
DELIMITER ;;
CREATE  FUNCTION `fNameConvert`(`fname` LONGTEXT CHARSET utf8mb4) RETURNS longtext CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result longtext;
      	
set Result= replace(  CONVERT(fname USING utf8mb4)   ,' ','');



 





 

 

 
RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `gdate` */;
DELIMITER ;;
CREATE  FUNCTION `gdate`(`jy` SMALLINT, `jm` SMALLINT, `jd` SMALLINT) RETURNS datetime
    READS SQL DATA
    DETERMINISTIC
BEGIN




	DECLARE
		i, j, e, k, mo,
		gy, gm, gd,
		g_day_no, j_day_no, bkab, jmm, mday, g_day_mo, bkab1, j1
	INT DEFAULT 0; 
	DECLARE fdate datetime;


  SET bkab = __mymod(jy,33);

  IF (bkab = 1 or bkab= 5 or bkab = 9 or bkab = 13 or bkab = 17 or bkab = 22 or bkab = 26 or bkab = 30) THEN
    SET j=1;
  end IF;

  SET bkab1 = __mymod(jy+1,33);

  IF (bkab1 = 1 or bkab1= 5 or bkab1 = 9 or bkab1 = 13 or bkab1 = 17 or bkab1 = 22 or bkab1 = 26 or bkab1 = 30) THEN
    SET j1=1;
  end IF;

	CASE jm
		WHEN 1 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 2 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 3 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 4 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 5 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 6 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 7 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 8 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 9 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 10 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 11 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 12 THEN IF jd > _jdmarray2(jm)+j or jd <= 0 THEN SET e=1; end IF;
	END CASE;
  IF jm > 12 or jm <= 0 THEN SET e=1; end IF;
  IF jy <= 0 THEN SET e=1; end IF;

  IF e>0 THEN
    RETURN 0;
  end IF;

  IF (jm>=11) or (jm=10 and jd>=11 and j=0) or (jm=10 and jd>11 and j=1) THEN
    SET i=1;
  end IF;
  SET gy = jy + 621 + i;

  IF (__mymod(gy,4)=0) THEN
    SET k=1;
  end IF;

	IF (__mymod(gy,100)=0) and (__mymod(gy,400)<>0) THEN
		SET k=0;
	END IF;

  SET jmm=jm-1;

  WHILE (jmm > 0) do
    SET mday=mday+_jdmarray2(jmm);
    SET jmm=jmm-1;
  end WHILE;

  SET j_day_no=(jy-1)*365+(__mydiv(jy,4))+mday+jd;
  SET g_day_no=j_day_no+226899;


  SET g_day_no=g_day_no-(__mydiv(gy-1,4));
  SET g_day_mo=__mymod(g_day_no,365);

	IF (k=1 and j=1) THEN
		IF (g_day_mo=0) THEN
			RETURN CONCAT_WS('-',gy,'12','30');
		END IF;
		IF (g_day_mo=1) THEN
			RETURN CONCAT_WS('-',gy,'12','31');
		END IF;
	END IF;

	IF (g_day_mo=0) THEN
		RETURN CONCAT_WS('-',gy,'12','31');
	END IF;


  SET mo=0;
  SET gm=gm+1;
  while g_day_mo>_gdmarray2(mo,k) do
		SET g_day_mo=g_day_mo-_gdmarray2(mo,k);
    SET mo=mo+1;
    SET gm=gm+1;
  end WHILE;
  SET gd=g_day_mo;

  RETURN CONCAT_WS('-',gy,gm,gd);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `gdatestr` */;
DELIMITER ;;
CREATE  FUNCTION `gdatestr`(`jdat` CHAR(10)) RETURNS datetime
    READS SQL DATA
    DETERMINISTIC
BEGIN




	DECLARE
		i, j, e, k, mo,
		gy, gm, gd,
		g_day_no, j_day_no, bkab, jmm, mday, g_day_mo, jd, jy, jm,bkab1,j1
	INT DEFAULT 0; 
	DECLARE jdd, jyd, jmd, jt varchar(100);
	DECLARE fdate datetime;

	SET jdd = SUBSTRING_INDEX(jdat, '/', -1);
	SET jt = SUBSTRING_INDEX(jdat, '/', 2);
	SET jyd = SUBSTRING_INDEX(jt, '/', 1);
	SET jmd = SUBSTRING_INDEX(jt, '/', -1);
	SET jd = CAST(jdd as SIGNED);
	SET jy = CAST(jyd as SIGNED);
	SET jm = CAST(jmd as SIGNED);


	 SET bkab = __mymod(jy,33);

  IF (bkab = 1 or bkab= 5 or bkab = 9 or bkab = 13 or bkab = 17 or bkab = 22 or bkab = 26 or bkab = 30) THEN
    SET j=1;
  end IF;

  SET bkab1 = __mymod(jy+1,33);

  IF (bkab1 = 1 or bkab1= 5 or bkab1 = 9 or bkab1 = 13 or bkab1 = 17 or bkab1 = 22 or bkab1 = 26 or bkab1 = 30) THEN
    SET j1=1;
  end IF;

	CASE jm
		WHEN 1 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 2 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 3 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 4 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 5 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 6 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 7 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 8 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 9 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 10 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 11 THEN IF jd > _jdmarray2(jm) or jd <= 0 THEN SET e=1; end IF;
		WHEN 12 THEN IF jd > _jdmarray2(jm)+j or jd <= 0 THEN SET e=1; end IF;
	END CASE;
  IF jm > 12 or jm <= 0 THEN SET e=1; end IF;
  IF jy <= 0 THEN SET e=1; end IF;

  IF e>0 THEN
    RETURN 0;
  end IF;

  IF (jm>=11) or (jm=10 and jd>=11 and j=0) or (jm=10 and jd>11 and j=1) THEN
    SET i=1;
  end IF;
  SET gy = jy + 621 + i;

  IF (__mymod(gy,4)=0) THEN
    SET k=1;
  end IF;

	IF (__mymod(gy,100)=0) and (__mymod(gy,400)<>0) THEN
		SET k=0;
	END IF;

  SET jmm=jm-1;

  WHILE (jmm > 0) do
    SET mday=mday+_jdmarray2(jmm);
    SET jmm=jmm-1;
  end WHILE;

  SET j_day_no=(jy-1)*365+(__mydiv(jy,4))+mday+jd;
  SET g_day_no=j_day_no+226899;


  SET g_day_no=g_day_no-(__mydiv(gy-1,4));
  SET g_day_mo=__mymod(g_day_no,365);

	IF (k=1 and j=1) THEN
		IF (g_day_mo=0) THEN
			RETURN CONCAT_WS('-',gy,'12','30');
		END IF;
		IF (g_day_mo=1) THEN
			RETURN CONCAT_WS('-',gy,'12','31');
		END IF;
	END IF;

	IF (g_day_mo=0) THEN
		RETURN CONCAT_WS('-',gy,'12','31');
	END IF;


  SET mo=0;
  SET gm=gm+1;
  while g_day_mo>_gdmarray2(mo,k) do
		SET g_day_mo=g_day_mo-_gdmarray2(mo,k);
    SET mo=mo+1;
    SET gm=gm+1;
  end WHILE;
  SET gd=g_day_mo;

  RETURN CONCAT_WS('-',gy,gm,gd);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `pdate` */;
DELIMITER ;;
CREATE  FUNCTION `pdate`(`gdate` DATETIME) RETURNS char(100) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
    READS SQL DATA
    DETERMINISTIC
BEGIN




	DECLARE
		i,
		gy, gm, gd,
		g_day_no, j_day_no, j_np,jy INT DEFAULT 0;  
	DECLARE jm, jd INT(2) ZEROFILL DEFAULT 0;
	DECLARE resout char(100);
	DECLARE ttime CHAR(20);

	SET gy = YEAR(gdate) - 1600;
	SET gm = MONTH(gdate) - 1;
	SET gd = DAY(gdate) - 1;
	SET ttime = TIME(gdate);
	SET g_day_no = ((365 * gy) + __mydiv(gy + 3, 4) - __mydiv(gy + 99, 100) + __mydiv (gy + 399, 400));
	SET i = 0;

	WHILE (i < gm) do
		SET g_day_no = g_day_no + _gdmarray(i);
		SET i = i + 1;
	END WHILE;

	IF gm > 1 and ((gy % 4 = 0 and gy % 100 <> 0)) or gy % 400 = 0 THEN
		SET g_day_no =	g_day_no + 1;
	END IF;

	SET g_day_no = g_day_no + gd;
	SET j_day_no = g_day_no - 79;
	SET j_np = j_day_no DIV 12053;
	SET j_day_no = j_day_no % 12053;
	SET jy = 979 + 33 * j_np + 4 * __mydiv(j_day_no, 1461);
	SET j_day_no = j_day_no % 1461;

	IF j_day_no >= 366 then
		SET jy = jy + __mydiv(j_day_no - 1, 365);
		SET j_day_no = (j_day_no - 1) % 365;
	END IF;

	SET i = 0;

	WHILE (i < 11 and j_day_no >= _jdmarray(i)) do
		SET j_day_no = j_day_no - _jdmarray(i);
		SET i = i + 1;
	END WHILE;

	SET jm = i + 1;
	SET jd = j_day_no + 1;
	SET resout = CONCAT_WS ('/', jy, jm, jd);

	IF (ttime <> '00:00:00') then
		SET resout = CONCAT_WS(' ', resout, ttime);
	END IF;

	RETURN resout;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `pday` */;
DELIMITER ;;
CREATE  FUNCTION `pday`(`gdate` DATETIME) RETURNS char(100) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
    READS SQL DATA
    DETERMINISTIC
BEGIN




	DECLARE
		i,
		gy, gm, gd,
		g_day_no, j_day_no, j_np,
		jy, jm, jd INT DEFAULT 0; 

	SET gy = YEAR(gdate) - 1600;
	SET gm = MONTH(gdate) - 1;
	SET gd = DAY(gdate) - 1;
	SET g_day_no = ((365 * gy) + __mydiv(gy + 3, 4) - __mydiv(gy + 99 , 100) + __mydiv(gy + 399, 400));
	SET i = 0;

	WHILE (i < gm) do
		SET g_day_no = g_day_no + _gdmarray(i);
		SET i = i + 1;
	END WHILE;

	IF gm > 1 and ((gy % 4 = 0 and gy % 100 <> 0)) or gy % 400 = 0 THEN
		SET g_day_no = g_day_no + 1;
	END IF;

	SET g_day_no = g_day_no + gd;
	SET j_day_no = g_day_no - 79;
	SET j_np = j_day_no DIV 12053;
	SET j_day_no = j_day_no % 12053;
	SET jy = 979 + 33 * j_np + 4 * __mydiv(j_day_no, 1461);
	SET j_day_no = j_day_no % 1461;

	IF j_day_no >= 366 then
		SET jy = jy + __mydiv(j_day_no - 1, 365);
		SET j_day_no = (j_day_no-1) % 365;
	END IF;

	SET i = 0;

	WHILE (i < 11 and j_day_no >= _jdmarray(i)) do
		SET j_day_no = j_day_no - _jdmarray(i);
		SET i = i + 1;
	END WHILE;

	SET jm = i + 1;
	SET jd = j_day_no + 1;
	RETURN jd;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `PMONTH` */;
DELIMITER ;;
CREATE  FUNCTION `PMONTH`(`gdate` DATETIME) RETURNS char(100) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
    READS SQL DATA
    DETERMINISTIC
BEGIN




	DECLARE
		i,
		gy, gm, gd,
		g_day_no, j_day_no, j_np,
		jy, jm, jd INT DEFAULT 0; 

	SET gy = YEAR(gdate) - 1600;
	SET gm = MONTH(gdate) - 1;
	SET gd = DAY(gdate) - 1;
	SET g_day_no = ((365 * gy) + __mydiv(gy + 3, 4) - __mydiv(gy + 99, 100) + __mydiv(gy + 399, 400));
	SET i = 0;

	WHILE (i < gm) do
		SET g_day_no = g_day_no + _gdmarray(i);
		SET i = i + 1;
	END WHILE;

	IF gm > 1 and ((gy % 4 = 0 and gy % 100 <> 0)) or gy % 400 = 0 THEN
		SET g_day_no = g_day_no + 1;
	END IF;

	SET g_day_no = g_day_no + gd;
	SET j_day_no = g_day_no - 79;
	SET j_np = j_day_no DIV 12053;
	set j_day_no = j_day_no % 12053;
	SET jy = 979 + 33 * j_np + 4 * __mydiv(j_day_no, 1461);
	SET j_day_no = j_day_no % 1461;

	IF j_day_no >= 366 then
		SET jy = jy + __mydiv(j_day_no - 1, 365);
		SET j_day_no =(j_day_no - 1) % 365;
	END IF;

	SET i = 0;

	WHILE (i < 11 and j_day_no >= _jdmarray(i)) do
		SET j_day_no = j_day_no - _jdmarray(i);
		SET i = i + 1;
	END WHILE;

	SET jm = i + 1;
	SET jd = j_day_no + 1;
	RETURN jm;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `pmonthname` */;
DELIMITER ;;
CREATE  FUNCTION `pmonthname`(`gdate` DATETIME) RETURNS varchar(100) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
    READS SQL DATA
    DETERMINISTIC
BEGIN




	CASE PMONTH(gdate)
		WHEN 1 THEN RETURN 'فروردین';
		WHEN 2 THEN RETURN 'اردیبهشت';
		WHEN 3 THEN	RETURN 'خرداد';
		WHEN 4 THEN	RETURN 'تیر';
		WHEN 5 THEN	RETURN 'مرداد';
		WHEN 6 THEN	RETURN 'شهریور';
		WHEN 7 THEN	RETURN 'مهر';
		WHEN 8 THEN	RETURN 'آبان';
		WHEN 9 THEN	RETURN 'آذر';
		WHEN 10 THEN RETURN	'دی';
		WHEN 11 THEN RETURN	'بهمن';
		WHEN 12 THEN RETURN	'اسفند';
	END CASE;

END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `pyear` */;
DELIMITER ;;
CREATE  FUNCTION `pyear`(`gdate` DATETIME) RETURNS char(100) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
    READS SQL DATA
    DETERMINISTIC
BEGIN




	DECLARE
		i,
		gy, gm, gd,
		g_day_no, j_day_no, j_np,
		jy, jm, jd INT DEFAULT 0; 

	SET gy = YEAR(gdate) - 1600;
	SET gm = MONTH(gdate) - 1;
	SET gd = DAY(gdate) - 1;
	SET g_day_no = ((365 * gy) + __mydiv(gy + 3, 4) - __mydiv(gy + 99, 100) + __mydiv(gy + 399, 400));
	SET i = 0;

	WHILE (i < gm) do
		SET g_day_no = g_day_no + _gdmarray(i);
		SET i = i + 1;
	END WHILE;

	IF gm > 1 and ((gy % 4 = 0 and gy % 100 <> 0)) or gy % 400 = 0 THEN
		SET g_day_no =	g_day_no + 1;
	END IF;

	SET g_day_no = g_day_no + gd;
	SET j_day_no = g_day_no - 79;
	SET j_np = j_day_no DIV 12053;
	set j_day_no = j_day_no % 12053;
	SET jy = 979 + 33 * j_np + 4 * __mydiv(j_day_no, 1461);
	SET j_day_no = j_day_no % 1461;

	IF j_day_no >= 366 then
		SET jy = jy + __mydiv(j_day_no - 1, 365);
		SET j_day_no = (j_day_no - 1) % 365;
	END IF;

	SET i = 0;

	WHILE (i < 11 and j_day_no >= _jdmarray(i)) do
		SET j_day_no = j_day_no - _jdmarray(i);
		SET i = i + 1;
	END WHILE;

	SET jm = i + 1;
	SET jd = j_day_no + 1;
	RETURN jy;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURNBILLPRICE` */;
DELIMITER ;;
CREATE  FUNCTION `RETURNBILLPRICE`(`idbill` bigint  ) RETURNS bigint(20)
BEGIN

DECLARE Result bigint;
      	
set Result=  (select sum( fprice) from billing_details where fidbilling = idbill and fdeleted=0 ) ;


RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURNBILLPRODUCTSIMAGE` */;
DELIMITER ;;
CREATE  FUNCTION `RETURNBILLPRODUCTSIMAGE`(`idbill` bigint  ) RETURNS longtext CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result longtext  CHARSET utf8mb4 COLLATE utf8mb4_general_ci;
      	
set Result=  (SELECT JSON_ARRAYAGG(JSON_OBJECT('fimage', fimage )) from billing_details  where fimage != ' ' and   fidbilling = idbill and fdeleted=0 ) ;



RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURNproducts_extra` */;
DELIMITER ;;
CREATE  FUNCTION `RETURNproducts_extra`(`idproduct` bigint  ) RETURNS longtext CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result longtext  CHARSET utf8mb4;
      	
set Result=  (SELECT JSON_ARRAYAGG(JSON_OBJECT('fkey', fkey , 'fval' , fval )) from products_extra  where    fproduct_id = idproduct  ) ;



RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURNproducts_varients_extra` */;
DELIMITER ;;
CREATE  FUNCTION `RETURNproducts_varients_extra`(`idvarient` bigint  ) RETURNS longtext CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result longtext  CHARSET utf8mb4;
      	
set Result=  (SELECT JSON_ARRAYAGG(JSON_OBJECT('fkey', fkey , 'fval' , fval )) from products_varients_extra  where    fproduct_varient_id = idvarient  ) ;



RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `returnrate_like_dislike` */;
DELIMITER ;;
CREATE  FUNCTION `returnrate_like_dislike`(f_status varchar(50) CHARSET utf8mb4 , f_idreview_and_rate bigint   ) RETURNS bigint(20)
BEGIN

DECLARE Result bigint;
      	
set Result=  (select count(*) from  tbl_review_and_rate_like_dislike  where fstatus = f_status  and  fidreview_and_rate = f_idreview_and_rate )    ;

 

RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `returnrate_like_dislike_questions` */;
DELIMITER ;;
CREATE  FUNCTION `returnrate_like_dislike_questions`(f_status varchar(50)  , f_idquestions bigint   ) RETURNS bigint(20)
BEGIN

DECLARE Result bigint;
      	
set Result=  (select count(*) from  questions_like_dislike  where fstatus = f_status  and  fidquestions = f_idquestions )    ;

 

RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURNSTOCK_QUANTITY` */;
DELIMITER ;;
CREATE  FUNCTION `RETURNSTOCK_QUANTITY`(`i_dproduct` bigint ,  `f_stock_quantity` bigint ) RETURNS bigint(20)
BEGIN
    DECLARE Result BIGINT;
    SELECT MAX(fstock_quantity)
    INTO Result
    FROM products_varients
    WHERE fidproduct = i_dproduct
      AND fdeleted = 0
      AND fManage_stock_quantity = 1;
    RETURN IFNULL(Result, 0);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_BRANDIMAGEBYID` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_BRANDIMAGEBYID`(f_id bigint    ) RETURNS varchar(2050) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result varchar(2050);
      	
set Result=  (select   fimages  from  product_brand   where  id= f_id   )   ;

 

RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_BRANDNAMEBYID` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_BRANDNAMEBYID`(f_id bigint    ) RETURNS varchar(2050) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result varchar(2050) CHARSET utf8mb4 ;
      	
set Result=  (select  fname   from  product_brand   where  id = f_id and fdeleted= 0 and factive = 1   )   ;

 

RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_CARRIERNAMEBYID` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_CARRIERNAMEBYID`(f_id varchar(2050) CHARSET utf8mb4    ) RETURNS longtext CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
    DECLARE Result LONGTEXT CHARSET utf8mb4;
    
    IF LENGTH(f_id) > 0 THEN
        SET Result = (
            SELECT JSON_ARRAYAGG(
                JSON_OBJECT(
                    'id', id,
                    'factive', factive,
                    'fextra', fextra,
                    'fname', fname,
                    'fimages', fimages,
                    'fidstore', fidstore,
                    'storeName', RETURN_STORENAMEBYID(fidstore)
                )
            ) AS CARRIERS
            FROM billcarriermethods
            WHERE FIND_IN_SET(id, f_id)
              AND fdeleted = 0
        );
    ELSE
        SET Result = NULL;
    END IF;
    
    RETURN Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_CATEGURY_ALL_CHILDS_IDS_STR` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_CATEGURY_ALL_CHILDS_IDS_STR`(fid_catag bigint , f_type varchar (200) CHARSET utf8mb4   ) RETURNS varchar(2000) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
    DECLARE Result VARCHAR(2000) CHARSET utf8mb4;
    
    IF f_type != 'product' THEN 
        RETURN NULL;
    END IF;
    
    WITH RECURSIVE category_tree AS (
        SELECT id
        FROM postscatag
        WHERE id = fid_catag
        UNION ALL
        SELECT p.id
        FROM postscatag p
        INNER JOIN category_tree ct ON ct.id = p.fparent
    )
    SELECT GROUP_CONCAT(id) INTO Result
    FROM category_tree;
    
    RETURN IFNULL(Result, '');
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_CATEGURY_CHILDS_STR_ID` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_CATEGURY_CHILDS_STR_ID`(fid_catag bigint    ) RETURNS varchar(2000) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
    DECLARE Result VARCHAR(2000) CHARSET utf8mb4;
    DECLARE done INT DEFAULT 0;
    DECLARE catag_id BIGINT;
    DECLARE parent_id BIGINT;
    DECLARE cur CURSOR FOR 
        SELECT id FROM postscatag WHERE id = fid_catag
        UNION ALL
        SELECT parent_id FROM (
            SELECT @r AS catag_id, 
                   (SELECT @r := fparent FROM postscatag WHERE id = catag_id) AS parent_id, 
                   @l := @l + 1 AS level 
            FROM (SELECT @r := fid_catag, @l := 0) val, postscatag 
            WHERE @r <> 0
        ) AS tbl;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    SET Result = '';
    OPEN cur;
    read_loop: LOOP
        FETCH cur INTO catag_id;
        IF done THEN
            LEAVE read_loop;
        END IF;
        SET Result = CONCAT(Result, ',', catag_id);
    END LOOP;
    CLOSE cur;

    RETURN IFNULL(TRIM(BOTH ',' FROM Result), '0');
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_CATEGURY_PARENTS_STR` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_CATEGURY_PARENTS_STR`(fid_catag bigint    ) RETURNS varchar(2000) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
    DECLARE Result VARCHAR(2000) CHARSET utf8mb4;
    DECLARE RootCatag VARCHAR(2000) CHARSET utf8mb4;

    
    SELECT fname INTO RootCatag 
    FROM postscatag 
    WHERE id = fid_catag 
    LIMIT 1;

    
    SET Result = (
        SELECT GROUP_CONCAT(DISTINCT parent_name ORDER BY level SEPARATOR ' / ')
        FROM (
            SELECT @r AS catag_id, 
                   (SELECT @r := fparent FROM postscatag WHERE id = catag_id) AS parent_id, 
                   (SELECT @n := fname FROM postscatag WHERE id = catag_id) AS parent_name, 
                   @l := @l + 1 AS level 
            FROM (SELECT @r := fid_catag, @l := 0) val, postscatag 
            WHERE @r <> 0
        ) AS tbl
    );

    
    IF Result IS NULL THEN
        SET Result = RootCatag;
    ELSE
        SET Result = CONCAT(RootCatag, ' / ', Result);
    END IF;

    RETURN Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_CATEGURY_PRODUCT_IMAGE` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_CATEGURY_PRODUCT_IMAGE`(fid_catag BIGINT, f_type VARCHAR(200) CHARSET utf8mb4) RETURNS varchar(2000) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
    DECLARE Result VARCHAR(2000) CHARSET utf8mb4;
    DECLARE childs VARCHAR(2000) CHARSET utf8mb4;


   

    RETURN IFNULL(Result, '');
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `return_full_address_from_webuser_bill_address` */;
DELIMITER ;;
CREATE  FUNCTION `return_full_address_from_webuser_bill_address`(`i_d` bigint  ) RETURNS varchar(3500) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result  varchar(3500) CHARSET utf8mb4;
      	
set Result=  (select  concat( ostan.title , "/ شهر:", city.title , "/ خیابان:" ,addr.fstreet  , "/ پلاک:" ,addr.fplak , "/ واحد:" ,addr.fvahed , "/ کدپستی:" ,addr.fpostalcode 
, "/ گیرنده:" , addr.fname , " " , addr.flastname , "/ موبایل:" ,addr.fmobile )  as fullAddress  from webuser_bill_address as addr inner 
      join province_cities as city on city.id = addr.fid_province_cities inner join province_cities as ostan 
      on ostan.id = city.parent  where     addr.id= i_d  ) ;


RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_MARSOLE_REAL_STATUS_STR` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_MARSOLE_REAL_STATUS_STR`(fid_Marsole bigint    ) RETURNS varchar(2000) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
DECLARE Result  varchar(2000) CHARSET utf8mb4;


  set Result =  ( SELECT    GROUP_CONCAT( md.fstatus  SEPARATOR ', ') as AllStatus  from  ( SELECT     md.fstatus    from  billing_marsole_details as md 
      inner join billing_details as bd on bd.id = md.fidbilling_details
    where md.fidmarsole = fid_Marsole  group by md.fstatus  )  as md ) ;
 
if Result is null then
set Result =  'NAn' ;
end if ;



RETURN Result ;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_MARSOLE_SEND_INFO` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_MARSOLE_SEND_INFO`(fid_Marsole bigint    ) RETURNS varchar(2000) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
DECLARE Result  varchar(2000) CHARSET utf8mb4;


  set Result =  ( SELECT JSON_ARRAYAGG(JSON_OBJECT('fsendedDate', fsendedDate, 'id', id , 'fsendeInfo',fsendeInfo, 'fstatus',fstatus)) as AllfsendedDate
      from  (   SELECT   distinct  mahmole.fstatus , mahmole.fsendedDate , mahmole.id  , mahmole.fsendeInfo   from billing_sellers_mahmole   as mahmole 
      inner join  billing_sellers_mahmole_details as mahmoleD on mahmoleD.fidmahmole = mahmole.id
      inner join  billing_marsole_details  as marsoleD on marsoleD.fidmahmole_details  = mahmoleD.id
      where marsoleD.fidmarsole =  fid_Marsole  group by mahmole.id  )  as md ) ;
 
if Result is null then
set Result =  'NAn' ;
end if ;



RETURN Result ;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_PRODUCT_COLORS` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_PRODUCT_COLORS`(f_idproduct bigint   ) RETURNS longtext CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
    DECLARE Result LONGTEXT CHARSET utf8mb4;

    
    IF EXISTS (
        SELECT 1 
        FROM product_attribute pa 
        WHERE pa.idproduct = f_idproduct 
          AND pa.fview_mode = 'color'
    ) THEN
        
        SELECT JSON_ARRAYAGG(JSON_OBJECT(
            'id', pav.id,
            'fvalue', pav.fvalue,
            'fdesc', pav.fdesc
        )) INTO Result
        FROM product_attribute pa
        JOIN product_attribute_variant pav ON pav.fidproduct_attribute = pa.id
        WHERE pa.idproduct = f_idproduct 
          AND pa.fview_mode = 'color'
          AND pa.fenable_variation = 1;
    ELSE
        SET Result = '';
    END IF;

    RETURN Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_PRODUCT_COMISSION_SELLER` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_PRODUCT_COMISSION_SELLER`(f_idproduct bigint  , f_idStore  int  ) RETURNS int(5)
BEGIN
    DECLARE Result INT(5);

    
    SELECT fcomissionP INTO Result 
    FROM stores 
    WHERE id = f_idStore 
    LIMIT 1;

    IF Result IS NOT NULL AND Result > 0 THEN
        RETURN Result;
    END IF;

    
    SELECT fcomissionP INTO Result 
    FROM products 
    WHERE id = f_idproduct 
    LIMIT 1;

    IF Result IS NOT NULL AND Result > 0 THEN
        RETURN Result;
    END IF;

    
    SELECT fcomissionP INTO Result 
    FROM postscatag 
    WHERE id = (SELECT IFNULL(fidCateg, 0) FROM products WHERE id = f_idproduct) 
    LIMIT 1;

    IF Result IS NOT NULL AND Result > 0 THEN
        RETURN Result;
    END IF;

    RETURN IFNULL(Result, 0);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_PRODUCT_COMISSION_SELLER_TABLE` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_PRODUCT_COMISSION_SELLER_TABLE`(f_idproduct bigint  , f_idStore  int  ) RETURNS varchar(550) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
    DECLARE Result VARCHAR(550)  CHARSET utf8mb4;

    
    SELECT fcomissionP INTO Result 
    FROM stores 
    WHERE id = f_idStore 
    LIMIT 1;

    IF Result IS NOT NULL AND Result > 0 THEN
        RETURN "stores";
    END IF;

    
    SELECT fcomissionP INTO Result 
    FROM products 
    WHERE id = f_idproduct 
    LIMIT 1;

    IF Result IS NOT NULL AND Result > 0 THEN
        RETURN    "products";
    END IF;

    
    SELECT fcomissionP INTO Result 
    FROM postscatag 
    WHERE id = (SELECT IFNULL(fidCateg, 0) FROM products WHERE id = f_idproduct) 
    LIMIT 1;

    IF Result IS NOT NULL AND Result > 0 THEN
        RETURN    "category";
    END IF;

    RETURN IFNULL("", 0);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_PRODUCT_IN_ORDER_COUNT` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_PRODUCT_IN_ORDER_COUNT`(f_idproduct bigint    ) RETURNS bigint(20)
BEGIN

DECLARE Result bigint;
      	
set Result=  (SELECT   sum(fcount ) from  billing_details where fidproduct=f_idproduct and fstatus = 'AwaitingPayment' and fdeleted = 0   )    ;

 

RETURN ifnull(Result , 0 ) ;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_PRODUCT_PRICEUNIT` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_PRODUCT_PRICEUNIT`(f_idproduct bigint  , f_is_amazing  int  ) RETURNS bigint(20)
BEGIN
    DECLARE Result BIGINT DEFAULT 0;
    DECLARE Result_1 BIGINT DEFAULT 0;
    DECLARE var_foff INT;
    DECLARE var_amazing_foff INT;
    DECLARE var_fprice INT;
    DECLARE var_fronding INT;
    DECLARE var_amazing_startDate DATETIME;
    DECLARE var_amazing_endDate DATETIME;
    DECLARE var_fManage_stock_quantity INT;
    DECLARE var_fstock_quantity INT;
    DECLARE var_instock INT DEFAULT 0;

    
    SELECT fManage_stock_quantity, IFNULL(fstock_quantity, 0), IFNULL(fronding, 0), IFNULL(foff, 0), IFNULL(fprice, 0),
           IFNULL(STR_TO_DATE(amazing_startDate, '%Y-%m-%d %H:%i:%s'), NULL), IFNULL(STR_TO_DATE(amazing_endDate, '%Y-%m-%d %H:%i:%s'), NULL), IFNULL(amazing_foff, 0)
    INTO var_fManage_stock_quantity, var_fstock_quantity, var_fronding, var_foff, var_fprice, var_amazing_startDate, var_amazing_endDate, var_amazing_foff
    FROM products_varients
    WHERE id = f_idproduct;

    
    IF (var_fManage_stock_quantity = 1 AND var_fstock_quantity > 0) OR (var_fManage_stock_quantity = 0 OR var_fManage_stock_quantity IS NULL) THEN
        SET var_instock = 1;
    END IF;

    IF var_instock = 0 THEN
        RETURN NULL;
    END IF;

    
    SET Result_1 = ROUND((var_fprice - (var_fprice * (var_foff / 100))), 0);

    
    IF f_is_amazing = 1 THEN
        IF var_amazing_foff > 0 AND var_amazing_endDate IS NOT NULL AND var_amazing_startDate IS NOT NULL THEN
            IF var_amazing_endDate > var_amazing_startDate AND TIMESTAMPDIFF(MINUTE, NOW(), var_amazing_endDate) > 1 THEN
                SET Result_1 = ROUND((var_fprice - (var_fprice * (var_amazing_foff / 100))), 0);
            END IF;
        END IF;
    END IF;

    
    IF Result_1 - var_fronding >= 1000 THEN
        SET Result_1 = Result_1 - var_fronding;
    END IF;

    SET Result = Result_1;

    RETURN IFNULL(Result, 0);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_PRODUCT_SELL_COUNT` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_PRODUCT_SELL_COUNT`(f_idproduct bigint    ) RETURNS bigint(20)
BEGIN

DECLARE Result bigint;
      	
set Result=  (SELECT   sum(fcount ) from  billing_details where fidproduct=f_idproduct and fstatus = 'Completed' and fdeleted = 0   )    ;

 

RETURN ifnull(Result , 0 ) ;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `RETURN_PRODUCT_VARIENTJSON` */;
DELIMITER ;;
CREATE  FUNCTION `RETURN_PRODUCT_VARIENTJSON`(f_idproduct bigint    ) RETURNS longtext CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
    DECLARE Result LONGTEXT CHARSET utf8mb4;

    
    SELECT JSON_ARRAYAGG(
        JSON_OBJECT(
            'id', id, 
            'factive', factive, 
            'fprice', fprice, 
            'fcanShappingBySeller', fcanShappingBySeller,
            'fcanShappingByMainStore', fcanShappingByMainStore, 
            'fManage_stock_quantity', fManage_stock_quantity, 
            'fstock_quantity', fstock_quantity
        )
    ) INTO Result
    FROM products_varients 
    WHERE fidproduct = f_idproduct 
      AND fdeleted = 0 
    ORDER BY fprice DESC;

    RETURN Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `return_storeIdByWebuserId` */;
DELIMITER ;;
CREATE  FUNCTION `return_storeIdByWebuserId`(f_idwebuser bigint    ) RETURNS int(11)
BEGIN

DECLARE Result  int(11);
      	
set Result=  (select  id  from  stores   where  fidwebuser= f_idwebuser   )   ;

 

RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `return_STORENAMEById` */;
DELIMITER ;;
CREATE  FUNCTION `return_STORENAMEById`(f_idStore bigint    ) RETURNS varchar(250) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN
    DECLARE Result VARCHAR(50) CHARSET utf8mb4;
    
    SELECT IFNULL(fnicname, fname) INTO Result
    FROM stores
    WHERE id = f_idStore;
    
    RETURN IFNULL(Result, '---');
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `return_userFullNameById` */;
DELIMITER ;;
CREATE  FUNCTION `return_userFullNameById`(f_idwebuser bigint    ) RETURNS varchar(250) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result varchar(50)  CHARSET utf8mb4;
      	
set Result=  (select  concat( FldName , ' ' ,FldLastName )  from  tblwebusers   where  FldId= f_idwebuser   )   ;

 

RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `return_USernameById` */;
DELIMITER ;;
CREATE  FUNCTION `return_USernameById`(f_idwebuser bigint    ) RETURNS varchar(250) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result varchar(50)  CHARSET utf8mb4;
      	
set Result=  (select  FldUsername    from  tblwebusers   where  FldId= f_idwebuser   )   ;

 

RETURN  ifnull( Result , "---") ;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `return_user_status_rate_like_dislike` */;
DELIMITER ;;
CREATE  FUNCTION `return_user_status_rate_like_dislike`(f_idwebuser bigint ,  f_idreview_and_rate bigint   ) RETURNS varchar(50) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result varchar(50);
      	
set Result=  (select fstatus from  tbl_review_and_rate_like_dislike  where fidwebuser = f_idwebuser  and  fidreview_and_rate = f_idreview_and_rate )    ;

 

RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `return_user_status_rate_like_dislike_questions` */;
DELIMITER ;;
CREATE  FUNCTION `return_user_status_rate_like_dislike_questions`(f_idwebuser bigint ,  f_idquestions bigint   ) RETURNS varchar(50) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
BEGIN

DECLARE Result varchar(50);
      	
set Result=  (select fstatus from  questions_like_dislike  where fidwebuser = f_idwebuser  and  fidquestions = f_idquestions )    ;

 

RETURN  Result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `SPLIT_STR` */;
DELIMITER ;;
CREATE  FUNCTION `SPLIT_STR`(id_list VARCHAR(2000)  CHARSET utf8mb4, delimeter VARCHAR(20)  CHARSET utf8mb4, position INT) RETURNS varchar(10) CHARSET utf8mb4 COLLATE utf8mb4_general_ci
    DETERMINISTIC
BEGIN
    RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(id_list, delimeter, position),
                             LENGTH(SUBSTRING_INDEX(id_list, delimeter, position - 1)) + 1),
                   delimeter, '');
  END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_gdmarray` */;
DELIMITER ;;
CREATE  FUNCTION `_gdmarray`(`m` SMALLINT) RETURNS smallint(6)
    READS SQL DATA
    DETERMINISTIC
BEGIN




	CASE m
		WHEN 0 THEN RETURN 31;
		WHEN 1 THEN RETURN 28;
		WHEN 2 THEN RETURN 31;
		WHEN 3 THEN RETURN 30;
		WHEN 4 THEN RETURN 31;
		WHEN 5 THEN RETURN 30;
		WHEN 6 THEN RETURN 31;
		WHEN 7 THEN RETURN 31;
		WHEN 8 THEN RETURN 30;
		WHEN 9 THEN RETURN 31;
		WHEN 10 THEN RETURN 30;
		WHEN 11 THEN RETURN 31;
	END CASE;

END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_gdmarray2` */;
DELIMITER ;;
CREATE  FUNCTION `_gdmarray2`(`m` SMALLINT, `k` SMALLINT) RETURNS smallint(6)
    READS SQL DATA
    DETERMINISTIC
BEGIN




	CASE m
		WHEN 0 THEN RETURN 31;
		WHEN 1 THEN RETURN 28+k;
		WHEN 2 THEN RETURN 31;
		WHEN 3 THEN RETURN 30;
		WHEN 4 THEN RETURN 31;
		WHEN 5 THEN RETURN 30;
		WHEN 6 THEN RETURN 31;
		WHEN 7 THEN RETURN 31;
		WHEN 8 THEN RETURN 30;
		WHEN 9 THEN RETURN 31;
		WHEN 10 THEN RETURN 30;
		WHEN 11 THEN RETURN 31;
	END CASE;


END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_jdmarray` */;
DELIMITER ;;
CREATE  FUNCTION `_jdmarray`(`m` SMALLINT) RETURNS smallint(6)
    READS SQL DATA
    DETERMINISTIC
BEGIN




	CASE m
		WHEN 0 THEN RETURN 31;
		WHEN 1 THEN RETURN 31;
		WHEN 2 THEN RETURN 31;
		WHEN 3 THEN RETURN 31;
		WHEN 4 THEN RETURN 31;
		WHEN 5 THEN RETURN 31;
		WHEN 6 THEN RETURN 30;
		WHEN 7 THEN RETURN 30;
		WHEN 8 THEN RETURN 30;
		WHEN 9 THEN RETURN 30;
		WHEN 10 THEN RETURN 30;
		WHEN 11 THEN RETURN 29;
	END CASE;

END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_jdmarray2` */;
DELIMITER ;;
CREATE  FUNCTION `_jdmarray2`(`m` SMALLINT) RETURNS smallint(6)
    READS SQL DATA
    DETERMINISTIC
BEGIN




	CASE m
		WHEN 1 THEN RETURN 31;
		WHEN 2 THEN RETURN 31;
		WHEN 3 THEN RETURN 31;
		WHEN 4 THEN RETURN 31;
		WHEN 5 THEN RETURN 31;
		WHEN 6 THEN RETURN 31;
		WHEN 7 THEN RETURN 30;
		WHEN 8 THEN RETURN 30;
		WHEN 9 THEN RETURN 30;
		WHEN 10 THEN RETURN 30;
		WHEN 11 THEN RETURN 30;
		WHEN 12 THEN RETURN 29;
	END CASE;

END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `__mydiv` */;
DELIMITER ;;
CREATE  FUNCTION `__mydiv`(`a` INT, `b` INT) RETURNS bigint(20)
    READS SQL DATA
    DETERMINISTIC
BEGIN




	return FLOOR(a / b);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `__mymod` */;
DELIMITER ;;
CREATE  FUNCTION `__mymod`(`a` INT, `b` INT) RETURNS bigint(20)
    READS SQL DATA
    DETERMINISTIC
BEGIN




	return (a - b * FLOOR(a / b));
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `clearAllData` */;
DELIMITER ;;
CREATE  PROCEDURE `clearAllData`()
BEGIN
 SET FOREIGN_KEY_CHECKS = 0;
delete  FROM  pages where   fauthor  != 'code-man'  ;
delete  FROM posts  where  fauthor  != 'code-man' ;
delete  FROM products    ;
delete  FROM postscatag  where   fauthor != 'code-man' ; 
delete  FROM tbl_faq   where   fauthor != 'code-man';
delete  FROM codemandata  where   fauthor != 'code-man';
delete  FROM codeman_messages   where   id > 1;
  delete from _portalsassions ; 
 delete from agis ; 
 delete from all_search_objects ; 
 delete from allsmssended ; 
 delete from billcarriermethods ; 
 delete from billcoupon ; 
 delete from billcoupon_used ; 
 delete from billing ; 
 delete from billing_details ; 
 delete from billing_state_history ; 
 delete from billpaymethods ; 
 delete from buy_basket ; 
 delete from buy_basket_next ; 
 delete from callerid_customers_gotodell ; 
 delete from cnntodb_settings ; 
 delete from codeman_tiketdetails ; 
 delete from codeman_tikets ; 
 delete from codeman_tiketstypes ; 
 delete from customers ; 
 delete from emailsend_settings ; 
 delete from excelemails_list ; 
 delete from factory_product ; 
 delete from general_components ; 
 delete from layouts_html ; 
 delete from lic ; 
 delete from logtable ; 
 delete from moduls ; 
 delete from modulssettings ; 
 delete from nobat_allnobats ; 
 delete from nobat_level1 ; 
 delete from nobat_level2_items ; 
 delete from nobat_level3_items ; 
 delete from nobat_level4_items ; 
 delete from nobat_logforallcalls ; 
 delete from nobat_usermanange ; 
 delete from orders ; 
 delete from post_comments ; 
 delete from product_allattribute ; 
 delete from product_attribute ; 
 delete from product_attribute_variant ; 
 delete from product_brand ; 
 delete from product_download_manager ; 
 delete from product_imagegallery ; 
 delete from products_log ; 
 delete from province_cities ; 
 delete from rating ; 
 delete from redirect_url_manager ; 
 delete from reports ; 
 delete from sendedemail ; 
 delete from sendedsms ; 
 delete from services ; 
 delete from tbl_demoreques ; 
 delete from tbl_forms ; 
 delete from tbl_forms_resuls ; 
 delete from tbl_review_and_rate ; 
 delete from tbl_review_and_rate_like_dislike ; 
 delete from tbl_unsubscribe ; 
 delete from tbl_utm ; 
 delete from tblholidays ; 
 delete from tblinstagram ; 
 delete from tblsounds ; 
 delete from tbluserlogininfo ; 
 delete from tblusers ; 
 delete from tblvoipserverinfo ; 
 delete from tblwebusers ; 
 delete from tempactivatecode ; 
 delete from transactions ; 
 delete from user_favorite ; 
 delete from visitors_search_history ; 
 delete from voip_man_lic_tmp ; 
 delete from wallet ; 
 delete from webuser_bill_address ; 

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `FillDataModulsById` */;
DELIMITER ;;
CREATE  PROCEDURE `FillDataModulsById`(IN `Fldid` INT)
BEGIN
SELECT * From  agis  where FldidModuls=Fldid  and flddeleted = 0 ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `getadmindashboardmsg` */;
DELIMITER ;;
CREATE  PROCEDURE `getadmindashboardmsg`()
BEGIN
 
  SELECT  * from    codeman_messages   where  fdeleted=0 and  factive =1  ;  


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `log_msg` */;
DELIMITER ;;
CREATE  PROCEDURE `log_msg`(IN `msg` VARCHAR(255) CHARSET utf8mb4)
BEGIN
 insert into logtable select 0, msg;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `ProductForAddViewBasket` */;
DELIMITER ;;
CREATE  PROCEDURE `ProductForAddViewBasket`(
IN f_count int ,
IN f_id  bigint
 )
BEGIN
 
  select  v.id ,
       p.fname ,
       v.fprice ,
      ROUND(( v.fprice  - ( v.fprice  * ( foff  / 100))),
              0) AS  fpriceUnit ,
      (ROUND(( v.fprice  - ( v.fprice  * ( foff  / 100))),
              0) *  f_count ) AS  fpriceAll ,  p.fimages ,
      v.factive ,
       v.foff ,
       v.fdate_update_price ,
       v.finserttime ,  p.fidCateg ,
       p.fkeys ,
       p.ftype 
       
       
 FROM products as p  inner join products_varients as v  on v.fidproduct  = p.id 
  WHERE
  v.id  =  f_id ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `RemoveProduct` */;
DELIMITER ;;
CREATE  PROCEDURE `RemoveProduct`(IN idProduct BIGINT)
BEGIN

    
    DECLARE orderCount INT;
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN 
        
        ROLLBACK; 
    END;



    outer_block: BEGIN
        
        SELECT IFNULL(COUNT(*), 0) INTO orderCount FROM billing_details WHERE fparent = idProduct;

        
        IF orderCount > 0 THEN
            LEAVE outer_block;
        END IF;

        
        START TRANSACTION;

        
        CALL RemoveProductVarients(idProduct, NULL);

        
        DELETE FROM products WHERE id = idProduct;

        
        DELETE FROM products_extra WHERE fproduct_id NOT IN (SELECT id FROM products);

        
        DELETE FROM all_search_objects WHERE ftype = 'product' AND fobjid NOT IN (SELECT id FROM products);

        
        DELETE FROM all_extra WHERE ftype = 'product' AND frefid NOT IN (SELECT id FROM products);

        
        DELETE FROM product_attribute_variant WHERE fidproduct_attribute IN (SELECT id FROM product_attribute WHERE idproduct NOT IN (SELECT id FROM products));

        
        DELETE FROM product_attribute WHERE idproduct NOT IN (SELECT id FROM products);

        
        DELETE FROM buy_basket WHERE idproduct NOT IN (SELECT id FROM products);

        
        DELETE FROM buy_basket_next WHERE idproduct NOT IN (SELECT id FROM products);

        
        DELETE FROM product_imagegallery WHERE idproduct NOT IN (SELECT id FROM products);

        
        DELETE FROM stores_request_sell_products WHERE fidproduct NOT IN (SELECT id FROM products);

        
        DELETE FROM webuser_seened WHERE fref NOT IN (SELECT id FROM products);

        
        DELETE FROM tbl_review_and_rate WHERE ftype = 'product' AND fiditem NOT IN (SELECT id FROM products);

        
        DELETE FROM tags_objects WHERE ftype = 'product' AND frefid NOT IN (SELECT id FROM products);

        
        DELETE FROM tbl_review_and_rate_like_dislike WHERE fidreview_and_rate NOT IN (SELECT id FROM tbl_review_and_rate);

        
        COMMIT;
    END outer_block;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `RemoveProductVarients` */;
DELIMITER ;;
CREATE  PROCEDURE `RemoveProductVarients`(
    IN idProduct BIGINT,
    IN idProductVarient BIGINT
)
BEGIN
    DECLARE orderCount INT;
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN 
        
        ROLLBACK; 
    END;

    


    outer_block: BEGIN
        
        IF idProduct IS NOT NULL THEN
            
            SELECT IFNULL(COUNT(*), 0) INTO orderCount FROM billing_details WHERE fparent = idProduct;

            
            IF orderCount > 0 THEN
                LEAVE outer_block;
            END IF;
        END IF;

        
        IF idProductVarient IS NOT NULL THEN
            
            SELECT IFNULL(COUNT(*), 0) INTO orderCount FROM billing_details WHERE fidproduct = idProductVarient;

            
            IF orderCount > 0 THEN
                LEAVE outer_block;
            END IF;
        END IF;

        
        START TRANSACTION;

        IF idProduct IS NOT NULL THEN
            
            DELETE FROM products_varients WHERE fidproduct = idProduct;
        END IF;

        IF idProductVarient IS NOT NULL THEN
            
            DELETE FROM products_varients WHERE id = idProductVarient;
        END IF;

        
        DELETE FROM product_monitoring_err_log WHERE idvarient NOT IN (SELECT id FROM products_varients);

        
        DELETE FROM product_monitoring_log WHERE idvarient NOT IN (SELECT id FROM products_varients);

        
        DELETE FROM products_varients_pricechange WHERE 1>2  and  fidproduct_variant NOT IN (SELECT id FROM products_varients);

		  DELETE FROM products_varients_stockchange WHERE 1>2 and  fidproduct_variant NOT IN (SELECT id FROM products_varients);

        
        DELETE FROM products_varients_extra WHERE fproduct_varient_id NOT IN (SELECT id FROM products_varients);

        
        COMMIT;
    END outer_block;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPAdd_portalsassions` */;
DELIMITER ;;
CREATE  PROCEDURE `SPAdd_portalsassions`(
IN t_oken  longtext CHARSET utf8mb4, 
IN d_ata longtext CHARSET utf8mb4 ,
IN i_dwebuser bigint ,
in F_ldType varchar(45)  CHARSET utf8mb4,
IN f_mnulist  longtext CHARSET utf8mb4)
BEGIN

  DELETE FROM _portalsassions WHERE insertTime < (CURDATE() - INTERVAL 15 DAY);
  
   INSERT INTO   _portalsassions   (   token,  FldData , FldType , fmnulist , idwebuser)  VALUES 
 ( t_oken ,  d_ata ,F_ldType,fmnulist , i_dwebuser );   
  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SpAGIs_FillDataModulsById` */;
DELIMITER ;;
CREATE  PROCEDURE `SpAGIs_FillDataModulsById`(IN `Fldid` INT)
BEGIN
SELECT * From  agis  where FldidModuls=Fldid  and flddeleted = 0 ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPbillcoupon_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPbillcoupon_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
 IN `f_expireDate` VARCHAR(255) CHARSET utf8mb4, 
 IN `f_value` BIGINT,
 IN `f_min_Value` BIGINT, 
 IN `f_max_Value` BIGINT, 
 IN `f_General_limitation` BIGINT,
 IN `f_User_limitation` BIGINT, 
IN `f_type` VARCHAR(255) CHARSET utf8mb4, 
IN `f_desc` LONGTEXT CHARSET utf8mb4,
IN `f_extra` LONGTEXT CHARSET utf8mb4,
IN `f_is_amazing_no` TINYINT ,
IN `f_idwebuser_only` BIGINT, 
IN `f_idproduct_only` BIGINT, 
IN `f_idproduct_varient_only` BIGINT, 
IN `f_active` TINYINT
)
BEGIN

 

IF i_d > 0 THEN
       UPDATE billcoupon
            SET 
            fidproduct_varient_only=f_idproduct_varient_only ,  fidwebuser_only=f_idwebuser_only ,   fidproduct_only=f_idproduct_only ,  fname=f_name , factive=f_active,   fdesc=f_desc   , fextra=f_extra  ,fexpireDate=f_expireDate ,fvalue=f_value , fmin_Value=f_min_Value
                ,fmax_Value=f_max_Value , fis_amazing_no=f_is_amazing_no  , fUser_limitation=f_User_limitation  , fGeneral_limitation=f_General_limitation 
                  
         WHERE id = i_d ;
		 select i_d  as id;
  END IF;
  IF i_d = 0 THEN
              INSERT  INTO  billcoupon (fidproduct_varient_only , fidproduct_only,fidwebuser_only, fname  , factive ,   fdesc    , fextra ,ftype ,fexpireDate,fvalue ,fmin_Value ,fmax_Value ,fis_amazing_no,fUser_limitation ,fGeneral_limitation)
               VALUES (f_idproduct_varient_only , f_idproduct_only ,f_idwebuser_only ,f_name , f_active,      f_desc   , f_extra ,f_type , f_expireDate ,f_value ,f_min_Value ,f_max_Value ,f_is_amazing_no,f_User_limitation ,f_General_limitation) ;
    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPbilling_substatus_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPbilling_substatus_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(900) CHARSET utf8mb4, 
 
 IN `f_message` VARCHAR(1900) CHARSET utf8mb4, 
 
IN `f_active` TINYINT
)
BEGIN

declare co integer ;
       set   co  =  (select count(id ) as id   from billing_substatus where fname = f_name  ) ;
       
       if  co > 0  then
        set i_d =   (select  id       from billing_substatus where fname = f_name ) ;
       end if ;


  IF i_d > 0 THEN
      
   
       UPDATE billing_substatus
            SET 
                fname=f_name , factive=f_active , fmessage=f_message
                
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  billing_substatus (fname,   factive  ,fmessage)
               VALUES (f_name,  f_active       ,f_message ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPCarrierMethods_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPCarrierMethods_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
 
IN `f_type` VARCHAR(255) CHARSET utf8mb4, 
IN `f_desc` LONGTEXT CHARSET utf8mb4,
IN `f_extra` LONGTEXT CHARSET utf8mb4,
in f_idstore int,
IN `f_active` TINYINT
)
BEGIN

 

  IF i_d > 0 THEN
       UPDATE billcarriermethods
            SET 
                fname=f_name , factive=f_active,   fdesc=f_desc   , fextra=f_extra    , fidstore=f_idstore
                  
         WHERE id = i_d ;
		 select i_d  as id;
  END IF;
  IF i_d = 0 THEN
              INSERT  INTO  billcarriermethods ( fname  , factive ,   fdesc    , fextra ,ftype ,fidstore  )
               VALUES ( f_name , f_active,      f_desc   , f_extra ,f_type  ,f_idstore ) ;
    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPcustomers_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPcustomers_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
IN `f_lastname` VARCHAR(255) CHARSET utf8mb4,
IN `f_mobile` VARCHAR(255) CHARSET utf8mb4,
IN `f_address` VARCHAR(255) CHARSET utf8mb4, 
IN `f_email`   VARCHAR(400) CHARSET utf8mb4 ,
IN `f_username`   VARCHAR(400) CHARSET utf8mb4 ,  
IN `f_idWebuser`  bigint
)
BEGIN
 
 declare newid integer   ;
 set newid = (select ifnull(id , 0)  from customers where    ( length(fusername) > 3 and  fusername=f_username )     or  ( length(fmobile) > 10 and  fmobile=f_mobile )) ;
if   i_d = 0 and  newid > 0  then
    set i_d = newid ;
end if ;
if length(f_username)=0 or f_username = null  then
   if length(f_mobile)>10  and  f_mobile <> null  then
        set f_username = f_mobile ;
   end if;
end if;

  IF i_d > 0 THEN
				UPDATE  customers  SET 
                fname =f_name ,  flastname=f_lastname ,  fmobile=f_mobile , faddress = f_address, femail =f_email  , fusername=f_username 
                , fidWebuser=f_idWebuser
                WHERE id = i_d ;
			select i_d  as id;
  END IF;
  IF i_d = 0 THEN
				INSERT  INTO  customers  ( fname ,flastname ,fmobile , faddress,femail   , fusername     ,fidWebuser        )
                VALUES (  f_name ,f_lastname ,f_mobile , f_address,f_email , f_username ,f_idWebuser) ;
			SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPDashboardInfo` */;
DELIMITER ;;
CREATE  PROCEDURE `SPDashboardInfo`(IN `MODELVIEW`   VARCHAR(255) CHARSET utf8mb4)
BEGIN
declare countfaq int ;
declare count_deactive_posts int ;
declare countstores int ;
declare countusers int ;
declare countlevel1 int ;
declare countlevel2 int ;
declare countposts int ;
declare countproducts int ;
declare countOtherPages int ;
declare counttodaynobat int ;
declare countd_1obat int ;
declare countd_2obat int ;
declare countd_3obat int ;
declare countd_4obat int ;
declare countd_5obat int ;
declare countd_6obat int ;
declare countd_7obat int ;
declare counttoday_getednobat int ;
declare countd_1obat_getednobat int ;
declare lastcommens longtext ;
 declare activetikets int ; 
 declare actiQuestions int ;
  declare doingOrders int ;
  declare AwaitingPaymentOrders int ;
  declare AwaitingConfirmationOrders int ;
   declare newEXSUserReq int ;
  declare newReviewComments int ;

   declare newNotif int ;
    


   declare newSellerRequests int ;
  declare newSellerProductRequest int ;
declare learnvideos longtext ;
if MODELVIEW='website' then 
 

set counttodaynobat = -1 ;
set counttoday_getednobat =-1 ;
set countd_1obat_getednobat = -1 ;
set countd_1obat = -1 ;
set countd_2obat = -1 ;
set countd_3obat = -1 ;
set countd_4obat = -1 ;
set countd_5obat = -1 ;
set countd_6obat = -1 ;
set countd_7obat = -1 ;
set countproducts = ( select count(*) from  products where fdeleted =0  and ( ftype = 'v_product' or  ftype='s_product'));
set countposts = ( select count(*) from posts  where fdeleted =0  );
set countfaq = ( select count(*) from tbl_faq where fdeleted=0  );
set count_deactive_posts = ( SELECT  count(*)  FROM posts where factive =  0 and fdeleted = 0   );
set countstores = ( select count(*) from stores where fdeleted=0  );

set countusers = ( select count(*) from tblwebusers where FldDeleted=0  );
 set countOtherPages = ( select count(*) from pages where fdeleted=0  and ftype = 'others');  
set countlevel1 = -1 ;
set countlevel2 = -1 ;
set activetikets = ( select count(*)   from  codeman_tikets  where  factive!=10 );  
set actiQuestions = ( select count(*)   from  questions  where  fstatus="NEW" and fdeleted = 0 and fidref is not null  );  

set doingOrders =  (select count(*)   from   billing  where (fstatus = 'doing'  )  and  fdeleted=0) ; 
set AwaitingPaymentOrders =  (select count(*)   from   billing  where (  fstatus = 'AwaitingPayment')  and  fdeleted=0) ; 
set AwaitingConfirmationOrders =  (select count(*)   from   billing  where (  fstatus = 'AwaitingConfirmation')  and  fdeleted=0) ; 

set newEXSUserReq =  (select count(*)    from   external_stores_user_requests    where fstatus = 'waiting'  ) ; 

set newReviewComments = (select count(*) as  newReviewComments from  tbl_review_and_rate  where fstatus = '1' and  fdeleted=0) ;
set newNotif = (select count(*) as  newNotif from  notifs_to_webuser  where fstatus = 'NEW' and  fdeleted=0) ;

set newSellerProductRequest =  (select count(*)as  newSellerProductRequest  from  stores_request_sell_products     ) ;
set newSellerRequests = (select count(*)as newSellerRequests   from  stores where  fstatus ='New'  and fdeleted= 0    ) ;
set learnvideos = (  SELECT JSON_ARRAYAGG(JSON_OBJECT('fname', fname , 'furl',  furl )) as learnvideos from   codemandata  where ftype='videoLearn-website');     
set lastcommens = -1 ; 
    
   
 
   
   select  count_deactive_posts,doingOrders, newEXSUserReq ,AwaitingPaymentOrders ,AwaitingConfirmationOrders,  newReviewComments,newNotif,newSellerProductRequest,newSellerRequests,  countfaq ,countstores, countusers, countlevel1 , countlevel2 ,countposts ,countproducts,counttodaynobat ,countd_1obat,countd_2obat,countd_3obat,countd_4obat,countd_5obat
   ,countd_6obat, countd_7obat , counttoday_getednobat ,countd_1obat_getednobat , lastcommens ,learnvideos  ,countOtherPages ,activetikets , actiQuestions  ;
   
   
elseif MODELVIEW='nobat' then 
set actiQuestions = ( select count(*) as actiQuestions  from  questions  where  fstatus="NEW" and fdeleted = 0 and fidref is not null  );    
set activetikets = ( select count(*) as activetikets from  codeman_tikets  where  factive!=10 );  
set counttodaynobat = ( SELECT count(*) FROM nobat_allnobats where FldDate =DATE(now()) and    FldDeleted=0  and FldActive=1  );
set counttoday_getednobat = ( SELECT count(*) FROM nobat_allnobats where FldDate =DATE(now()) and  FldIdCustomer>0 and   FldDeleted=0  and FldActive=1  );
set countd_1obat_getednobat = ( SELECT count(*) FROM nobat_allnobats where FldDate = DATE(  DATE_ADD(now(), INTERVAL 1 DAY)) and  FldIdCustomer>0 and   FldDeleted=0  and FldActive=1  );
set countd_1obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 1 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_2obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 2 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_3obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 3 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_4obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 4 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_5obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 5 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_6obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 6 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_7obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 7 DAY))   and    FldDeleted=0  and FldActive=1  );
set countproducts = -1;
set countposts = ( select count(*) from posts  where fdeleted =0  );
set countlevel1 = ( select count(*) from nobat_level1 where FldDeleted =0  );
set countlevel2 = ( select count(*) from nobat_level2_items where FldDeleted=0  );
set count_deactive_posts = ( SELECT  count(*)  FROM posts where factive =  0 and fdeleted = 0   );
set countfaq = -1;
set countstores = -1;
set countusers = ( select count(*) from tblwebusers where FldDeleted=0  );
set doingOrders = -1 ; 
set AwaitingPaymentOrders = -1 ; 
set AwaitingConfirmationOrders = -1 ; 
set  newEXSUserReq = -1 ; 
set newReviewComments = -1 ; 
set newNotif = -1 ; 

set newSellerProductRequest = -1 ; 
set newSellerRequests = -1 ; 
set learnvideos = (  SELECT JSON_ARRAYAGG(JSON_OBJECT('fname', fname , 'furl',  furl )) as learnvideos from   codemandata  where ftype='videoLearn-nobat');     
set lastcommens = (  SELECT JSON_ARRAYAGG(JSON_OBJECT('FldRate', FldRate , 'FldSuggest',  FldSuggest, 'FldComment',  FldComment )) as lastcommens from rating   );   
    
set countOtherPages = -1 ;    
  
   
   select count_deactive_posts,doingOrders , AwaitingPaymentOrders, AwaitingConfirmationOrders,  newReviewComments,newNotif,newSellerProductRequest,newSellerRequests, countfaq  ,countstores, newEXSUserReq , countusers , countlevel1 , countlevel2 ,countposts ,countproducts,counttodaynobat ,countd_1obat,countd_2obat,countd_3obat,countd_4obat,countd_5obat
   ,countd_6obat, countd_7obat , counttoday_getednobat ,countd_1obat_getednobat , lastcommens ,learnvideos ,countOtherPages  , activetikets , actiQuestions ;
   
 else 
   
 set actiQuestions = ( select count(*) as actiQuestions  from  questions  where  fstatus="NEW" and fdeleted = 0 and  fidref is not null  );   
set activetikets = ( select count(*) as activetikets from  codeman_tikets  where  factive!=10 );  
set counttodaynobat = ( SELECT count(*) FROM nobat_allnobats where FldDate =DATE(now()) and    FldDeleted=0  and FldActive=1  );
set counttoday_getednobat = ( SELECT count(*) FROM nobat_allnobats where FldDate =DATE(now()) and  FldIdCustomer>0 and   FldDeleted=0  and FldActive=1  );
set countd_1obat_getednobat = ( SELECT count(*) FROM nobat_allnobats where FldDate = DATE(  DATE_ADD(now(), INTERVAL 1 DAY)) and  FldIdCustomer>0 and   FldDeleted=0  and FldActive=1  );
set countd_1obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 1 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_2obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 2 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_3obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 3 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_4obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 4 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_5obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 5 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_6obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 6 DAY))   and    FldDeleted=0  and FldActive=1  );
set countd_7obat = ( SELECT count(*) FROM nobat_allnobats where FldDate =   DATE(  DATE_ADD(now(), INTERVAL 7 DAY))   and    FldDeleted=0  and FldActive=1  );
 
 
set countlevel1 = ( select count(*) from nobat_level1 where FldDeleted =0  );
set countlevel2 = ( select count(*) from nobat_level2_items where FldDeleted=0  );
  set   newEXSUserReq = -1 ; 
  set  doingOrders = -1 ; 
   set  AwaitingPaymentOrders = -1 ;  
   set  AwaitingConfirmationOrders = -1 ; 
set newReviewComments = -1 ; 
set newNotif = -1 ; 
set newSellerProductRequest = -1 ; 
set newSellerRequests = -1 ; 

   set countproducts = ( select count(*) from  products where fdeleted =0  );
set countposts = ( select count(*) from posts  where fdeleted =0  );
set countfaq = ( select count(*) from tbl_faq where fdeleted=0  );
set count_deactive_posts = ( SELECT  count(*)  FROM posts where factive =  0 and fdeleted = 0   );
set countstores = ( select count(*) from stores where fdeleted=0  );
set countusers = ( select count(*) from tblwebusers where FldDeleted=0  );
 set countOtherPages = ( select count(*) from pages where fdeleted=0  and ftype = 'others');  
 
 
 
set learnvideos = (  SELECT JSON_ARRAYAGG(JSON_OBJECT('fname', fname , 'furl',  furl )) as learnvideos from   codemandata  );     
set lastcommens = (  SELECT JSON_ARRAYAGG(JSON_OBJECT('FldRate', FldRate , 'FldSuggest',  FldSuggest, 'FldComment',  FldComment )) as lastcommens from rating   );   
    
set countOtherPages = -1 ;    
  
   
   select count_deactive_posts,doingOrders , AwaitingPaymentOrders, AwaitingConfirmationOrders ,newReviewComments,newNotif,newSellerProductRequest,newSellerRequests, countfaq , countstores , newEXSUserReq , countusers, countlevel1 , countlevel2 ,countposts ,countproducts,counttodaynobat ,countd_1obat,countd_2obat,countd_3obat,countd_4obat,countd_5obat
   ,countd_6obat, countd_7obat , counttoday_getednobat ,countd_1obat_getednobat , lastcommens ,learnvideos ,countOtherPages ,activetikets , actiQuestions ;
   
   end if;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPDashboardInfoLevel1` */;
DELIMITER ;;
CREATE  PROCEDURE `SPDashboardInfoLevel1`(IN `F_ldId` INT )
BEGIN
declare countfaq int ;
declare countposts int ;
declare countproducts int ;
  declare activetikets int ;
declare counttoday_getednobat int ;
declare countd_1obat_getednobat int ;




set activetikets = 0 ; 
set counttoday_getednobat = ( SELECT count(*) FROM nobat_allnobats where FldDate =DATE(now()) and  FldidLastLevel =F_ldId  and   FldDeleted=0  and FldActive=1  );
set countd_1obat_getednobat = ( SELECT count(*) FROM nobat_allnobats where FldDate = DATE(  DATE_ADD(now(), INTERVAL 1 DAY)) and  FldidLastLevel =  F_ldId  and   FldDeleted=0  and FldActive=1  );
set countproducts = ( select count(*) from  products where fdeleted =0  );
set countposts = ( select count(*) from posts  where fdeleted =0  );
set countfaq = ( select count(*) from tbl_faq where fdeleted=0  );

 
    
 select  countfaq , countposts ,countproducts,  counttoday_getednobat ,countd_1obat_getednobat , activetikets   ;
 
 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPDashboardInfoSeller` */;
DELIMITER ;;
CREATE  PROCEDURE `SPDashboardInfoSeller`(IN `i_dStore` INT ,  IN `i_WebUser` INT )
BEGIN
 
declare countproducts int ;
declare countRequestedproducts int ;
declare countNewMessages int ;
declare countNewOrderToCustomer int ;
declare countNewOrderToMainStore int ;
declare activetikets int ;
    
 
set countproducts = (  select count(*) 
 from  products as p  inner join products_varients as v  on p.id = v.fidproduct
 where v.fidstore = i_dStore  and     p.fdeleted =0 and  v.fdeleted =0  and ( p.ftype = 'v_product' or  p.ftype='s_product'));
 
 
 set countRequestedproducts = ( select count(*) from  stores_request_sell_products  where fdeleted =0  and  fidstore = i_dStore);
 
set countNewMessages = ( select count(*) from  store_sellers_messages  where fdeleted =0 and idStore =i_dStore  and  factive = 1 );

 set activetikets =   ( select count(*) as activetikets from  codeman_tikets  where  factive!=10  and fuserId= i_WebUser );   
 
set countNewOrderToCustomer =    (  select count(*)
             from billing_marsole  as bm   
                     inner join billing as b on b.id = bm.fidbilling
                     inner join stores as s on s.id = bm.fidstore_sender
                      where bm.fdeleted=0   and bm.fidstore_sender <> 1 and b.fstatus  = "doing"   
                      and bm.fstatus="doing"
                       and  bm.fidstore_sender  = i_dStore );
set countNewOrderToMainStore =    (    select   count(*) 
         from billing_marsole_details as bmd
      inner join billing_marsole as bm  on bm.id = bmd.fidmarsole
      inner join  billing_details as bd on bd.id  =   bmd.fidbilling_details

      where bm.fdeleted=0   and bd.id not in (select fidbilling_details  from  billing_sellers_mahmole_details   )
      and bm.fidstore_sender = 1  and  bd.fidstore <> 1    and  bd.fidstore  =  i_dStore      );


   select  countproducts , countNewOrderToCustomer , countNewOrderToMainStore , countNewMessages, countRequestedproducts , activetikets ;
 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPDashboardInfoUser` */;
DELIMITER ;;
CREATE  PROCEDURE `SPDashboardInfoUser`(IN `F_ldId` INT ,IN `MODELVIEW`   VARCHAR(255) CHARSET utf8mb4 )
BEGIN
  declare CompletedOrders int ;
declare doingOrders int ;
 declare CanceledOrders int ;
declare activetikets int ;
declare counttoday_getednobat int ;
declare countd_1obat_getednobat int ;
declare AwaitingPaymentOrders int ;
declare AwaitingConfirmationOrders int ;
 declare returnedOrders int ;
if MODELVIEW='website' then 
set counttoday_getednobat = -1;
set countd_1obat_getednobat = -1 ;
  set doingOrders =(select count(*)   from   billing  where (  fstatus = 'doing')  and fidwebuser = F_ldId and  fdeleted=0) ; 
 set AwaitingPaymentOrders =(select count(*)   from   billing  where (  fstatus = 'AwaitingPayment')  and fidwebuser = F_ldId and  fdeleted=0) ; 
 set AwaitingConfirmationOrders =(select count(*)   from   billing  where (  fstatus = 'AwaitingConfirmation')  and fidwebuser = F_ldId and  fdeleted=0) ;  
 set activetikets =   ( select count(*) as activetikets from  codeman_tikets  where  factive!=10  and fuserId= F_ldId );   
     set CanceledOrders =(select count(*)   from   billing  where (  fstatus = 'Canceled')  and fidwebuser = F_ldId and  fdeleted=0) ; 
  set CompletedOrders =(select count(*)   from   billing  where (  fstatus = 'Completed')  and fidwebuser = F_ldId and  fdeleted=0) ; 
   set returnedOrders =(select count(*)   from   billing  where (  fstatus = 'returned')  and fidwebuser = F_ldId and  fdeleted=0) ; 
  select    AwaitingPaymentOrders  ,  AwaitingConfirmationOrders  , returnedOrders  , doingOrders, CompletedOrders , CanceledOrders , activetikets,  counttoday_getednobat ,countd_1obat_getednobat ; 
elseif MODELVIEW='nobat' then 
set counttoday_getednobat = ( SELECT count(*) FROM nobat_allnobats where FldDate =DATE(now()) and  FldIdCustomer =F_ldId  and   FldDeleted=0  and FldActive=1  );
set countd_1obat_getednobat = ( SELECT count(*) FROM nobat_allnobats where FldDate = DATE(  DATE_ADD(now(), INTERVAL 1 DAY)) and  FldIdCustomer =  F_ldId  and   FldDeleted=0  and FldActive=1  );
 select    AwaitingPaymentOrders  ,  AwaitingConfirmationOrders  , returnedOrders  , doingOrders, CompletedOrders , CanceledOrders , activetikets,  counttoday_getednobat ,countd_1obat_getednobat ; 
 else
 set counttoday_getednobat = ( SELECT count(*) FROM nobat_allnobats where FldDate =DATE(now()) and  FldIdCustomer =F_ldId  and   FldDeleted=0  and FldActive=1  );
set countd_1obat_getednobat = ( SELECT count(*) FROM nobat_allnobats where FldDate = DATE(  DATE_ADD(now(), INTERVAL 1 DAY)) and  FldIdCustomer =  F_ldId  and   FldDeleted=0  and FldActive=1  );
 set activetikets =   ( select count(*) as activetikets from  codeman_tikets  where  factive!=10  and fuserId= F_ldId );   
 select    AwaitingPaymentOrders  ,  AwaitingConfirmationOrders  , returnedOrders  , doingOrders, CompletedOrders , CanceledOrders , activetikets,  counttoday_getednobat ,countd_1obat_getednobat ; 
end if;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPEmails_Update` */;
DELIMITER ;;
CREATE  PROCEDURE `SPEmails_Update`(
IN `i_d` BIGINT, 
IN `f_html` LONGTEXT CHARSET utf8mb4,
IN `f_title` LONGTEXT CHARSET utf8mb4,
IN `f_active` tinyint 
)
BEGIN

  declare f_last_update datetime ;
 set f_last_update =   now() ;

  IF i_d > 0 THEN
      
   
       UPDATE emails
            SET 
            ftitle = f_title ,    pattern=f_html    , factive=f_active   WHERE id = i_d ; 
                select i_d  as id;
   
  END IF;

  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPExtensions_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPExtensions_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(900) CHARSET utf8mb4, 
IN `f_desc` longtext CHARSET utf8mb4, 
IN `f_type` VARCHAR(955) CHARSET utf8mb4,
IN `f_price` BIGINT, 
IN `f_extra` longtext CHARSET utf8mb4, 
IN `f_off` TINYINT    ,
IN `f_key` VARCHAR(900) CHARSET utf8mb4,  
IN `f_image` VARCHAR(1900) CHARSET utf8mb4, 
IN `f_hide` TINYINT
)
BEGIN

declare co integer ;
       set   co  =  (select count(id ) as id   from codeman_extens where fname = f_name  or  fkey=f_key ) ;
       
       if  co > 0  then
        set i_d =   (select  id       from codeman_extens where fname = f_name  or  fkey=f_key limit 1 ) ;
       end if ;


  IF i_d > 0 THEN
      
   
       UPDATE codeman_extens
            SET 
        foff=f_off ,     fprice=f_price , ftype=f_type ,  fname=f_name , fhide=f_hide ,   fdesc=f_desc , fkey=f_key  , fimage=f_image , fextra=f_extra
               ,  flastupdate = now()
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  codeman_extens (fname,   fhide  ,fkey ,fimage  ,fdesc ,fprice,ftype ,fextra , foff )
               VALUES (f_name,  f_hide       ,f_key  ,f_image   ,f_desc ,f_price ,f_type , f_extra  , f_off) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPexternal_stores_list_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPexternal_stores_list_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(455) CHARSET utf8mb4, 
IN `f_image` VARCHAR(955) CHARSET utf8mb4, 
IN `f_type` VARCHAR(255) CHARSET utf8mb4, 
IN `f_url` VARCHAR(955) CHARSET utf8mb4, 
IN `f_latinName` VARCHAR(455) CHARSET utf8mb4, 
IN `f_order` BIGINT

 
)
BEGIN

 

IF i_d > 0 THEN
       UPDATE external_stores_list
            SET  fname=f_name ,  fimage=f_image ,  ftype=f_type ,  furl=f_url ,  flatinName=f_latinName ,  forder=f_order 
              
                  
         WHERE id = i_d ;
		 select i_d  as id;
  END IF;
  IF i_d = 0 THEN
              INSERT  INTO  external_stores_list (fname ,fimage,ftype,furl,flatinName,forder)
               VALUES ( f_name ,f_image,f_type,f_url,f_latinName,f_order) ;
    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPexternal_stores_user_requests_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPexternal_stores_user_requests_AddUpdate`(
IN `i_d` BIGINT,
 IN `f_price` int(15), 
IN `f_name` VARCHAR(455) CHARSET utf8mb4, 
IN `f_image` VARCHAR(955) CHARSET utf8mb4, 
IN `f_status` VARCHAR(255) CHARSET utf8mb4, 
IN `f_url` VARCHAR(955) CHARSET utf8mb4, 
IN `f_adminDesc` VARCHAR(1455) CHARSET utf8mb4,
 IN `f_dateend` VARCHAR(455) CHARSET utf8mb4,  
 IN `f_deactiveLinkProductOnExpire` tinyint(3), 
IN `f_desc` VARCHAR(1455) CHARSET utf8mb4 

 
)
BEGIN

 

IF i_d > 0 THEN
       UPDATE external_stores_user_requests
            SET fprice=f_price , fname=f_name ,  fimage=f_image ,fstatus=f_status ,   furl=f_url ,   fadminDesc=f_adminDesc , fdesc=f_desc     
           ,   fdateend=f_dateend  , fdeactiveLinkProductOnExpire=f_deactiveLinkProductOnExpire
                  
         WHERE id = i_d ;
		 select i_d  as id;
  END IF;
  IF i_d = 0 THEN
              
    SELECT  -1 as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPgeneral_components_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPgeneral_components_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
IN `f_html` LONGTEXT CHARSET utf8mb4,
 IN `f_author` VARCHAR(255) CHARSET utf8mb4, 
IN `f_type` VARCHAR(255) CHARSET utf8mb4, 
 IN `f_com_type` VARCHAR(255) CHARSET utf8mb4, 
IN `f_active` TINYINT,
IN `no_html` TINYINT ,
IN `f_canedit` VARCHAR(255) CHARSET utf8mb4 ,
IN `f_desc` VARCHAR(955) CHARSET utf8mb4,
IN `f_fixtype` VARCHAR(955) CHARSET utf8mb4
)
BEGIN
declare f_last_update datetime ;
 set f_last_update =   now() ;

   IF i_d > 0 THEN
      
   if   no_html > 0  then
			UPDATE general_components  SET 
                fname=f_name , factive=f_active,    flast_update=f_last_update ,
               fauthor=f_author ,ftype=f_type   , fcom_type=f_com_type , fcanedit=f_canedit , fdesc=f_desc, ffixtype=f_fixtype
			WHERE id = i_d and id > 10  ;

         else
         	 UPDATE general_components  SET 
                 fname=f_name , factive=f_active,  fhtml=f_html, flast_update=f_last_update ,
               fauthor=f_author ,ftype=f_type    , fcom_type=f_com_type ,    fcanedit=f_canedit, fdesc=f_desc, ffixtype=f_fixtype
			WHERE id = i_d   and id > 10  ;
         
         end if;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  general_components (fhtml,fauthor,ftype,factive,fname,flast_update ,fcom_type ,fcanedit  , fdesc ,ffixtype
             )
               VALUES (f_html,f_author,f_type,f_active,f_name,f_last_update ,f_com_type ,f_canedit , f_desc ,f_fixtype
                   ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `spGetAllModulsForCustomer` */;
DELIMITER ;;
CREATE  PROCEDURE `spGetAllModulsForCustomer`()
BEGIN

 SELECT * From  moduls where flddeleted=0 and FldVisibal=1;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `spGetItemInfoFromWeb` */;
DELIMITER ;;
CREATE  PROCEDURE `spGetItemInfoFromWeb`(IN id  int  , IN t_ype INT)
BEGIN
   
 declare Start_day_interval int;
  declare End_day_interval int;
    declare  fromdate date  ;
 declare   todate date  ;

set  Start_day_interval =(  select  fldval from  nobat_settings  where fldkey='Start_day_interval') ;
set End_day_interval  = (  select fldval from  nobat_settings where fldkey='End_day_interval' ) ;

 
 
set  todate = ( select  DATE_ADD(now(), INTERVAL End_day_interval DAY) );    
 set fromdate =(select  DATE_ADD(now(), INTERVAL Start_day_interval DAY)  ) ;

call SPNobat_AllNobats_ReturnDatebyRowNumber  (fromdate,todate ,t_ype,id) ;


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `spGetItemTimeInfoFromWeb` */;
DELIMITER ;;
CREATE  PROCEDURE `spGetItemTimeInfoFromWeb`(IN fdate  date  , IN fidlastlevel  INT)
BEGIN
   
  declare flastleve int;
 
 declare  Type_ int ;
 declare  Favetime int ;
 
 set flastleve = 1 ;
  set Type_ = 4 ;
   set Favetime = -1 ;

 call SPNobat_ReturnAllNobatTime_ByWhere  (fdate, flastleve , fidlastlevel,Type_,Favetime) ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `spGetLevel1FromWeb` */;
DELIMITER ;;
CREATE  PROCEDURE `spGetLevel1FromWeb`(in id int )
BEGIN
 	   call SPNobat_DeactiveNearNobats();
SELECT        nobat_level1.Fldid, nobat_level1.Fldtitle, nobat_level1.FldActive, nobat_level1.FldSex, nobat_level1.FldShortCode,
 nobat_level1.FldWebDesc, nobat_level2_items.Fldtitle AS Fldtitle2
 ,nobat_level1.FldLastCommensCount as commentsCount ,  CASE
    WHEN nobat_level1.FldLastCommensCount >0  THEN round( nobat_level1.FldLasRating/nobat_level1.FldLastCommensCount , 2)  
    ELSE 0
END as avrageRating ,                    

 CASE  
      WHEN nobat_level1.FldLastCommensCount >0  THEN round(( nobat_level1.FldLastSuggest/nobat_level1.FldLastCommensCount)*100 , 2)  
      ELSE 0
  END as  SuggestCount    , nobat_level1.fimages,
                      nobat_level1.furl,
                      nobat_level1.fhtml,
                      nobat_level1.flast_update , nobat_level1.FldActive_OV , nobat_level1.Fldvoicepath_OV
	 
FROM            nobat_level1 INNER JOIN
                         nobat_level2_items ON nobat_level1.FldIdlevel2_Items = nobat_level2_items.Fldid
WHERE        (nobat_level2_items.FldDeleted = 0) AND (nobat_level1.FldDeleted = 0) and     nobat_level1.Fldid =id  ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPgspin_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPgspin_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
 IN `f_extra` LONGTEXT CHARSET utf8mb4,
 IN `f_items` LONGTEXT CHARSET utf8mb4,
 IN `f_General_limitation` BIGINT,
 IN `f_User_limitation` BIGINT, 
 
IN `f_desc` LONGTEXT CHARSET utf8mb4,
 
IN `f_active` TINYINT
)
BEGIN

 

IF i_d > 0 THEN
       UPDATE gspin
            SET 
               fname=f_name , factive=f_active,   fdesc=f_desc  , fextra=f_extra  , fitems=f_items
                 , fUser_limitation=f_User_limitation  , fGeneral_limitation=f_General_limitation 
                  
         WHERE id = i_d ;
		 select i_d  as id;
  END IF;
  IF i_d = 0 THEN
              INSERT  INTO  gspin (  fname ,fextra , factive ,   fdesc  ,fitems     ,fUser_limitation ,fGeneral_limitation)
               VALUES ( f_name , f_extra, f_active,      f_desc  ,f_items    ,f_User_limitation ,f_General_limitation) ;
    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPHolidays_AddUpdateHolidays` */;
DELIMITER ;;
CREATE  PROCEDURE `SPHolidays_AddUpdateHolidays`(IN `F_ldId` INT, IN `F_ldTitle` VARCHAR(255) CHARSET utf8mb4, IN `F_ldDate` DATETIME)
BEGIN
 DECLARE   varid bigint ;
 IF F_ldId > 0 then
	  
         UPDATE tblholidays   SET    FldTitle = F_ldTitle,   FldDate = F_ldDate   , flddeleted = 0   WHERE tblholidays.Fldid = F_ldId ;
		 SELECT F_ldId ;
END if ;
IF F_ldId = 0 then
		SET varid =   (   SELECT   tblholidays.Fldid   FROM tblholidays  WHERE tblholidays.FldDate = F_ldDate    limit 1 );
		IF varid > 0 then
			SET F_ldId = varid;
			IF F_ldId > 0 then
				UPDATE tblholidays    SET flddeleted = 0 ,  FldTitle = F_ldTitle,   FldDate = F_ldDate    WHERE tblholidays .Fldid = F_ldId ;
				SELECT F_ldId ;
			END if ;
		END if ;
		IF F_ldId = 0 then
            INSERT tblholidays (   FldTitle,    FldDate  )    VALUES (      F_ldTitle,    F_ldDate );
		    SELECT LAST_INSERT_ID();
		END if;
END if;
         
         
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPlayouts_html_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPlayouts_html_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_element_id` BIGINT, 
 IN `f_html`longtext CHARSET utf8mb4 
)
BEGIN
 
declare co integer ;
       set   co  =  (select count(id ) as id   from layouts_html where f_element_id = felement_id  ) ;
       
       if  co > 0  then
        set i_d =   (select  id       from layouts_html where f_element_id = felement_id   ) ;
       end if ;

  IF i_d > 0 THEN
      
   
       UPDATE layouts_html
            SET 
                fhtml=f_html  
                
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  layouts_html (fhtml , felement_id )
               VALUES (f_html , f_element_id ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPLevel1_UpdateHTML` */;
DELIMITER ;;
CREATE  PROCEDURE `SPLevel1_UpdateHTML`(
IN `i_d` BIGINT, 
IN `f_html` LONGTEXT CHARSET utf8mb4
)
BEGIN

  declare f_last_update datetime ;
 set f_last_update =   now() ;

  IF i_d > 0 THEN
      
   
       UPDATE nobat_level1
            SET 
                fhtml=f_html   , flast_update=f_last_update    WHERE Fldid = i_d ; 
                select i_d  as id;
   
  END IF;

  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPLevel2_UpdateHTML` */;
DELIMITER ;;
CREATE  PROCEDURE `SPLevel2_UpdateHTML`(
IN `i_d` BIGINT, 
IN `f_html` LONGTEXT CHARSET utf8mb4
)
BEGIN

  declare f_last_update datetime ;
 set f_last_update =   now() ;

  IF i_d > 0 THEN
      
   
       UPDATE  nobat_level2_items
            SET 
                fhtml=f_html   , flast_update=f_last_update    WHERE Fldid = i_d ; 
                select i_d  as id;
   
  END IF;

  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AddUpdateNobat_Level1` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AddUpdateNobat_Level1`(
IN `F_ldTitle` VARCHAR(255) CHARSET utf8mb4, 
IN `F_ldVoicePath` VARCHAR(3500) CHARSET utf8mb4, 
IN `F_ldPcName` VARCHAR(255) CHARSET utf8mb4, 
IN `F_ldActive` TINYINT, 
IN `i_d_` BIGINT, 
IN `F_ldJobTitle` VARCHAR(255) CHARSET utf8mb4, 
IN `F_ldSex` VARCHAR(255) CHARSET utf8mb4, 
IN `F_mobile` VARCHAR(255) CHARSET utf8mb4, 
IN `F_ldldidDB` BIGINT, 
IN `F_ldActive_OV` TINYINT, 
IN `F_ldVoicePath_OV` VARCHAR(3500) CHARSET utf8mb4, 
IN `F_ldShortCode` INT, 
IN `F_ldIdlevel2_Items` INT, 
IN `F_ldWebDesc` LONGTEXT CHARSET utf8mb4)
BEGIN

  
   
 declare OldShirtc int ;
 
  IF i_d_ > 0 THEN
  
    set  OldShirtc = ( select FldShortCode  from nobat_level1 where Fldid = i_d_  );
    if OldShirtc <> F_ldShortCode then
			if ( select count(*)  from nobat_level1 where FldShortCode = F_ldShortCode)>0 then
					set F_ldShortCode = OldShirtc ;
                END IF;      
        END IF;    
        
        	   UPDATE nobat_level1
            SET 
               Fldtitle = F_ldTitle, 
			   FldWebDesc=F_ldWebDesc,
		FldMobile=F_mobile,
			   FldShortCode=F_ldShortCode,
              
               FldActive = F_ldActive, 
               FldJobTitle = F_ldJobTitle, 
               FldSex = F_ldSex,
               FldPcName=F_ldPcName,
			   FldActive_OV=F_ldActive_OV,
			   
			   FldIdlevel2_Items=F_ldIdlevel2_Items , flast_update=now()
         WHERE nobat_level1.Fldid = i_d_ ;

		 select i_d_  as Fldid;
   
  END IF;

  IF i_d_ = 0 THEN
 
  		 	 if ( select count(*)  from nobat_level1 where FldShortCode = F_ldShortCode)>0 then 
			 set F_ldShortCode = ( select  ifnull( MAX(FldShortCode),100) + 1  from  nobat_level1 ) ;
             end if ;
             	 
              INSERT  INTO  nobat_level1(
               Fldtitle, 
               Fldvoicepath, 
               FldPcName, 
               FldActive, 
               FldJobTitle, 
               FldSex,FldidDB ,FldActive_OV,FldVoicePath_OV ,FldShortCode,FldIdlevel2_Items,FldWebDesc , flast_update ,FldMobile)
               VALUES (
                  F_ldTitle, 
                  F_ldVoicePath, 
                  F_ldPcName, 
                  F_ldActive, 
                  F_ldJobTitle, 
                  F_ldSex,F_ldldidDB,F_ldActive_OV ,F_ldVoicePath_OV ,F_ldShortCode,F_ldIdlevel2_Items,F_ldWebDesc , now() , F_mobile) ;
                  

    SELECT  LAST_INSERT_ID() as Fldid;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AddUpdateNobat_Level2_Items` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AddUpdateNobat_Level2_Items`(IN `Title` VARCHAR(255) CHARSET utf8mb4, IN `VoicePath` VARCHAR(3500) CHARSET utf8mb4, IN `PcName` VARCHAR(255) CHARSET utf8mb4, IN `F_ldActive` TINYINT, IN `id_` BIGINT, IN `F_ldidDB` BIGINT, IN `F_ldIdlevel3_Items` BIGINT, IN `F_ldWebDesc` LONGTEXT CHARSET utf8mb4)
BEGIN

 
 
  IF id_ > 0 THEN

       UPDATE   nobat_level2_items
            SET 
               Fldtitle = Title, 
			    FldWebDesc=F_ldWebDesc,
               Fldvoicepath = VoicePath, 
               FldActive = F_ldActive,
			   FldIdlevel3_Items= F_ldIdlevel3_Items  , flast_update=now()
         WHERE nobat_level2_items.Fldid = id_ ;

		 select id_  as Fldid;
   
  END IF;

  IF id_ = 0 THEN
 
 
             INSERT   nobat_level2_items(Fldtitle, Fldvoicepath, FldPcName, FldActive,FldidDB,FldIdlevel3_Items,FldWebDesc , flast_update)
               VALUES (Title, VoicePath, PcName, F_ldActive,FldidDB,F_ldIdlevel3_Items,F_ldWebDesc , now()) ;
                  

    SELECT  LAST_INSERT_ID() as Fldid;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AddUpdateRating` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AddUpdateRating`(
 
 in      F_ldid bigint,
 in     F_ldIdCustomer bigint,
  in    F_ldIdNobat bigint,
 in     F_ldRate int(10),
 in     F_ldStatus tinyint(2),
 in     F_ldComment longtext   CHARSET utf8mb4 ,
 in     F_ldSuggest tinyint(2)
 )
BEGIN
   DECLARE   varid bigint ;
   
   
   if F_ldRate<20 then
   set F_ldRate=20 ;
end if;
     

      IF  F_ldid > 0  then
	  
		UPDATE  rating
            SET 
               FldRate = F_ldRate, 
			   FldComment=F_ldComment ,
				 FldStatus=1 ,
				 FldSuggest = F_ldSuggest
         WHERE   Fldid = F_ldid  ;

		 select F_ldid as id ;

		end if ;
      IF F_ldId = 0 then
          
		
		     SET varid =   (   SELECT   Fldid   FROM rating  WHERE  FldIdNobat = F_ldIdNobat  limit 1  ) ;
		  IF  varid > 0 then
           SET F_ldId = varid ;
 end if ;
             IF F_ldId > 0 then
			  
         UPDATE rating    SET   FldRate = F_ldRate, 
			   FldComment=F_ldComment, flddeleted = 0  ,  FldSuggest = F_ldSuggest
		 WHERE Fldid = F_ldId ;
		 
		  SELECT F_ldId as id ;
         END if;
      IF F_ldId = 0 then
          
            INSERT rating (FldIdCustomer,FldIdNobat ,  FldRate, FldStatus ,
		 FldComment , FldSuggest  )    VALUES (F_ldIdCustomer,F_ldIdNobat ,  F_ldRate, 1 ,
		 F_ldComment , F_ldSuggest ) ;
			 
            SELECT last_insert_id() as id ;

         END if ;
   END if ;
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AddUpdate_Nobat_AllNobats` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AddUpdate_Nobat_AllNobats`(IN `Title` VARCHAR(255) CHARSET utf8mb4, IN `VoicePath` VARCHAR(255) CHARSET utf8mb4, IN `PcName` VARCHAR(255) CHARSET utf8mb4, IN `A_ctive` TINYINT(1), IN `fid` BIGINT, IN `idLastLevel` BIGINT, IN `LastLevel` SMALLINT, IN `FDate` DATETIME, IN `FTimeStart` INT, IN `FTimeEnd` INT, IN `FTimeStartSTR` VARCHAR(255) CHARSET utf8mb4, IN `FTimeEndSTR` VARCHAR(255) CHARSET utf8mb4)
BEGIN

   
   
   
   
   
   
   
   
   
   
   
   
   
   
IF fid > 0 THEN
    UPDATE nobat_allnobats
    SET Fldtitle = Title,
        Fldvoicepath = VoicePath,
        FldActive = A_ctive,
        fldidLastLevel = idLastLevel,
        fldLastLevel = LastLevel,
        FldDate =  ifnull(FDate, now()),
        FldTimeStart = FTimeStart,
        FldTimeEnd = FTimeEnd,
         FldPcName = PcName,
        FldTimeStartSTR = FTimeStartSTR,
        FldTimeEndSTR = FTimeEndSTR
    WHERE Fldid = fid;
  END IF;

  IF fid = 0 THEN
    INSERT INTO nobat_allnobats (Fldtitle, Fldvoicepath, FldActive,
    fldidLastLevel, fldLastLevel, FldDate, FldTimeStart, FldTimeEnd, FldTimeStartSTR, FldTimeEndSTR , FldPcName)
      VALUES (Title, VoicePath, A_ctive, idLastLevel, LastLevel,  ifnull(FDate, now()), FTimeStart, FTimeEnd, FTimeStartSTR, FTimeEndSTR,PcName);
    SELECT
      LAST_INSERT_ID();
  END IF;
  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AllNobats_Aprov` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AllNobats_Aprov`(IN t_ype  int , IN idNobat  int ,IN FldInsertUserRole VARCHAR(1055) CHARSET utf8mb4  )
BEGIN
   
 	 
update  nobat_allnobats set FldAproved = t_ype  , FldInsertUser=FldInsertUserRole
  where  Fldid=idNobat and FldDeleted=0    and (  nobat_allnobats.FldFlag=1 or  nobat_allnobats.FldFlag=2  or  nobat_allnobats.FldFlag=3) ;
         
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AllNobats_Laghve` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AllNobats_Laghve`(IN id  bigint   )
BEGIN
   
   call SPNobat_DeactiveNearNobats();
   	  	 
 UPDATE nobat_allnobats SET FldMobileNO=NULL, FldCodeMeli=NULL, FldCallTime=NULL ,FldCommentVoicePath=NULL, FldCallerid=NULL, FldFlag=0, FldIdCustomer=NULL  WHERE Fldid =  id ;
         
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPnobat_allnobats_Level1Nobats` */;
DELIMITER ;;
CREATE  PROCEDURE `SPnobat_allnobats_Level1Nobats`(IN `Wheree` VARCHAR(1055) CHARSET utf8mb4, IN `limitt` INT)
BEGIN
   
   call SPNobat_DeactiveNearNobats();
   	  	  if  length(LTRIM(rtrim(Wheree)))<2  then
	  set  Wheree=' 1=1' ;
      end if;
      
        SET @stmt_str = CONCAT('SELECT  nobat_allnobats.Fldid, nobat_allnobats.FldDate,  fMilladyToShamsi_NoTime(nobat_allnobats.FldDate) AS FldDatePER, nobat_allnobats.FldTimeStartSTR, nobat_allnobats.FldTimeEndSTR, nobat_allnobats.Fldtitle, 
                         nobat_allnobats.FldCallTime, nobat_allnobats.FldCallerid, nobat_allnobats.FldCodeMeli, nobat_allnobats.FldMobileNO, nobat_allnobats.FldIdCustomer, nobat_allnobats.FldCommentVoicePath, 
                          fMilladyToShamsi_ByTime(nobat_allnobats.FldCallTime) AS PersianCallTime, nobat_allnobats.FldidLastLevel, nobat_allnobats.FldLastLevel, nobat_allnobats.FldFlag, nobat_allnobats.FldidDB, 
                         nobat_allnobats.Fldvoicepath, nobat_allnobats.FldPcName, nobat_allnobats.FldDeleted, nobat_allnobats.FldTimeEnd, nobat_allnobats.FldActive, nobat_allnobats.FldTimeStart, tblwebusers.FldName, 
                         tblwebusers.FldLastName, tblwebusers.FldSex, nobat_allnobats.FldAproved
FROM            nobat_allnobats LEFT OUTER JOIN
                         tblwebusers ON nobat_allnobats.FldIdCustomer = tblwebusers.Fldid
WHERE        (nobat_allnobats.FldDeleted = 0)  ', Wheree, '
ORDER BY Fldid   limit ', limitt, ' ');
  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
   
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AllNobats_Level1NobatsFarakhan` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AllNobats_Level1NobatsFarakhan`(IN `idlevel1` int )
BEGIN
   
   call SPNobat_DeactiveNearNobats();
 SELECT   (@row_number := @row_number + 1)   AS RowNumber  ,  nobat_allnobats.Fldid, nobat_allnobats.FldDate,  fMilladyToShamsi_NoTime(nobat_allnobats.FldDate) AS FldDatePER, nobat_allnobats.FldTimeStartSTR, nobat_allnobats.FldTimeEndSTR, nobat_allnobats.Fldtitle, 
                         nobat_allnobats.FldCallTime, nobat_allnobats.FldCallerid, nobat_allnobats.FldCodeMeli, nobat_allnobats.FldMobileNO, nobat_allnobats.FldIdCustomer, nobat_allnobats.FldCommentVoicePath, 
                          fMilladyToShamsi_ByTime(nobat_allnobats.FldCallTime) AS PersianCallTime, nobat_allnobats.FldidLastLevel, nobat_allnobats.FldLastLevel, nobat_allnobats.FldFlag, nobat_allnobats.FldidDB, 
                         nobat_allnobats.Fldvoicepath, nobat_allnobats.FldPcName, nobat_allnobats.FldDeleted, nobat_allnobats.FldTimeEnd, nobat_allnobats.FldActive, nobat_allnobats.FldTimeStart, tblwebusers.FldName, 
                         tblwebusers.FldLastName, tblwebusers.FldSex, nobat_allnobats.FldAproved , nobat_allnobats.FldDesc
FROM            nobat_allnobats LEFT OUTER JOIN
                         tblwebusers ON nobat_allnobats.FldIdCustomer = tblwebusers.Fldid  , (SELECT @row_number := 0) AS x
WHERE        (nobat_allnobats.FldDeleted = 0)    and  DATE_FORMAT( nobat_allnobats.FldDate,"%Y/%m/%d") = DATE_FORMAT( now(),"%Y/%m/%d") and  nobat_allnobats.FldidLastLevel = idlevel1     and 
  ( nobat_allnobats.FldFlag=1 or nobat_allnobats.FldFlag=2  or nobat_allnobats.FldFlag=3)  
ORDER BY Fldid    ; 
   
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AllNobats_ReturnDatebyRowNumber` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AllNobats_ReturnDatebyRowNumber`(IN `fromdate` DATE, IN `todate` DATE, IN `flastleve` INT, IN `fidlastlevel` INT)
BEGIN
   
  call SPNobat_DeactiveNearNobats();

	  	    select  * ,(@row_number := @row_number + 1)   AS RowNumber   from ( 
          SELECT distinct  DATE_FORMAT( t.flddate,'%Y-%m-%d') AS flddate   
        FROM nobat_allnobats AS t , (SELECT @row_number := 0) AS x
      where t.flddeleted=0 and  t.FldActive=1  AND t.FldFlag=0 AND t.FldLastLevel=flastleve  AND  t.FldidLastLevel=fidlastlevel and  
      FldDate BETWEEN fromdate AND  todate  ) as r  order by  r.flddate  ;
 
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AllNobats_search` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AllNobats_search`(IN `Wheree` VARCHAR(1055) CHARSET utf8mb4, IN `limitt` INT)
BEGIN
if  length(LTRIM(rtrim(Wheree)))<2 then
	  set  Wheree=' 1=1' ;
end if;

 SET @stmt_str = CONCAT('  SELECT   
  nobat_allnobats.Fldid,
  nobat_allnobats.FldDate,
    fMilladyToShamsi_NoTime( nobat_allnobats.FldDate) as FldDatePER ,
  nobat_allnobats.FldTimeStartSTR,
  nobat_allnobats.FldTimeEndSTR,
  nobat_allnobats.Fldtitle,
  nobat_allnobats.FldCallTime,
  nobat_allnobats.FldCallerid,
  nobat_allnobats.FldCodeMeli,
  nobat_allnobats.FldMobileNO,
  nobat_allnobats.FldIdCustomer,
  nobat_allnobats.FldCommentVoicePath,
 fMilladyToShamsi_ByTime(nobat_allnobats.FldCallTime) AS PersianCallTime,
  nobat_allnobats.FldidLastLevel,
  nobat_allnobats.FldLastLevel,
  nobat_allnobats.FldFlag,
  nobat_allnobats.FldidDB,
  nobat_allnobats.Fldvoicepath,
  nobat_allnobats.FldPcName,
  nobat_allnobats.FldDeleted,
  nobat_allnobats.FldTimeEnd,
  nobat_allnobats.FldActive,
  nobat_allnobats.FldTimeStart
FROM nobat_allnobats
WHERE nobat_allnobats.FldDeleted = 0
 and ', Wheree, '
ORDER BY Fldid   limit ', limitt, ' ');
  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  
  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AllNobats_UnLockNobat` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AllNobats_UnLockNobat`(IN id  bigint   )
BEGIN
   
   call SPNobat_DeactiveNearNobats();
   	  	 
 UPDATE nobat_allnobats SET FldMobileNO=NULL, FldCodeMeli=NULL, FldCallTime=NULL ,FldCommentVoicePath=NULL, 
 FldCallerid=NULL, FldFlag=0, FldIdCustomer=NULL    , FldLocked=false , 
     FldLockedTime=null , FldTranUID = null        WHERE Fldid =  id ;
         
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AllNobats_UserNobats` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AllNobats_UserNobats`(in idCustomer bigint , idLevel1 bigint)
BEGIN
  call SPNobat_DeactiveNearNobats();
 
 if idLevel1 =0 then
 
SELECT     ffffConvertMilladyToGHamary(nobat_allnobats.FldDate) AS FldDate, nobat_allnobats.FldAproved, nobat_allnobats.Fldid, nobat_allnobats.FldidLastLevel, nobat_allnobats.FldFlag, nobat_allnobats.Fldtitle, 
                         nobat_allnobats.FldActive, nobat_allnobats.FldCallerid, nobat_allnobats.FldTimeStartSTR, nobat_allnobats.FldCodeMeli, nobat_allnobats.FldMobileNO,  ffffConvertMilladyToGHamary(nobat_allnobats.FldInsertTime) 
  AS inserTime, nobat_allnobats.FldDesc, nobat_level1.Fldtitle AS FldtitleLevel1, CASE WHEN (CAST(FldDate AS date) < CAST(now() AS date)) THEN - 1 WHEN (CAST(FldDate AS date) > CAST(now() AS date)) 
                         THEN 1 ELSE 2 END AS fldState,
                             (SELECT         ifnull(FldRate, 0) AS Expr1
                               FROM            rating
                               WHERE        (FldIdNobat = nobat_allnobats.Fldid) AND (flddeleted = 0)  limit 1 ) AS rate,
                             (SELECT       ifnull(FldSuggest, 0) AS Expr1
                               FROM            rating AS Rating_1
                               WHERE        (FldIdNobat = nobat_allnobats.Fldid) AND (flddeleted = 0)   limit 1  ) AS FldSuggest,  ffffConvertMilladyToGHamary(nobat_allnobats.FldCallTime)as FldCallTime
FROM            nobat_allnobats INNER JOIN
                         nobat_level1 ON nobat_allnobats.FldidLastLevel = nobat_level1.Fldid
WHERE        (nobat_allnobats.FldIdCustomer = idCustomer) AND (nobat_allnobats.FldDeleted = 0)
ORDER BY fldState DESC  ;
 end if ;
 if idLevel1 > 0 then
 
SELECT     ffffConvertMilladyToGHamary(nobat_allnobats.FldDate) as FldDate , nobat_allnobats.FldAproved ,   nobat_allnobats.Fldid, nobat_allnobats.FldidLastLevel, nobat_allnobats.FldFlag, nobat_allnobats.Fldtitle, nobat_allnobats.FldActive, nobat_allnobats.FldCallerid, nobat_allnobats.FldTimeStartSTR, 
                         nobat_allnobats.FldCodeMeli, nobat_allnobats.FldMobileNO, ffffConvertMilladyToGHamary(nobat_allnobats.FldInsertTime)
						 AS inserTime, nobat_allnobats.FldDesc, nobat_level1.Fldtitle AS FldtitleLevel1 , 
  CASE 
     WHEN  (CAST(FldDate as date) < CAST(now() as date))   THEN -1   
     WHEN (CAST(FldDate as date) > CAST(now() as date)) THEN  1  
     ELSE 2  
  END as fldState,     (select    ifnull( FldRate ,0)  from rating where FldIdNobat =  nobat_allnobats.Fldid and FldDeleted=0  limit 1) as rate
    ,    (select  ifnull( FldSuggest ,0) from rating where FldIdNobat =  nobat_allnobats.Fldid and FldDeleted=0   limit 1 ) as FldSuggest ,  ffffConvertMilladyToGHamary(nobat_allnobats.FldCallTime)as FldCallTime
FROM            nobat_allnobats INNER JOIN
                         nobat_level1 ON nobat_allnobats.FldidLastLevel = nobat_level1.Fldid
WHERE        (nobat_allnobats.FldIdCustomer = idCustomer) AND (nobat_allnobats.FldDeleted = 0) and ( nobat_level1.Fldid=idLevel1)
order by fldState   desc ;
end if;


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_AllSMSSended_UserMessages` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_AllSMSSended_UserMessages`(   
in idCustomer bigint ,
   in count bigint  )
BEGIN

SELECT        allsmssended.tell, allsmssended.message,   allsmssended.insertTime  , allsmssended.result, tblwebusers.Fldid
 
FROM            allsmssended INNER JOIN
                         tblwebusers ON allsmssended.tell = tblwebusers.FldMobile
						 where tblwebusers.fldid = idCustomer
						 order by allsmssended.insertTime desc limit count  ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_DeactiveNearNobats` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_DeactiveNearNobats`()
BEGIN
declare  Timenow varchar(5) ;
 declare tp varchar(100);
 declare  Timen int;
 set tp = concat( 'AutoDisabel Datetime: ' , cast( now() as char(40)) );

	set    Timenow = ( select DATE_FORMAT(NOW(), '%H:%i'));
	 

	  set Timen  =( select fConvertTimeToInt(Timenow) + 60 ) ;
         
	    UPDATE nobat_allnobats SET FldActive=0 , flddesc=tp   WHERE    FldActive=1 AND fldflag=0      AND   date( FldDate)< date(now())  ;
	  UPDATE nobat_allnobats SET FldActive=0 , flddesc=tp   WHERE    FldActive=1 AND fldflag=0   and  FldTimeEnd <=  Timen    AND   date(FldDate) = date(now())  ;
      
       UPDATE nobat_allnobats SET FldMobileNO=NULL, FldCodeMeli=NULL, FldCallTime=NULL ,FldCommentVoicePath=NULL, 
 FldCallerid=NULL, FldFlag=0, FldIdCustomer=NULL    , FldLocked=false , 
     FldLockedTime=null , FldTranUID = null        where FldLocked= true  and  (  FldIdTransaction=0 or FldIdTransaction=null )   and  TIMESTAMPDIFF(MINUTE,FldLockedTime,NOW()) > 15     ;
      
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_GetFixLockedNobatById` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_GetFixLockedNobatById`(
 in  F_ldid bigint,
 in     F_ldCallerid varchar(100)  CHARSET utf8mb4 , 
  in    F_ldCodeMeli varchar(100)  CHARSET utf8mb4,
  in   F_ldMobileNO varchar(100)  CHARSET utf8mb4,
  in   F_pid varchar(500)  CHARSET utf8mb4 ,
 in     F_ldIdCustomer  bigint)
BEGIN

  declare flag int ;
	  declare A_ctive tinyint(1) ;
       declare tranID bigint ; 
       
      set flag = ( select   FldFlag   from nobat_allnobats where Fldid=F_ldid and FldDeleted=0);
      set A_ctive = ( select   FldActive   from nobat_allnobats where Fldid=F_ldid and FldDeleted=0);
      set tranID = ( select   ID   from transactions  where  PID= F_pid  and IDRef=F_ldid  );
      
      
	  if   flag =1 and A_ctive = 1       and tranID>0  then
	  UPDATE nobat_allnobats SET FldCallTime=now() , FldCommentVoicePath=NULL,
      FldCallerid=F_ldCallerid,  FldFlag=1,  FldIdCustomer=F_ldIdCustomer  , FldCodeMeli=F_ldCodeMeli 
	  ,  FldMobileNO=F_ldMobileNO , FldIdTransaction  = tranID  WHERE Fldid = F_ldid and FldFlag=1  and FldLocked=1 and   FldTranUID = F_pid  ;
	  select  F_ldid as id ;
	 
	  else
	  select -1  as id ;
     
     end if;
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_GetLockNobatById` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_GetLockNobatById`(
 in  F_ldid bigint,
 in     F_ldCallerid varchar(100)  CHARSET utf8mb4 , 
  in    F_ldCodeMeli varchar(100)  CHARSET utf8mb4,
  in   F_ldMobileNO varchar(100)  CHARSET utf8mb4,
 in     F_ldIdCustomer  bigint,
   in   F_UID varchar(150)  CHARSET utf8mb4)
BEGIN

  declare flag int ;
	  declare A_ctive tinyint(1) ;
      
      set flag = ( select   FldFlag   from nobat_allnobats where Fldid=F_ldid and FldDeleted=0);
            set A_ctive = ( select   FldActive   from nobat_allnobats where Fldid=F_ldid and FldDeleted=0);
 
	  if   flag =0 and A_ctive = 1  then
	 UPDATE nobat_allnobats SET FldCallTime=now() ,FldCommentVoicePath=NULL, FldLocked=true , 
     FldLockedTime=now() , FldTranUID = F_UID ,
     FldCallerid=F_ldCallerid,FldFlag=1,FldIdCustomer=F_ldIdCustomer  , FldCodeMeli=F_ldCodeMeli 
	 ,  FldMobileNO=F_ldMobileNO  WHERE Fldid = F_ldid and FldFlag=0       ;
	 select   * from nobat_allnobats  where fldid= F_ldid ;
	 
	 else
	 select -1  as id ;
     
     end if;
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_GetNobatById` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_GetNobatById`(
 in  F_ldid bigint,
 in     F_ldCallerid varchar(100)  CHARSET utf8mb4 , 
  in    F_ldCodeMeli varchar(100)  CHARSET utf8mb4,
  in   F_ldMobileNO varchar(100)  CHARSET utf8mb4,
 in     F_ldIdCustomer  bigint)
BEGIN

  declare flag int ;
	  declare A_ctive tinyint(1) ;
      
      set flag = ( select   FldFlag   from nobat_allnobats where Fldid=F_ldid and FldDeleted=0);
            set A_ctive = ( select   FldActive   from nobat_allnobats where Fldid=F_ldid and FldDeleted=0);
 
	  if   flag =0 and A_ctive = 1  then
	 UPDATE nobat_allnobats SET FldCallTime=now() ,FldCommentVoicePath=NULL,  FldCallerid=F_ldCallerid,FldFlag=1,FldIdCustomer=F_ldIdCustomer  , FldCodeMeli=F_ldCodeMeli 
	 ,  FldMobileNO=F_ldMobileNO  WHERE Fldid = F_ldid and FldFlag=0    ;
	 select  F_ldid as id ;
	 
	 else
	 select -1  as id ;
     
     end if;
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_Level1_FindById` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_Level1_FindById`(IN `id` INT)
BEGIN
Select *  From  nobat_level1   WHERE Fldid =  id   and FldDeleted = 0   ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_Level1_FindByShortCode` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_Level1_FindByShortCode`(IN `ShortCode` BIGINT)
BEGIN
Select *  From  nobat_level1   WHERE FldShortCode =  ShortCode    and FldDeleted = 0    order by fldid desc ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_Level1_GetLastShortCode` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_Level1_GetLastShortCode`()
BEGIN
 select  IFNULL( max(FldShortCode),100) + 1 as ShortCode  from  nobat_level1 ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_Level1_Items_search` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_Level1_Items_search`(IN `Wheree` VARCHAR(1055) CHARSET utf8mb4, IN `limitt` INT)
BEGIN

  SET @stmt_str = CONCAT(' SELECT        								  nobat_level1.Fldid,  nobat_level1.IdCustomer, 
 ifnull( (select CONCAT( tyu.FldName , '' '' , tyu.FldLastName )  from  tblwebusers as tyu  where tyu.Fldid =  nobat_level1.IdCustomer ), '''') as   CustomerName , 
								  nobat_level1.fldvoicepath,
                                  nobat_level1.fldtitle,
                                  nobat_level1.fldactive,
								  nobat_level1.fldiddb,
                                  nobat_level1.fldsex,
                                  nobat_level1.fldjobtitle,
                                  nobat_level1.fldactive_ov,
                                  nobat_level1.fldvoicepath_ov,
                                  nobat_level1.fldshortcode,
                                    nobat_level1.FldWebDesc,
                                  nobat_level1.fldidlevel2_items ,
                                  nobat_level2_items.Fldtitle as Fldtitle2   ,    nobat_level2_items.furl as furllevel2 , nobat_level1.fimages,
                      nobat_level1.furl,
                      nobat_level1.fhtml,
                      nobat_level1.flast_update , FldMobile
FROM            nobat_level1 inner join nobat_level2_items on nobat_level1.fldidlevel2_items = nobat_level2_items.Fldid 
WHERE        (nobat_level1.FldDeleted = 0) and ', Wheree, '
ORDER BY  nobat_level1.Fldid  desc  limit ', limitt, ' ');
  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_Level2_FindById` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_Level2_FindById`(IN `id` INT)
BEGIN
Select *  From  nobat_level2_items   WHERE Fldid =  id   and FldDeleted = 0   ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_Level2_Items_search` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_Level2_Items_search`(IN `Wheree` VARCHAR(1055) CHARSET utf8mb4, IN `limitt` INT)
BEGIN
  

  SET @stmt_str = CONCAT(' SELECT *
FROM nobat_level2_items
WHERE nobat_level2_items.FldDeleted = 0  and ', Wheree, '
ORDER BY nobat_level2_items.Fldid   limit ', limitt, ' ');
  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_Level3_Items_search` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_Level3_Items_search`(IN `Wheree` VARCHAR(1055) CHARSET utf8mb4, IN `limitt` INT)
BEGIN

  SET @stmt_str = CONCAT(' SELECT *
FROM nobat_level3_items
WHERE FldDeleted = 0  and ', Wheree, '
ORDER BY Fldid   limit ', limitt, ' ');
  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_Level4_Items_search` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_Level4_Items_search`(IN `Wheree` VARCHAR(1055) CHARSET utf8mb4, IN `limitt` INT)
BEGIN

  SET @stmt_str = CONCAT(' SELECT *
FROM nobat_level4_items
WHERE FldDeleted = 0  and ', Wheree, '
ORDER BY Fldid   limit ', limitt, ' ');
  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_Rating_Aprov` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_Rating_Aprov`(IN t_ype  int , IN idComment  int   )
BEGIN
   
  declare id_level1 bigint;
  declare id_Nobat bigint;
 declare commentsCount int;
 Declare SumRate bigint;
 declare SuggestCount int;
 
 
        update rating set FldStatus = t_ype where  Fldid=idComment and FldDeleted=0  ;


set id_Nobat = ( select  FldIdNobat from rating where  Fldid=idComment and FldDeleted=0 );
set id_level1 = (  select  FldidLastLevel from nobat_allnobats where Fldid = id_Nobat );
set commentsCount = (  SELECT         COUNT(*)   
FROM            rating INNER JOIN
                         nobat_allnobats ON rating.FldIdNobat = nobat_allnobats.Fldid
WHERE        (rating.FldStatus = 2) AND (rating.flddeleted = 0) and nobat_allnobats.FldidLastLevel=id_level1 );
 set SumRate = (  SELECT          sum(rating.fldrate) 
FROM            rating INNER JOIN
                         nobat_allnobats ON rating.FldIdNobat = nobat_allnobats.Fldid
WHERE        (rating.FldStatus = 2) AND (rating.flddeleted = 0) and nobat_allnobats.FldidLastLevel=id_level1 );
 
set SuggestCount = ( SELECT        COUNT(*)   
FROM            rating INNER JOIN
                         nobat_allnobats ON rating.FldIdNobat = nobat_allnobats.Fldid
WHERE        (rating.FldStatus = 2) and rating.FldSuggest = 1 AND (rating.flddeleted = 0) and nobat_allnobats.FldidLastLevel=id_level1);




update nobat_level1 set  FldLasRating =ifnull( SumRate,0) , FldLastCommensCount=ifnull( commentsCount , 0) , FldLastSuggest=SuggestCount where   nobat_level1.Fldid =id_level1 ;



     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_ReportAll` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_ReportAll`(IN `flLevel` INT, IN `Wheree` VARCHAR(1055))
BEGIN

if  length(LTRIM(rtrim(Wheree)))<2 then
	  set  Wheree=' 1=1' ;
end if;

 IF flLevel=1  then
  
    SET @stmt_str = CONCAT(' SELECT *,ROW_NUMBER() OVER (Order by  Fldid_L1) AS RowNumber 
  FROM (SELECT        L1.Fldid AS Fldid_L1, L1.Fldtitle AS Fldtitle_L1, AllN.Fldid AS Fldid_AllN, AllN.FldIdCustomer,
  AllN.FldFlag, AllN.FldDate,  fMilladyToShamsi_NoTime(AllN.FldDate) AS FldDateSRT, AllN.FldCallerid, fMilladyToShamsi_byTime( AllN.FldCallTime) AS FldCallTime, 
                         AllN.FldTimeStartSTR, AllN.FldTimeEndSTR, AllN.FldCodeMeli, AllN.FldMobileNO, AllN.Fldvoicepath, AllN.FldActive, AllN.FldCommentVoicePath
FROM            nobat_level1 AS L1 INNER JOIN
                         nobat_allnobats AS AllN ON L1.Fldid = AllN.FldidLastLevel
WHERE        (AllN.FldActive = 1) AND (AllN.FldDeleted = 0) AND (L1.FldDeleted = 0) AND (L1.FldActive = 1) AND (length(L1.Fldvoicepath) > 0) ) as ty  where ', Wheree, '   ');
  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  
 end if;
       IF flLevel=2  then
  
    SET @stmt_str = CONCAT(' SELECT *,ROW_NUMBER() OVER (Order by  Fldid_L1) AS RowNumber 
  FROM (SELECT        L1.Fldid AS Fldid_L1, L1.Fldtitle AS Fldtitle_L1, AllN.Fldid AS Fldid_AllN, AllN.FldIdCustomer,
  AllN.FldFlag, AllN.FldDate,  fMilladyToShamsi_NoTime(AllN.FldDate) AS FldDateSRT, AllN.FldCallerid, fMilladyToShamsi_byTime( AllN.FldCallTime) AS FldCallTime, 
                         AllN.FldTimeStartSTR, AllN.FldTimeEndSTR, AllN.FldCodeMeli, AllN.FldMobileNO, AllN.Fldvoicepath, AllN.FldActive, AllN.FldCommentVoicePath
FROM            nobat_level1 AS L1 INNER JOIN
                         nobat_allnobats AS AllN ON L1.Fldid = AllN.FldidLastLevel
WHERE        (AllN.FldActive = 1) AND (AllN.FldDeleted = 0) AND (L1.FldDeleted = 0) AND (L1.FldActive = 1) AND (length(L1.Fldvoicepath) > 0) ) as ty  where ', Wheree, '   ');
  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  
 end if;
      
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_ReturnActiveItems_ByLevel` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_ReturnActiveItems_ByLevel`(
IN `flLevel` SMALLINT, 
IN `Wheree` VARCHAR(1055) CHARSET utf8mb4)
BEGIN


 

call SPNobat_DeactiveNearNobats();



	  if  length(LTRIM(rtrim(Wheree))) <2  then
	  set  Wheree=' 1=1' ;
		end if ;

   IF flLevel=1 then 
   
     SET @stmt_str = CONCAT(' SELECT *,(@row_number := @row_number + 1)   AS RowNumber
  FROM (
SELECT distinct
         t.Fldid, t.IdCustomer, t.FldIdlevel2_Items, t.Fldvoicepath, t.Fldtitle, t.FldActive, t.FldidDB, t.FldPcName, t.FldSex, t.FldNationalCode, t.FldMobile, t.FldJobTitle, t.FldActive_OV, t.Fldvoicepath_OV, t.FldShortCode, t.FldWebDesc, 
                         t.FldHostName, t.FldInsertTime, t.FldInsertUser, t.FldDeleted		 			  ,t.FldLastCommensCount as commentsCount ,CASE  
      WHEN t.FldLastCommensCount >0  THEN round( t.FldLasRating/t.FldLastCommensCount , 2) 
      ELSE 0
  END as  avrageRating  ,
  CASE  
      WHEN t.FldLastCommensCount >0  THEN round(( t.FldLastSuggest/t.FldLastCommensCount)*100 , 2)  
      ELSE 0
  END as  SuggestCount  , t.fimages,
                      t.furl,
                      
                      t.flast_update
  FROM 
  nobat_level1 t
  INNER JOIN nobat_allnobats
    ON t.Fldid = nobat_allnobats.FldidLastLevel, (SELECT @row_number := 0) AS x
WHERE t.FldDeleted = 0
AND t.FldActive = 1
AND nobat_allnobats.FldActive = 1
AND nobat_allnobats.FldDeleted = 0
AND nobat_allnobats.FldFlag = 0 ) as ty   where ' , Wheree  );

 


  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  
   
   end if ;
   
   IF flLevel=2 then 
   
     SET @stmt_str = CONCAT('     SELECT *,(@row_number := @row_number + 1)   AS RowNumber
	 FROM (SELECT DISTINCT t.Fldid, t.FldIdlevel3_Items	,t.FldWebDesc		,  t.Fldvoicepath, t.Fldtitle, t.FldActive, t.FldidDB, t.FldPcName, t.FldDeleted, t.FldHostName, t.FldInsertTime, t.FldInsertUser , t.fimages,
                      t.furl,
                      
                      t.flast_update
FROM            nobat_allnobats INNER JOIN
                         nobat_level1 ON nobat_allnobats.FldidLastLevel = nobat_level1.Fldid INNER JOIN
                         nobat_level2_items AS t ON nobat_level1.FldIdlevel2_Items = t.Fldid, (SELECT @row_number := 0) AS x
WHERE        (t.FldDeleted = 0) AND (t.FldActive = 1) AND  (nobat_allnobats.FldActive = 1) AND (nobat_allnobats.FldDeleted = 0) AND (nobat_level1.FldDeleted = 0) AND (nobat_level1.FldActive = 1) AND 
                         (nobat_allnobats.FldFlag = 0)) AS ty  where  ' , Wheree  );

 


  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  
   
   end if ;
   
   IF flLevel=3 then 
   
     SET @stmt_str = CONCAT(' SELECT *,(@row_number := @row_number + 1)   AS RowNumber
FROM
	(
	SELECT DISTINCT
		nobat_level3_items.Fldid,
		nobat_level3_items.FldIdlevel4_Items,
		nobat_level3_items.Fldvoicepath,
		nobat_level3_items.Fldtitle,
		nobat_level3_items.FldActive,
		nobat_level3_items.FldidDB,
		nobat_level3_items.FldPcName,
        	nobat_level3_items.FldWebDesc		 ,
		nobat_level3_items.FldDeleted,
		nobat_level3_items.FldHostName,
		nobat_level3_items.FldInsertTime,
		nobat_level3_items.FldInsertUser 
	FROM
		nobat_level3_items
		INNER JOIN nobat_level2_items ON nobat_level3_items.Fldid = nobat_level2_items.FldIdlevel3_Items
		INNER JOIN nobat_level1 ON nobat_level2_items.Fldid = nobat_level1.FldIdlevel2_Items
		INNER JOIN nobat_allnobats ON nobat_level1.Fldid = nobat_allnobats.FldidLastLevel , (SELECT @row_number := 0) AS x
	WHERE
		( nobat_level2_items.FldDeleted = 0 ) 
		AND ( nobat_level2_items.FldActive = 1 ) 
	 
		AND ( nobat_allnobats.FldActive = 1 ) 
		AND ( nobat_allnobats.FldDeleted = 0 ) 
		AND ( nobat_level1.FldDeleted = 0 ) 
		AND ( nobat_level1.FldActive = 1 ) 
	 
		AND ( nobat_level3_items.FldActive = 1 ) 
		AND ( nobat_level3_items.FldDeleted = 0 ) 
	 
	AND ( nobat_allnobats.FldFlag = 0 ) 
	) AS ty
                         
                        
                         where  ' , Wheree  );

 


  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  
   
   end if ;
   IF flLevel=4 then 
   
     SET @stmt_str = CONCAT('   SELECT *, (@row_number := @row_number + 1)   AS RowNumber
   FROM (SELECT DISTINCT 
                         nobat_level4_items.Fldid, nobat_level4_items.Fldvoicepath      	 ,	nobat_level4_items.FldWebDesc	, nobat_level4_items.Fldtitle, nobat_level4_items.FldActive, nobat_level4_items.FldidDB, nobat_level4_items.FldPcName, nobat_level4_items.FldDeleted, 
                         nobat_level4_items.FldHostName, nobat_level4_items.FldInsertTime, nobat_level4_items.FldInsertUser
FROM            nobat_allnobats INNER JOIN
                         nobat_level1 ON nobat_allnobats.FldidLastLevel = nobat_level1.Fldid INNER JOIN
                         nobat_level2_items AS t ON nobat_level1.FldIdlevel2_Items = t.Fldid INNER JOIN
                         nobat_level3_items ON t.FldIdlevel3_Items = nobat_level3_items.Fldid INNER JOIN
                         nobat_level4_items ON nobat_level3_items.FldIdlevel4_Items = nobat_level4_items.Fldid , (SELECT @row_number := 0) AS x
WHERE        (t.FldDeleted = 0) AND (t.FldActive = 1) AND   (nobat_allnobats.FldActive = 1) AND (nobat_allnobats.FldDeleted = 0) AND (nobat_level1.FldDeleted = 0) AND (nobat_level1.FldActive = 1) AND 
                           (nobat_level3_items.FldActive = 1) AND (nobat_level3_items.FldDeleted = 0)  
                         AND (nobat_allnobats.FldFlag = 0) AND  (nobat_level4_items.FldActive = 1) AND (nobat_level4_items.FldDeleted = 0)  ) AS ty 
  where  ' , Wheree  );

 


  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
  
   
   end if ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_ReturnAllNobatTime_ByWhere` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_ReturnAllNobatTime_ByWhere`( 
  in  fdate date,
    in  flastleve int,
  in   fidlastlevel int,
    in  Type_ int,
   in   Favetime int
   )
BEGIN
   
  	  call  SPNobat_DeactiveNearNobats();
      IF  Type_ = 0 then
        SELECT
      COUNT(*)
    FROM nobat_allnobats AS t
    WHERE t.flddeleted = 0
    AND t.FldActive = 1
    AND fldflag = 0
    AND t.FldLastLevel =  flastleve
    AND t.FldidLastLevel =  fidlastlevel
    AND FldDate =  fdate;
end if ;


      IF  Type_ = 1 then
        SELECT
      FldTimeStart,
      FldTimeEnd,
      FldTimeStartSTR,
      FldTimeEndSTR,
      Fldid,FldDate
    FROM nobat_allnobats AS t
    WHERE t.flddeleted = 0
    AND t.FldActive = 1
    AND fldflag = 0
    AND t.FldLastLevel =  flastleve
    AND t.FldidLastLevel =  fidlastlevel
    AND FldDate =  fdate
    AND FldTimeStart < 720; 
end if ;
      IF  Type_ = 2 then
         SELECT
      FldTimeStart,
      FldTimeEnd,
      FldTimeStartSTR,
      FldTimeEndSTR,
      Fldid,FldDate
    FROM nobat_allnobats AS t
    WHERE t.flddeleted = 0
    AND t.FldActive = 1
    AND fldflag = 0
    AND t.FldLastLevel =  flastleve
    AND t.FldidLastLevel =  fidlastlevel
    AND FldDate =  fdate
    AND FldTimeStart BETWEEN 720 AND 1080;
end if ;
      IF  Type_ = 3 then
         SELECT
      FldTimeStart,
      FldTimeEnd,
      FldTimeStartSTR,
      FldTimeEndSTR,
      Fldid,FldDate
    FROM nobat_allnobats AS t
    WHERE t.flddeleted = 0
    AND t.FldActive = 1
    AND fldflag = 0
    AND t.FldLastLevel =  flastleve
    AND t.FldidLastLevel =  fidlastlevel
    AND FldDate =  fdate
    AND FldTimeStart BETWEEN 1080 AND 1440;
end if ;

	 IF  Type_ = 7 then
	 
	   SELECT DISTINCT   *  FROM (
        SELECT
     count(*) as 'count' , 'Morning' as tp
    FROM nobat_allnobats AS t
    WHERE t.flddeleted = 0
    AND t.FldActive = 1
    AND fldflag = 0
    AND t.FldLastLevel =  flastleve
    AND t.FldidLastLevel =  fidlastlevel
    AND FldDate =  fdate
    AND FldTimeStart < 720

      union  
         SELECT
       count(*) as 'count' , 'Noon' as tp
    FROM nobat_allnobats AS t
    WHERE t.flddeleted = 0
    AND t.FldActive = 1
    AND fldflag = 0
    AND t.FldLastLevel =  flastleve
    AND t.FldidLastLevel =  fidlastlevel
    AND FldDate =  fdate
    AND FldTimeStart BETWEEN 720 AND 1080

       union
         SELECT
          count(*) as 'count' , 'evening' as tp  
    FROM nobat_allnobats AS t
    WHERE t.flddeleted = 0
    AND t.FldActive = 1
    AND fldflag = 0
    AND t.FldLastLevel =  flastleve
    AND t.FldidLastLevel =  fidlastlevel
    AND FldDate =  fdate
    AND FldTimeStart BETWEEN 1080 AND 1440
	
	 ) as t  ;
	 end if ;

      IF  Type_ = 4 then
         SELECT
      FldTimeStart,
      FldTimeEnd,
      FldTimeStartSTR,
      FldTimeEndSTR,
      Fldid,FldDate
    FROM nobat_allnobats AS t
    WHERE t.flddeleted = 0
    AND t.FldActive = 1
    AND fldflag = 0
    AND t.FldLastLevel =  flastleve
    AND t.FldidLastLevel =  fidlastlevel
    AND FldDate =  fdate;
 end if ;
      IF  Type_ = 5 AND  Favetime >= 0 then
 
	   SELECT DISTINCT   *  FROM (
	   
	 (  SELECT 
        FldTimeStart,  FldTimeEnd,  FldTimeStartSTR,   FldTimeEndSTR,  Fldid ,FldDate
      FROM nobat_allnobats AS t
      WHERE t.flddeleted = 0  AND t.FldActive = 1   AND fldflag = 0  AND t.FldLastLevel = 1  AND t.FldidLastLevel =  fidlastlevel
      AND FldDate =  fdate  AND FldTimeStart <=  Favetime   AND t.FldTimeEnd >=  Favetime   limit 1    )

    union

   (  SELECT   FldTimeStart,   FldTimeEnd,  FldTimeStartSTR,  FldTimeEndSTR,  Fldid  ,FldDate
      FROM nobat_allnobats AS t
      WHERE t.flddeleted = 0
      AND t.FldActive = 1  AND fldflag = 0   AND t.FldLastLevel =  flastleve   AND t.FldidLastLevel =  fidlastlevel
      AND FldDate =  fdate   AND FldTimeStart <=  Favetime   ORDER BY FldTimeStart DESC   limit 2  )
	  
    UNION	  
 
   (  SELECT       FldTimeStart,   FldTimeEnd,   FldTimeStartSTR,   FldTimeEndSTR,   Fldid  ,FldDate
      FROM nobat_allnobats AS t
      WHERE t.flddeleted = 0 AND t.FldActive = 1   AND fldflag = 0   AND t.FldLastLevel =  flastleve
      AND t.FldidLastLevel =  fidlastlevel   AND FldDate =  fdate  AND FldTimeStart >=  Favetime
      ORDER BY FldTimeStart   limit 2)
	  ) as dt   ORDER BY Fldid  ;
	 end if ;
	  IF  Type_ = 6 then
SELECT          FldTimeStart, FldTimeEnd, FldTimeStartSTR, FldTimeEndSTR, Fldid, FldDate
FROM            nobat_allnobats AS t
WHERE        (FldDeleted = 0) AND (FldActive = 1) AND (FldFlag = 0) AND (FldLastLevel =  flastleve) AND (FldidLastLevel =  fidlastlevel) AND (Fldid >  Favetime) limit 1 ;
end if;
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_ReturnIdsLevel1ByIdLevel2` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_ReturnIdsLevel1ByIdLevel2`(in Param1 int )
BEGIN
	 declare  EndDate   datetime ;
	 declare End_day_interval int ;
  set End_day_interval   = (select   nobat_settings.fldval from nobat_settings where fldkey ='End_day_interval'  limit 1);

     set   EndDate = DATE_ADD( now(), INTERVAL End_day_interval  DAY)    ;
      
       SELECT *,
 (@row_number := @row_number + 1)   AS RowNumber  FROM (
SELECT distinct
   t.Fldid, t.IdCustomer, t.FldIdlevel2_Items, t.Fldvoicepath, t.Fldtitle, t.FldActive, t.FldidDB, t.FldPcName, t.FldSex, t.FldNationalCode, t.FldMobile, t.FldJobTitle, t.FldActive_OV, t.Fldvoicepath_OV, t.FldShortCode, t.FldWebDesc, 
                         t.FldHostName, t.FldInsertTime, t.FldInsertUser, t.FldDeleted, t.fimages,
                      t.furl,
                      t.fhtml,
                      t.flast_update

						  ,t.FldLastCommensCount as commentsCount ,  CASE
    WHEN t.FldLastCommensCount >0  THEN round( t.FldLasRating/t.FldLastCommensCount , 2)  
    ELSE 0
END as avrageRating  ,  CASE
    WHEN t.FldLastCommensCount >0  THEN round(( t.FldLastSuggest/t.FldLastCommensCount)*100 , 2)  
    ELSE 0
END  as SuggestCount
FROM 
  nobat_level1 t
  INNER JOIN nobat_allnobats
    ON t.Fldid = nobat_allnobats.FldidLastLevel , (SELECT @row_number := 0) AS x 
WHERE t.FldDeleted = 0
AND t.FldActive = 1
 
AND nobat_allnobats.FldActive = 1
AND nobat_allnobats.FldDeleted = 0
AND nobat_allnobats.FldFlag = 0
AND nobat_allnobats.FldDate<= EndDate) as ty   WHERE ty.Fldid IN (SELECT DISTINCT nobat_level1.Fldid
FROM            nobat_allnobats INNER JOIN
                         nobat_level1 ON nobat_allnobats.FldidLastLevel = nobat_level1.Fldid INNER JOIN
                         nobat_level2_items ON nobat_level1.FldIdlevel2_Items = nobat_level2_items.Fldid
WHERE        (nobat_level2_items.Fldid = Param1) AND (nobat_level2_items.FldDeleted = 0) AND (nobat_level2_items.FldActive = 1)   AND  
                         (nobat_level1.FldDeleted = 0) AND (nobat_level1.FldActive = 1)   AND (nobat_allnobats.FldFlag = 0) AND (nobat_allnobats.FldDeleted = 0) AND (nobat_allnobats.FldActive = 1) AND 
                         (nobat_allnobats.FldDate <= EndDate));


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_ReturnIdsLevel2ByIdLevel3` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_ReturnIdsLevel2ByIdLevel3`(in Param1 int )
BEGIN
	 declare  EndDate   datetime ;
	 declare End_day_interval int ;
  set End_day_interval   = (select   nobat_settings.fldval from nobat_settings where fldkey ='End_day_interval'  limit 1);

     set   EndDate = DATE_ADD( now(), INTERVAL End_day_interval  DAY)    ;
      
  SELECT *,
 (@row_number := @row_number + 1)   AS RowNumber  FROM (SELECT DISTINCT t.*
FROM            nobat_allnobats INNER JOIN
                         nobat_level1 ON nobat_allnobats.FldidLastLevel = nobat_level1.Fldid INNER JOIN
                         nobat_level2_items AS t ON nobat_level1.FldIdlevel2_Items = t.Fldid   , (SELECT @row_number := 0) AS x
WHERE        (t.FldDeleted = 0) AND (t.FldActive = 1)  AND (nobat_allnobats.FldActive = 1) AND (nobat_allnobats.FldDeleted = 0) AND (nobat_allnobats.FldFlag = 0) AND (nobat_allnobats.FldDate <= EndDate) 
                         AND (nobat_level1.FldDeleted = 0) AND (nobat_level1.FldActive = 1)  
) AS ty
  WHERE ty.Fldid IN (SELECT DISTINCT nobat_level2_items.Fldid
 FROM nobat_level3_items
  INNER JOIN nobat_level2_items
    ON nobat_level3_items.Fldid = nobat_level2_items.FldIdlevel3_Items
  INNER JOIN nobat_level1
    ON nobat_level2_items.Fldid = nobat_level1.FldIdlevel2_Items
  INNER JOIN nobat_allnobats
    ON nobat_level1.Fldid = nobat_allnobats.FldidLastLevel
WHERE        (nobat_level2_items.FldDeleted = 0) AND (nobat_level2_items.FldActive = 1)  AND   (nobat_level1.FldDeleted = 0) AND 
                         (nobat_level1.FldActive = 1)   AND (nobat_allnobats.FldFlag = 0) AND (nobat_allnobats.FldDeleted = 0) AND (nobat_allnobats.FldActive = 1) AND (nobat_allnobats.FldDate <= EndDate) 
                         AND   (nobat_level3_items.FldDeleted = 0) AND (nobat_level3_items.FldActive = 1)   AND (nobat_level3_items.Fldid = Param1));
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPNobat_ReturnIdsLevel3ByIdLevel4` */;
DELIMITER ;;
CREATE  PROCEDURE `SPNobat_ReturnIdsLevel3ByIdLevel4`(in Param1 int )
BEGIN
	 declare  EndDate   datetime ;
	 declare End_day_interval int ;
  set End_day_interval   = (select   nobat_settings.fldval from nobat_settings where fldkey ='End_day_interval'  limit 1);

     set   EndDate = DATE_ADD( now(), INTERVAL End_day_interval  DAY)    ;
      
        SELECT *,
 (@row_number := @row_number + 1)   AS RowNumber 
	  FROM (SELECT DISTINCT 
                         nobat_level3_items.*
FROM            nobat_allnobats INNER JOIN
                         nobat_level1 ON nobat_allnobats.FldidLastLevel = nobat_level1.Fldid INNER JOIN
                         nobat_level2_items AS t ON nobat_level1.FldIdlevel2_Items = t.Fldid INNER JOIN
                         nobat_level3_items ON t.FldIdlevel3_Items = nobat_level3_items.Fldid INNER JOIN
                         nobat_level4_items ON nobat_level3_items.FldIdlevel4_Items = nobat_level4_items.Fldid , (SELECT @row_number := 0) AS x 
WHERE        (t.FldDeleted = 0) AND (t.FldActive = 1)  AND (nobat_allnobats.FldActive = 1) AND (nobat_allnobats.FldDeleted = 0) AND (nobat_allnobats.FldFlag = 0) AND (nobat_allnobats.FldDate <= EndDate) 
                         AND (nobat_level1.FldDeleted = 0) AND (nobat_level1.FldActive = 1) AND   (nobat_level3_items.FldActive = 1) AND 
                         (nobat_level3_items.FldDeleted = 0) AND   (nobat_level4_items.FldActive = 1) AND (nobat_level4_items.FldDeleted = 0)   
                         ) AS ty 
  WHERE ty.Fldid IN (SELECT DISTINCT nobat_level3_items.Fldid
FROM            nobat_allnobats INNER JOIN
                         nobat_level1 ON nobat_allnobats.FldidLastLevel = nobat_level1.Fldid INNER JOIN
                         nobat_level2_items ON nobat_level1.FldIdlevel2_Items = nobat_level2_items.Fldid INNER JOIN
                         nobat_level3_items ON nobat_level2_items.FldIdlevel3_Items = nobat_level3_items.Fldid INNER JOIN
                         nobat_level4_items ON nobat_level3_items.FldIdlevel4_Items = nobat_level4_items.Fldid
WHERE        (nobat_level2_items.FldDeleted = 0) AND (nobat_level2_items.FldActive = 1)  AND   (nobat_level1.FldDeleted = 0) AND 
                         (nobat_level1.FldActive = 1) AND  (nobat_allnobats.FldFlag = 0) AND (nobat_allnobats.FldDeleted = 0) AND (nobat_allnobats.FldActive = 1) AND (nobat_allnobats.FldDate <= EndDate) 
                           AND (nobat_level3_items.FldDeleted = 0) AND (nobat_level3_items.FldActive = 1)   AND 
                         (nobat_level4_items.FldActive = 1) AND (nobat_level4_items.FldDeleted = 0)   AND (nobat_level4_items.Fldid = Param1));

 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `Spnobat_settingsGet` */;
DELIMITER ;;
CREATE  PROCEDURE `Spnobat_settingsGet`()
BEGIN
Select *    From  nobat_settings    where  flddeleted = 0 ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPorders_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPorders_AddUpdate`(
IN `i_d` BIGINT, 
IN `o_rdercode` VARCHAR(255) CHARSET utf8mb4, 
IN `f_idproduct` BIGINT, 
IN `f_idcustomer` BIGINT, 
IN `f_status` VARCHAR(255) CHARSET utf8mb4, 
 IN `f_desc` VARCHAR(955) CHARSET utf8mb4, 
 IN `f_host` VARCHAR(955) CHARSET utf8mb4 
)
BEGIN
 
declare lastcronmin integer ;
  IF i_d > 0 THEN
      
   
       UPDATE  orders
            SET 
               fidproduct  = f_idproduct ,   fidcustomer =f_idcustomer  ,   fstatus = f_status ,   fdesc = f_desc ,  fhost  = f_host 
                
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
    set lastcronmin = (select max(cronmin) +1  from  orders );
              
              INSERT  INTO  orders  ( ordercode, fidproduct ,fidcustomer  , fstatus , fdesc ,     fhost   , cronmin          )
               VALUES ( o_rdercode,  f_idproduct ,f_idcustomer  , f_status , f_desc ,     f_host  , lastcronmin ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPpages_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPpages_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
IN `f_html` LONGTEXT CHARSET utf8mb4,
 IN `f_layout` LONGTEXT CHARSET utf8mb4,
IN `f_author` VARCHAR(255) CHARSET utf8mb4, 
IN `f_type` VARCHAR(255) CHARSET utf8mb4, 
 IN `f_com_type` VARCHAR(255) CHARSET utf8mb4, 
IN `f_active` TINYINT,
IN `no_html` TINYINT ,
IN `f_canedit` VARCHAR(255) CHARSET utf8mb4 ,
IN `f_desc` VARCHAR(955) CHARSET utf8mb4,
IN `f_ctitle` VARCHAR(955) CHARSET utf8mb4,
  IN `f_canonical` VARCHAR(1245) CHARSET utf8mb4 ,
IN `f_picAlt` VARCHAR(655) CHARSET utf8mb4 ,
IN `f_keys` VARCHAR(1255) CHARSET utf8mb4 ,
IN `f_image` VARCHAR(1900) CHARSET utf8mb4, 
IN `f_fixtype` VARCHAR(955) CHARSET utf8mb4
)
BEGIN
  declare f_last_update datetime ;
 set f_last_update =   now() ;
   IF i_d > 0 THEN
   if   no_html > 0  then
			UPDATE pages  SET 
              fimage=f_image ,  fkeys =f_keys ,   fcanonical=f_canonical ,fpicAlt=f_picAlt , fname=f_name , factive=f_active,    flast_update=f_last_update , flayout=f_layout , fctitle=f_ctitle ,
               fauthor=f_author ,ftype=f_type   , fcom_type=f_com_type , fcanedit=f_canedit , fdesc=f_desc, ffixtype=f_fixtype
			WHERE id = i_d    ;
         else
         	 UPDATE pages  SET 
               fimage=f_image ,  fkeys =f_keys ,   fcanonical=f_canonical ,fpicAlt=f_picAlt ,   fname=f_name , factive=f_active,  fhtml=f_html, flast_update=f_last_update , flayout=f_layout , fctitle = f_ctitle ,
               fauthor=f_author ,ftype=f_type    , fcom_type=f_com_type ,    fcanedit=f_canedit, fdesc=f_desc, ffixtype=f_fixtype
			WHERE id = i_d     ;
         end if;
		 select i_d  as id;
  END IF;
  IF i_d = 0 THEN
              INSERT  INTO  pages (fhtml,fauthor,ftype,factive,fname,flast_update ,fcom_type ,fcanedit  , fdesc ,ffixtype ,fctitle ,fpicAlt , fcanonical , fkeys ,fimage , flayout
             )
               VALUES (f_html,f_author,f_type,f_active,f_name,f_last_update ,f_com_type ,f_canedit , f_desc ,f_fixtype , f_ctitle , f_picAlt  , f_canonical ,f_keys , f_image , f_layout
                   ) ;
    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPPaymethods_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPPaymethods_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
 
IN `f_type` VARCHAR(255) CHARSET utf8mb4, 
IN `f_desc` LONGTEXT CHARSET utf8mb4,
IN `f_extra` LONGTEXT CHARSET utf8mb4,
IN `f_active_coupon` TINYINT ,
IN `f_active_wallet` TINYINT ,
IN `f_active_Virtual` TINYINT ,
IN `f_only_wallet` TINYINT , 
IN `f_active_Amazing` TINYINT ,
IN `f_min_Value` bigint ,
IN `f_max_Value` bigint ,
IN `f_images` VARCHAR(900) CHARSET utf8mb4, 
IN `f_active` TINYINT
)
BEGIN

 

  IF i_d > 0 THEN
       UPDATE billpaymethods
            SET 
             fmax_Value = f_max_Value , fmin_Value =f_min_Value ,   fname=f_name , factive=f_active,   fdesc=f_desc   , fextra=f_extra  , factive_coupon=f_active_coupon , factive_wallet= f_active_wallet
                , factive_Virtual=f_active_Virtual ,fonly_wallet=f_only_wallet , factive_Amazing = f_active_Amazing , fimages=f_images
                , fupdatetime = now()
                  
         WHERE id = i_d ;
		 select i_d  as id;
  END IF;
  IF i_d = 0 THEN
              INSERT  INTO  billpaymethods (fmax_Value, fmin_Value , fname  , factive ,   fdesc    , fextra ,ftype  , factive_coupon , factive_wallet,factive_Virtual , fonly_wallet,factive_Amazing,fimages)
               VALUES ( f_max_Value ,f_min_Value , f_name , f_active,      f_desc   , f_extra ,f_type ,f_active_coupon ,f_active_wallet,f_active_Virtual  ,f_only_wallet,f_active_Amazing,f_images) ;
    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPpostscatag_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPpostscatag_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
 
IN `f_images` LONGTEXT CHARSET utf8mb4,
IN `f_content` LONGTEXT CHARSET utf8mb4,
IN `f_layout` LONGTEXT CHARSET utf8mb4,
IN `f_html` LONGTEXT CHARSET utf8mb4,
IN `f_comissionP` int(5),
IN `f_author` VARCHAR(255) CHARSET utf8mb4, 
IN `f_type` VARCHAR(255) CHARSET utf8mb4,
 IN `f_ctitle` VARCHAR(255) CHARSET utf8mb4,
 IN `f_products_msg` VARCHAR(1255) CHARSET utf8mb4, 
 IN `f_products_msg2` VARCHAR(1255) CHARSET utf8mb4, 
 IN `f_parent` BIGINT, 
IN `f_keys` VARCHAR(1255) CHARSET utf8mb4,
  IN `f_canonical` VARCHAR(1245) CHARSET utf8mb4 ,
IN `f_picAlt` VARCHAR(655) CHARSET utf8mb4 ,
 IN `f_isLink`tinyint(3), 
 
  IN `f_show_inMainCatags`tinyint(3), 
   IN `f_show_inRmnue`tinyint(3), 
    IN `f_show_inMegamenue`tinyint(3), 
     IN `f_show_inElemans`tinyint(3), 
     
 IN `f_allowupdateImage` TINYINT   , 
IN `f_active` TINYINT
)
BEGIN

  declare f_last_update datetime ;
 set f_last_update =   now() ;

  IF i_d > 0 THEN
      
   
       UPDATE postscatag
            SET 
           fcanonical=f_canonical ,fpicAlt=f_picAlt , fshow_inMainCatags=f_show_inMainCatags ,  fshow_inRmnue =f_show_inRmnue  , fshow_inMegamenue = f_show_inMegamenue ,fshow_inElemans  = f_show_inElemans ,  
                fname=f_name , factive=f_active,fimages=f_images  ,  flast_update=f_last_update , fproducts_msg=f_products_msg, fproducts_msg2=f_products_msg2,
                fcontent=f_content ,fauthor=f_author   ,fkeys=f_keys ,fparent=f_parent ,flayout=f_layout , fctitle=f_ctitle
                , fcomissionP= f_comissionP , fisLink= f_isLink  , fallowupdateImage = f_allowupdateImage
                
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  postscatag (
              fshow_inMainCatags , fshow_inRmnue  , fshow_inMegamenue , fshow_inElemans ,  
              fisLink,fcomissionP,fcontent,fhtml,fauthor,ftype,fkeys,factive,fimages,fname,flast_update,fparent,flayout ,
              fctitle,fproducts_msg,fproducts_msg2 ,fpicAlt , fcanonical , fallowupdateImage
             )
               VALUES (
               f_show_inMainCatags , f_show_inRmnue  , f_show_inMegamenue , f_show_inElemans ,  
               f_isLink,f_comissionP, f_content,f_html,f_author,f_type,f_keys,f_active,f_images,f_name,f_last_update,f_parent,f_layout ,
               f_ctitle,f_products_msg,f_products_msg2 , f_picAlt  , f_canonical ,f_allowupdateImage
                   ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPpostscatag_UpdateHTML` */;
DELIMITER ;;
CREATE  PROCEDURE `SPpostscatag_UpdateHTML`(
IN `i_d` BIGINT, 
IN `f_html` LONGTEXT CHARSET utf8mb4
)
BEGIN

  declare f_last_update datetime ;
 set f_last_update =   now() ;

  IF i_d > 0 THEN
      
   
       UPDATE postscatag
            SET 
                fhtml=f_html   , flast_update=f_last_update    WHERE id = i_d ; 
                select i_d  as id;
   
  END IF;

  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPPosts_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPPosts_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_idwebuser` BIGINT, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
IN `f_imagescount` INT, 
IN `f_images` LONGTEXT CHARSET utf8mb4,
IN `f_content` LONGTEXT CHARSET utf8mb4,
IN `f_layout` LONGTEXT CHARSET utf8mb4,
IN `f_html` LONGTEXT CHARSET utf8mb4,
IN `f_author` VARCHAR(255) CHARSET utf8mb4, 
IN `f_ctitle` VARCHAR(500) CHARSET utf8mb4, 
IN `f_type` VARCHAR(255) CHARSET utf8mb4, 
IN `f_idCateg` INT,
 
IN `f_keys` VARCHAR(1255) CHARSET utf8mb4, 
 IN `f_canonical` VARCHAR(1245) CHARSET utf8mb4 ,
IN `f_picAlt` VARCHAR(655) CHARSET utf8mb4 ,
IN `f_active` TINYINT
)
BEGIN

  declare f_last_update datetime ;
 set f_last_update =   now() ;

  IF i_d > 0 THEN
      
   
       UPDATE posts
            SET 
              fcanonical=f_canonical ,fpicAlt=f_picAlt ,   fname=f_name , factive=f_active,fimages=f_images  , fidCateg=f_idCateg   , flast_update=f_last_update , fctitle=f_ctitle ,
                fimagescount=f_imagescount ,fcontent=f_content ,fauthor=f_author ,ftype=f_type ,fkeys=f_keys ,flayout=f_layout
                
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  posts (fctitle,fimagescount,fcontent,fhtml,fauthor,ftype,fidCateg,fkeys,factive,fimages,fname,flast_update,flayout,fpicAlt , fcanonical , fidwebuser
             )
               VALUES (f_ctitle,f_imagescount,f_content,f_html,f_author,f_type,f_idCateg,f_keys,f_active,f_images,f_name,f_last_update ,f_layout , f_picAlt  , f_canonical , f_idwebuser
                   ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPPosts_UpdateHTML` */;
DELIMITER ;;
CREATE  PROCEDURE `SPPosts_UpdateHTML`(
IN `i_d` BIGINT, 
IN `f_html` LONGTEXT CHARSET utf8mb4,
IN `f_extra` LONGTEXT CHARSET utf8mb4
)
BEGIN

  declare f_last_update datetime ;
 set f_last_update =   now() ;

  IF i_d > 0 THEN
      
   
       UPDATE posts
            SET 
                fhtml=f_html   , flast_update=f_last_update  , fextra=f_extra   WHERE id = i_d ; 
                select i_d  as id;
   
  END IF;

  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPPost_AllComments` */;
DELIMITER ;;
CREATE  PROCEDURE `SPPost_AllComments`(IN `Wheree` VARCHAR(1055) CHARSET utf8mb4, IN `limitt` INT)
BEGIN
   
 	  	  if  length(LTRIM(rtrim(Wheree)))<2  then
	  set  Wheree=' 1=1' ;
      end if;
      
        SET @stmt_str = CONCAT('  

(select c.* , p.fname as pname from post_comments as c inner join posts as p on p.id = c.fidpost where p.fdeleted=0 and c.fdeleted=0   ', Wheree, '
ORDER BY  c.id   )
union all 
(select c.* , p.fname as pname from post_comments as c inner join products as p on p.id = c.fidpost where p.fdeleted=0 and c.fdeleted=0   ', Wheree, '
ORDER BY  c.id )


 limit ', limitt, ' ');
  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
   
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPpost_comments_Aprov` */;
DELIMITER ;;
CREATE  PROCEDURE `SPpost_comments_Aprov`(IN t_ype  int , IN idComment  int   )
BEGIN
   
 
 
 
        update post_comments set fstatus = t_ype where  id=idComment and fdeleted=0  ;

  



     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPProductsAtribute_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPProductsAtribute_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_key` VARCHAR(255) CHARSET utf8mb4, 
IN `f_idCateg` int,  
IN `f_type` VARCHAR(255) CHARSET utf8mb4, 
IN `f_active` TINYINT
)
BEGIN

declare co integer ;
       set   co  =  (select count(id ) as id   from product_allattribute where fkey = f_key and  fidCateg = f_idCateg) ;
       
       if  co > 0  then
        set i_d =   (select  id       from product_allattribute where fkey = f_key  and  fidCateg = f_idCateg) ;
       end if ;


  IF i_d > 0 THEN
      
   
       UPDATE product_allattribute
            SET 
                fkey=f_key , factive=f_active    ,ftype=f_type  , fidCateg = f_idCateg
                
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  product_allattribute (fkey,  ftype, factive  ,fidCateg   )
               VALUES (f_key, f_type, f_active    ,    f_idCateg      ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPProducts_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPProducts_AddUpdate`(
 IN `i_d` BIGINT, 
IN `f_name` VARCHAR(955) CHARSET utf8mb4,
 IN `f_latiName` VARCHAR(955) CHARSET utf8mb4, 
IN `f_desc` LONGTEXT CHARSET utf8mb4, 
IN `f_info1` LONGTEXT CHARSET utf8mb4, 
IN `f_info2` LONGTEXT CHARSET utf8mb4, 
IN `f_html` LONGTEXT CHARSET utf8mb4,
IN `f_images` LONGTEXT CHARSET utf8mb4,
IN `f_active` TINYINT,
 IN `f_comissionP` TINYINT, 
IN `f_idCateg` INT,
IN `f_keys` VARCHAR(1255) CHARSET utf8mb4 ,
IN `f_is_down` INT,
IN `f_is_virtual` INT,
IN `f_sku` VARCHAR(255) CHARSET utf8mb4 ,
IN `f_is_soon` INT,
IN `f_layout` LONGTEXT CHARSET utf8mb4,
IN `f_isService` INT,
IN `f_id_brand` INT,
IN `f_idCarrierId` longtext  CHARSET utf8mb4,
IN `f_tax` INT,
IN `f_tax_shenase` VARCHAR(145) CHARSET utf8mb4 ,
IN `f_taxUnit` VARCHAR(145) CHARSET utf8mb4 ,
IN `f_type` varchar(200) CHARSET utf8mb4, 
IN `f_weight` decimal(10,2),
IN `f_length` decimal(10,2),
IN `f_width` decimal(10,2),
IN `f_height` decimal(10,2),
IN `f_creatorInfo` longtext CHARSET utf8mb4 ,
IN `f_canonical` VARCHAR(1245) CHARSET utf8mb4 ,
IN `f_picAlt` VARCHAR(655) CHARSET utf8mb4 ,
IN `f_zarib` INT,
IN `f_ctitle` VARCHAR(555) CHARSET utf8mb4 
)
BEGIN

   IF i_d > 0 THEN
  
  
   
                    
                    
       
       UPDATE products
            SET 
           fidCarrierId = f_idCarrierId ,  fpicAlt=f_picAlt ,   fzarib=f_zarib ,   fname=f_name ,  fidCateg=f_idCateg  , fcomissionP=f_comissionP   , fcanonical=f_canonical  
                ,fdesc=f_desc, fimages=f_images ,factive=f_active, 
                  fkeys= f_keys ,
                fis_down=f_is_down ,fis_virtual =f_is_virtual , fis_soon=f_is_soon , 
flayout=f_layout , fctitle=f_ctitle ,
                   ftax = f_tax ,ftaxUnit=f_taxUnit,ftax_shenase=f_tax_shenase
               ,finfo1 = f_info1 ,finfo2 = f_info2,
                  fid_brand = f_id_brand   ,fweight = f_weight ,flength = f_length   ,fwidth = f_width  ,   fheight = f_height 
              ,ftype=f_type , fhtml=f_html  
                 , fsku = f_sku , flatiName = f_latiName, fisService = f_isService 
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  products (fidCarrierId ,fzarib , fpicAlt,  fcanonical ,fcomissionP ,
            fname , fdesc,fhtml,fimages,factive, 
             fidCateg ,fkeys ,fis_down ,fis_virtual ,fis_soon  ,
             fweight ,flength,fwidth,fheight ,fsku, fid_brand ,finfo1,finfo2,flatiName , fisService  
            ,fcomments  ,fsuggests ,  flayout ,fctitle ,  ftax,ftaxUnit,ftax_shenase,ftype , fcreatorInfo)
               VALUES (f_idCarrierId ,f_zarib ,f_picAlt , f_canonical ,f_comissionP ,
                   f_name , f_desc,f_html,f_images, f_active, 
                   f_idCateg , f_keys,f_is_down ,f_is_virtual ,f_is_soon , 
                   f_weight ,f_length,f_width,f_height, f_sku, f_id_brand ,f_info1,f_info2 ,f_latiName ,  f_isService 
                    ,  0 ,0 ,   f_layout , f_ctitle ,  f_tax,f_taxUnit,f_tax_shenase,f_type, f_creatorInfo) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPProducts_UpdateHTML` */;
DELIMITER ;;
CREATE  PROCEDURE `SPProducts_UpdateHTML`(
IN `i_d` BIGINT, 
IN `f_html` LONGTEXT CHARSET utf8mb4
)
BEGIN

  declare f_last_update datetime ;
 set f_last_update =   now() ;

  IF i_d > 0 THEN
      
   
       UPDATE products
            SET 
                fhtml=f_html        WHERE id = i_d ; 
                select i_d  as id;
   
  END IF;

  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPProducts_Varients_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPProducts_Varients_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_price` BIGINT, 
IN `f_ronding` BIGINT, 
IN `f_down_extra` LONGTEXT CHARSET utf8mb4,
IN `f_active` TINYINT, 
IN `f_off` INT, 
IN `a_mazing_foff` INT, 
IN `f_is_Single_sale` INT,
IN `f_is_freeShip` INT,
IN `f_Manage_stock_quantity` INT,
IN `f_stock_quantity` INT,
IN `f_low_stock_amount` INT,
IN `f_idproduct` bigint,
IN `f_idstore` bigint,
IN `f_canShappingByMainStore` tinyint,
IN `f_canShappingBySeller` tinyint,
IN `f_daystoSendMainStore` tinyint,
IN `f_daystoSendCustomerByMainStore` tinyint,
IN `f_daystoSendCustomerBySeller` tinyint,
IN `f_inMainStoreStock` tinyint,
 IN `f_max_sell_quantity` INT,
IN `f_is_amazing` INT,
IN `f_is_soon` INT,
IN `f_weight` decimal(10,2),
IN `f_length` decimal(10,2),
IN `f_width` decimal(10,2),
IN `f_height` decimal(10,2),
IN `f_type` varchar(200) CHARSET utf8mb4, 
IN `f_garantidesc` varchar(2245) CHARSET utf8mb4,
IN `f_customBuyBoxdesc` varchar(2245) CHARSET utf8mb4, 
IN `famazing_startDate`  VARCHAR(255) CHARSET utf8mb4 ,
in famazing_endDate  VARCHAR(255) CHARSET utf8mb4 ,
in famazing_startTime  VARCHAR(255) CHARSET utf8mb4 ,
in famazing_endTime   VARCHAR(255) CHARSET utf8mb4 
)
BEGIN
  declare Oldfis_amazing int ;
  declare  Oldfprice int ;
    declare Oldamazing_foff int ;
  declare  Oldoff int ;
    declare Oldfactive int ;
  declare  Oldfronding int ;
  declare  f_date_update_price datetime ;
  IF i_d > 0 THEN
         set   Oldfis_amazing = ( select  fis_amazing  from  products_varients where id = i_d  );
         set   Oldamazing_foff = ( select  amazing_foff  from  products_varients where id = i_d  );
         set  Oldfprice = ( select  fprice  from  products_varients where id = i_d  );
         set  Oldoff = ( select  foff  from  products_varients where id = i_d  );
         set   Oldfronding = ( select  fronding  from  products_varients where id = i_d  );
         set   Oldfactive = ( select  factive  from  products_varients where id = i_d  );
      
	   if     Oldfprice <> f_price      then  
		   set f_date_update_price =   now() ;
         else
          set f_date_update_price =   ( select  fdate_update_price  from  products_varients where id = i_d  );
       END IF; 
       UPDATE products_varients
            SET 
                 fprice=f_price , fis_soon = f_is_soon ,  fcustomBuyBoxdesc=f_customBuyBoxdesc  , fronding=f_ronding 
                 , fdaystoSendCustomerByMainStore=f_daystoSendCustomerByMainStore  
                 , fdaystoSendCustomerBySeller=f_daystoSendCustomerBySeller 
                 , fgarantidesc=f_garantidesc 
                 , finMainStoreStock=f_inMainStoreStock 
                   ,factive=f_active,foff=f_off,
                     fweight = f_weight ,flength = f_length   ,fwidth = f_width  ,   fheight = f_height ,
                fdate_update_price= f_date_update_price ,  
                  fcanShappingBySeller=f_canShappingBySeller,fcanShappingByMainStore=f_canShappingByMainStore,
                  fdaystoSendMainStore=f_daystoSendMainStore,
                fis_amazing= f_is_amazing, ftype=f_type , amazing_startDate=famazing_startDate ,
                amazing_endDate=famazing_endDate , amazing_startTime=famazing_startTime 
                , fManage_stock_quantity= f_Manage_stock_quantity,  fis_Single_sale= f_is_Single_sale,amazing_endTime = famazing_endTime
                ,fstock_quantity = f_stock_quantity 
                ,flow_stock_amount = f_low_stock_amount
               , fis_freeShip=f_is_freeShip ,fidproduct=f_idproduct 
                 ,fidstore = f_idstore  ,   fmax_sell_quantity = f_max_sell_quantity,
                    fdown_extra = f_down_extra , amazing_foff=a_mazing_foff , fdeleted = 0 
         WHERE id = i_d ;
		 select i_d  as id;
  END IF;
  IF i_d = 0 THEN
              INSERT  INTO  products_varients (
          fronding,  fprice, factive,foff, fis_soon ,
            fdate_update_price ,  fis_amazing ,ftype,amazing_startDate ,
           amazing_endDate ,amazing_startTime,amazing_endTime , fis_Single_sale,fManage_stock_quantity,fstock_quantity,flow_stock_amount ,
           fmax_sell_quantity, fidproduct, fdown_extra , fsellcount ,
         amazing_foff ,  fis_freeShip,fidstore ,fcanShappingBySeller,fcanShappingByMainStore,fdaystoSendMainStore ,
         fdaystoSendCustomerByMainStore , fgarantidesc , fcustomBuyBoxdesc , finMainStoreStock , fdaystoSendCustomerBySeller 
         ,  fweight ,flength,fwidth,fheight )
               VALUES (
                  f_ronding,  f_price,  
                   f_active,f_off ,  f_is_soon ,  now()    ,  f_is_amazing ,
                   f_type,   famazing_startDate  ,     famazing_endDate 
                   ,famazing_startTime,famazing_endTime ,f_is_Single_sale , f_Manage_stock_quantity,f_stock_quantity,f_low_stock_amount ,
                    f_max_sell_quantity, f_idproduct,   
                     f_down_extra ,0,  a_mazing_foff  , f_is_freeShip ,f_idstore ,  f_canShappingBySeller,f_canShappingByMainStore,
                     f_daystoSendMainStore,f_daystoSendCustomerByMainStore , f_garantidesc , f_customBuyBoxdesc, f_inMainStoreStock , f_daystoSendCustomerBySeller 
                     , f_weight ,f_length,f_width,f_height) ;
    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPproduct_attribute_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPproduct_attribute_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_value` VARCHAR(9955) CHARSET utf8mb4, 
IN `f_view_mode` VARCHAR(9955) CHARSET utf8mb4, 
 IN `f_enable_variation` tinyint, 
  IN `f_attribute_visibility` tinyint, 
IN `f_idatribute` bigint, 
IN `f_order` VARCHAR(40) CHARSET utf8mb4, 
IN `f_idproduct` bigint
)
BEGIN

    
	   declare co integer ;
       set   co  =  (select count(id ) as id   from product_attribute where idproduct = f_idproduct and idatribute=f_idatribute  ) ;
       
       if  co > 0  then
        set i_d =   (select  id       from product_attribute where idproduct = f_idproduct and idatribute=f_idatribute ) ;
       end if ; 
 

  IF i_d > 0 THEN
      
   
            UPDATE product_attribute
            SET 
                fview_mode=f_view_mode ,  fvalue=f_value   , fattribute_visibility=f_attribute_visibility , fenable_variation=f_enable_variation
             ,   forder = f_order
            WHERE id = i_d ;
         
                   
         

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
            
              INSERT  INTO  product_attribute (fvalue,  idproduct, idatribute  ,fattribute_visibility  , fenable_variation , fview_mode , forder)
               VALUES (f_value, f_idproduct, f_idatribute   ,f_attribute_visibility,       f_enable_variation  ,f_view_mode ,f_order  ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPproduct_brand_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPproduct_brand_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_idInsertUser` BIGINT, 
IN `f_name` VARCHAR(900) CHARSET utf8mb4, 
 IN `f_latinName` VARCHAR(900) CHARSET utf8mb4,  
 IN `f_images` VARCHAR(1900) CHARSET utf8mb4, 
 IN `f_layout`longtext CHARSET utf8mb4, 
  IN `f_idcatags`mediumtext CHARSET utf8mb4,  
  IN `f_ctitle` VARCHAR(555) CHARSET utf8mb4,   
  IN `f_desc` VARCHAR(955) CHARSET utf8mb4,  
  IN `f_canonical` VARCHAR(1245) CHARSET utf8mb4 ,
IN `f_picAlt` VARCHAR(655) CHARSET utf8mb4 ,
IN `f_keys` VARCHAR(1255) CHARSET utf8mb4 ,
IN `f_active` TINYINT
)
BEGIN

declare co integer ;
       set   co  =  (select count(id ) as id   from product_brand where fname = f_name  ) ;
       
       if  co > 0  then
        set i_d =   (select  id       from product_brand where fname = f_name  limit 1 ) ;
       end if ;


  IF i_d > 0 THEN
      
   
       UPDATE product_brand
            SET 
           fkeys =f_keys ,   fcanonical=f_canonical ,fpicAlt=f_picAlt ,  fname=f_name , factive=f_active , fctitle= f_ctitle , fdesc=f_desc , flatinName=f_latinName  , fimages=f_images , flayout =f_layout ,fidcatags=f_idcatags
               ,  flast_update = now()
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  product_brand (fname,   factive  ,flatinName ,fimages ,flayout , fidcatags , fctitle ,fdesc ,fpicAlt , fcanonical , fkeys , fidInsertUser)
               VALUES (f_name,  f_active       ,f_latinName  ,f_images   ,f_layout , f_idcatags , f_ctitle,f_desc , f_picAlt  , f_canonical ,f_keys , f_idInsertUser)  ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPProduct_CATAGS_LEVELS` */;
DELIMITER ;;
CREATE  PROCEDURE `SPProduct_CATAGS_LEVELS`(  IN id_gatag  int    )
BEGIN
   
 
 select  fname , id , furl, fisLink  from 
 (select fname , id , furl , fisLink from postscatag WHERE id = id_gatag  and fdeleted = 0 
 union all
 select      parent_name  , parent_id, parent_url , ifnull( parent_fisLink, 0 ) as parent_fisLink 
from   (SELECT @r AS catag_id, 
   (SELECT @r := fparent    FROM postscatag WHERE id = catag_id and fdeleted = 0 ) AS parent_id, 
    (SELECT  @n := fname  FROM postscatag WHERE id = catag_id and fdeleted = 0 ) AS parent_name, 
    (SELECT  @w := furl  FROM postscatag WHERE id = catag_id and fdeleted = 0 ) AS parent_url, 
    (SELECT  @z := fisLink  FROM postscatag WHERE id = catag_id and fdeleted = 0 ) AS parent_fisLink, 
   @l := @l + 1 AS level 
 FROM (SELECT @r := id_gatag, @l := 0) val, postscatag WHERE @r <> 0 ) as tbl ) as tb where id <> 0 ;
 
 


 
  
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPRating_AllComments` */;
DELIMITER ;;
CREATE  PROCEDURE `SPRating_AllComments`(IN `Wheree` VARCHAR(1055) CHARSET utf8mb4, IN `limitt` INT)
BEGIN
   
   call SPNobat_DeactiveNearNobats();
   	  	  if  length(LTRIM(rtrim(Wheree)))<2  then
	  set  Wheree=' 1=1' ;
      end if;
      
        SET @stmt_str = CONCAT('SELECT   rating.Fldid ,  fMilladyToShamsi_NoTime( nobat_allnobats.FldDate) AS FldDatePER,  fMilladyToShamsi_ByTime( nobat_allnobats.FldCallTime) AS PersianCallTime,  nobat_allnobats.FldidLastLevel, 
                         tblwebusers.FldName, tblwebusers.FldLastName, tblwebusers.FldSex, tblwebusers.FldNationalCode as FldCodeMeli , tblwebusers.FldMobile as FldMobileNO,   rating.FldRate,   rating.FldStatus,   rating.FldComment, 
                          rating.FldIdNobat,  rating.FldIdCustomer, nobat_level1.Fldtitle,  nobat_level2_items.Fldtitle AS  level2_Items_Fldtitle,  nobat_allnobats.FldFlag,  nobat_allnobats.FldAproved,  nobat_allnobats.FldActive
FROM            tblwebusers INNER JOIN
                          rating ON tblwebusers.Fldid =  rating.FldIdCustomer INNER JOIN
                          nobat_allnobats ON  rating.FldIdNobat =  nobat_allnobats.Fldid INNER JOIN
                         nobat_level1 ON  nobat_allnobats.FldidLastLevel = nobat_level1.Fldid INNER JOIN
                          nobat_level2_items ON nobat_level1.FldIdlevel2_Items =  nobat_level2_items.Fldid
WHERE        ( nobat_allnobats.FldDeleted = 0) AND ( rating.flddeleted = 0)   ', Wheree, '
ORDER BY  nobat_allnobats.Fldid   limit ', limitt, ' ');
  PREPARE stmt FROM @stmt_str;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
   
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPRating_AllCommentsByIdLevel1` */;
DELIMITER ;;
CREATE  PROCEDURE `SPRating_AllCommentsByIdLevel1`(IN IdLevel1  bigint  , IN limitt INT)
BEGIN
   
   call SPNobat_DeactiveNearNobats();
   	  	 
SELECT         rating.Fldid,  ( rating.FldInsertTime) AS insertTime,  tblwebusers.FldName,  tblwebusers.FldLastName,  rating.FldRate,  rating.FldComment,  rating.FldSuggest
FROM             tblwebusers INNER JOIN
                          rating ON  tblwebusers.Fldid =  rating.FldIdCustomer INNER JOIN
                          nobat_allnobats ON  rating.FldIdNobat =  nobat_allnobats.Fldid
WHERE        ( nobat_allnobats.FldDeleted = 0) AND ( rating.flddeleted = 0) AND ( rating.FldStatus = 2) AND ( nobat_allnobats.FldidLastLevel = IdLevel1)
ORDER BY  rating.FldInsertTime DESC  limit limitt ;
         
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPrenewSearchObjects` */;
DELIMITER ;;
CREATE  PROCEDURE `SPrenewSearchObjects`(
 
IN `r_id` BIGINT, 
IN `f_weight` BIGINT, 
IN `t_type` varchar(200) CHARSET utf8mb4 , 
 IN `f_word` varchar(200) CHARSET utf8mb4 
)
BEGIN
  DECLARE id_all_search_words BIGINT;

  
  INSERT INTO all_search_words (word) 
  VALUES (f_word) 
  ON DUPLICATE KEY UPDATE word = f_word, id = LAST_INSERT_ID(id);

  SET id_all_search_words = LAST_INSERT_ID();

  IF id_all_search_words > 0 THEN
    INSERT INTO all_search_relations (id_search_word, refid, fweight, ftype) 
    VALUES (id_all_search_words, r_id, f_weight, t_type);
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPReportsAdd` */;
DELIMITER ;;
CREATE  PROCEDURE `SPReportsAdd`(IN `R_ptid` INT, IN `_rptstring` LONGTEXT CHARSET utf8mb4, IN `Rptname` VARCHAR(200) CHARSET utf8mb4, IN `ModuleID` INT)
BEGIN
 
insert reports(Rptid,RptContent,Rptname,ModuleID,FormCode) VALUES( R_ptid ,_rptstring,Rptname,ModuleID, 1 );

    SELECT   LAST_INSERT_ID();

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPReportsUpdateAndLog` */;
DELIMITER ;;
CREATE  PROCEDURE `SPReportsUpdateAndLog`(IN `R_ptid` INT, IN `_rptstring` LONGTEXT CHARSET utf8mb4)
BEGIN
insert tblreportlog(FldReport,FldName,FldIdUser) select RptContent,Rptname,1 from reports where RptContent is Not NULL and RptID=R_ptid ;
update reports set RptContent=_rptstring  where RptID=R_ptid ;
 select RptID from  reports where RptID = R_ptid;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPReports_FindByid` */;
DELIMITER ;;
CREATE  PROCEDURE `SPReports_FindByid`(IN `R_ptid` INT)
BEGIN
select * from reports where Rptid =  R_ptid  ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPreview_and_rate_Aprov` */;
DELIMITER ;;
CREATE  PROCEDURE `SPreview_and_rate_Aprov`(IN t_ype  int , IN idComment  int   )
BEGIN
   
  declare f_iditem bigint;
 
 declare commentsCount int   ;
 Declare SumRate bigint;
  Declare endRate bigint  ;
 declare SuggestCount int   ;
  declare Suggest_per int   ;
  
    declare f_id_VarientProduct bigint;
   declare commentsCount_VarientProduct int   ;
 Declare SumRate_VarientProduct bigint;
  Declare endRate_VarientProduct bigint  ;
 declare SuggestCount_VarientProduct int   ;
  declare Suggest_per_VarientProduct int   ;
  
  
    declare f_idstore bigint;
   declare commentsCount_store int   ;
 Declare SumRate_store bigint;
  Declare endRate_store bigint  ;
 declare SuggestCount_store int   ;
  declare Suggest_per_store int   ;
 
  
 set commentsCount = 0;
  set SumRate = 0;
   set SuggestCount = 0;
    set  Suggest_per = 0;
    
   set commentsCount_VarientProduct = 0;
  set SumRate_VarientProduct = 0;
   set SuggestCount_VarientProduct = 0;
    set  Suggest_per_VarientProduct = 0; 

     set commentsCount_store = 0;
  set SumRate_store = 0;
   set SuggestCount_store = 0;
    set  Suggest_per_store= 0; 

    
update tbl_review_and_rate set fstatus = t_ype where  id=idComment and fdeleted=0  ;


 
set f_iditem = (  select  fiditem from tbl_review_and_rate where id = idComment );
set f_id_VarientProduct = (  select  fidproducts_varients  from tbl_review_and_rate where id = idComment );
set f_idstore = (  select  fidstore  from tbl_review_and_rate where id = idComment );


set commentsCount = ( SELECT COUNT(*) FROM tbl_review_and_rate where fiditem = f_iditem and ( fstatus = 2)
  AND ( fdeleted = 0) and ftype = "product" );
set commentsCount_VarientProduct = ( SELECT COUNT(*) FROM tbl_review_and_rate where fidproducts_varients = f_id_VarientProduct and ( fstatus = 2)
  AND ( fdeleted = 0) and ftype = "product" );
set commentsCount_store = ( SELECT COUNT(*) FROM tbl_review_and_rate where fidstore = f_idstore and ( fstatus = 2)
  AND ( fdeleted = 0) and ftype = "product" );


set SumRate = (  SELECT sum( frate) FROM tbl_review_and_rate where fiditem = f_iditem and ( fstatus = 2)
  AND ( fdeleted = 0) and ftype = "product" );
set SumRate_VarientProduct = (  SELECT sum( frate) FROM tbl_review_and_rate where fidproducts_varients = f_id_VarientProduct and ( fstatus = 2)
  AND ( fdeleted = 0) and ftype = "product" );
set SumRate_store = (  SELECT sum( frate) FROM tbl_review_and_rate where fidstore = f_idstore and ( fstatus = 2)
  AND ( fdeleted = 0) and ftype = "product" );


set SuggestCount = ( SELECT COUNT(*)   FROM tbl_review_and_rate where fiditem = f_iditem and ( fstatus = 2)
  AND ( fdeleted = 0) and ftype = "product"  and fsuggest = 1  ) ;
set SuggestCount_VarientProduct = ( SELECT COUNT(*)   FROM tbl_review_and_rate where fidproducts_varients = f_id_VarientProduct  and ( fstatus = 2)
  AND ( fdeleted = 0) and ftype = "product"  and fsuggest = 1  ) ;  
set SuggestCount_store = ( SELECT COUNT(*)   FROM tbl_review_and_rate where fidstore = f_idstore  and ( fstatus = 2)
  AND ( fdeleted = 0) and ftype = "product"  and fsuggest = 1  ) ;    
  
  
  set commentsCount_VarientProduct = (ifnull(commentsCount_VarientProduct ,0 ) ) ;
  set SumRate_VarientProduct = (ifnull(SumRate_VarientProduct ,0 ))  ;
   set SuggestCount_VarientProduct = ( ifnull(SuggestCount_VarientProduct ,0 ))  ;
 
  set commentsCount = (ifnull(commentsCount ,0 ) ) ;
  set SumRate = (ifnull(SumRate ,0 ))  ;
   set SuggestCount = ( ifnull(SuggestCount ,0 ))  ;
   
    set commentsCount_store = (ifnull(commentsCount_store ,0 ) ) ;
  set SumRate_store = (ifnull(SumRate_store ,0 ))  ;
   set SuggestCount_store = ( ifnull(SuggestCount_store ,0 ))  ; 


 if commentsCount > 0 and  SumRate > 0 then
set endRate = (  SumRate  / commentsCount ) ;
end if ;
 if commentsCount_VarientProduct > 0 and  SumRate_VarientProduct > 0 then
set endRate_VarientProduct = (  SumRate_VarientProduct  / commentsCount_VarientProduct ) ;
end if ;

  if commentsCount_store > 0 and  SumRate_store > 0 then
set endRate_store = (  SumRate_store  / commentsCount_store ) ;
end if ;


update products set  frate = endRate , fcomments= commentsCount      , fsuggests=SuggestCount where   id = f_iditem   ;

update products set  frate = 100 , fcomments= 0   , fsuggests=0 where   fcomments  is null or  fcomments =0  ;

update products_varients set  frate = endRate_VarientProduct , fcomments= commentsCount_VarientProduct      , fsuggests=SuggestCount_VarientProduct  where   id = f_id_VarientProduct   ;

update products_varients set  frate = 100 , fcomments= 0   , fsuggests=0  where   fcomments  is null or  fcomments =0 ;


update stores set  frate = endRate_store , fcomments= commentsCount_store      , fsuggests=SuggestCount_store  where   id = f_idstore   ;

update stores  set  frate = 100 , fcomments= 0   , fsuggests=0  where   fcomments  is null or  fcomments =0 ;


select endRate,endRate_VarientProduct,endRate_store ;
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `spSerachFromWeb` */;
DELIMITER ;;
CREATE  PROCEDURE `spSerachFromWeb`(IN `Wheree` VARCHAR(1055) CHARSET utf8mb4, IN `limitt` INT)
BEGIN

   set  Wheree=(select  concat( '%', Wheree ,'%' ));
   
   
SELECT       nobat_level1.Fldid, nobat_level1.Fldtitle, nobat_level1.FldActive, nobat_level1.FldSex, nobat_level1.FldShortCode, nobat_level1.FldWebDesc, nobat_level2_items.Fldtitle AS Fldtitle2
  ,nobat_level1.FldLastCommensCount as commentsCount , 
  CASE  
      WHEN nobat_level1.FldLastCommensCount >0  THEN round( nobat_level1.FldLasRating/nobat_level1.FldLastCommensCount , 2)  
      ELSE 0
  END as avrageRating
    ,
CASE  
      WHEN nobat_level1.FldLastCommensCount >0  THEN round(( nobat_level1.FldLastSuggest/nobat_level1.FldLastCommensCount)*100 , 2)  
      ELSE 0
  END as  SuggestCount   , nobat_level1.fimages,
                      nobat_level1.furl,
                      nobat_level1.fhtml,
                      nobat_level1.flast_update
 
FROM            nobat_level1 INNER JOIN
                         nobat_level2_items ON nobat_level1.FldIdlevel2_Items = nobat_level2_items.Fldid
WHERE      (  (nobat_level2_items.FldDeleted = 0) AND (nobat_level1.FldDeleted = 0)) and
                        (  (nobat_level1.FldShortCode LIKE Wheree) or   (nobat_level2_items.Fldtitle LIKE Wheree)  or (nobat_level1.Fldtitle LIKE Wheree)) limit limitt  ;
   
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPSMS_AllSMSSended_UserMessages` */;
DELIMITER ;;
CREATE  PROCEDURE `SPSMS_AllSMSSended_UserMessages`(   
in idCustomer bigint ,
   in count bigint  )
BEGIN

SELECT        allsmssended.tell, allsmssended.message, fMilladyToShamsi_ByTime( allsmssended.insertTime ) as insertTime  , allsmssended.result, tblwebusers.Fldid
 
FROM            allsmssended INNER JOIN
                         tblwebusers ON allsmssended.tell = tblwebusers.FldMobile
						 where tblwebusers.fldid = idCustomer
						 order by allsmssended.insertTime desc limit count  ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPStores_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPStores_AddUpdate`(
IN `i_d` BIGINT,
 IN `f_idwebuser` BIGINT, 
IN `f_name` VARCHAR(900) CHARSET utf8mb4, 
 IN `f_latinName` VARCHAR(900) CHARSET utf8mb4,  
 IN `f_images` VARCHAR(1900) CHARSET utf8mb4, 
 IN `f_layout`longtext CHARSET utf8mb4, 
  IN `f_ctitle` VARCHAR(555) CHARSET utf8mb4,   
  IN `f_desc` VARCHAR(955) CHARSET utf8mb4,  
 
  
   IN `i_s_new` tinyint(3)  ,  
      IN `i_s_official` tinyint(3)  , 
         IN `i_s_trusted` tinyint(3)  , 
         IN `f_status` VARCHAR(555) CHARSET utf8mb4,   
          IN `f_comissionP` tinyint(3)  , 
         IN `f_id_province_cities` int, 
IN `f_plak` VARCHAR(255) CHARSET utf8mb4, 
IN `f_vahed` VARCHAR(255) CHARSET utf8mb4, 
IN `f_postalcode` VARCHAR(255) CHARSET utf8mb4, 
IN `f_street` VARCHAR(255) CHARSET utf8mb4, 
 IN `f_mapCenter` VARCHAR(255) CHARSET utf8mb4, 
  IN `f_mapAddress` longtext CHARSET utf8mb4, 
  
    IN `f_BankInfo` longtext CHARSET utf8mb4, 
         
          IN `o_n_no_return` tinyint(3)  , 
           IN `o_n_commitment` tinyint(3)  , 
            IN `o_n_time_shipping` tinyint(3)  , 
            
    IN `f_name_og` VARCHAR(555) CHARSET utf8mb4,  
      IN `f_encode_og` VARCHAR(555) CHARSET utf8mb4,  
        IN `f_sabtNo_og` VARCHAR(555) CHARSET utf8mb4,  
          IN `f_address_og` VARCHAR(1055) CHARSET utf8mb4,  
            IN `f_tell_og` VARCHAR(555) CHARSET utf8mb4,  IN `f_supportMobile` VARCHAR(555) CHARSET utf8mb4,  
              IN `f_shenaseMeli_og` VARCHAR(555) CHARSET utf8mb4,  
IN `f_active` TINYINT
)
BEGIN

declare co integer ;
       set   co  =  (select count(id ) as id   from stores where fidwebuser = f_idwebuser  ) ;
       
       if  co > 0  then
        set i_d =   (select  id from stores where fidwebuser = f_idwebuser ) ;
       end if ;


  IF i_d > 0 THEN
      
   
       UPDATE stores
            SET 
              fcomissionP=f_comissionP ,  fname=f_name , factive=f_active , fctitle= f_ctitle , fdesc=f_desc , flatinName=f_latinName  , fimages=f_images , flayout =f_layout  ,
                fname_og=f_name_og ,  fencode_og=f_encode_og ,fsabtNo_og=f_sabtNo_og , faddress_og=f_address_og , ftell_og=f_tell_og , fshenaseMeli_og=f_shenaseMeli_og ,
                is_new=i_s_new,is_official=i_s_official, is_trusted=i_s_trusted, fstatus=f_status ,  
                on_no_return=o_n_no_return,on_commitment=o_n_commitment,on_time_shipping=o_n_time_shipping  ,
                fBankInfo=f_BankInfo, fdeleted = 0 , fsupportMobile=f_supportMobile ,
                fid_province_cities=f_id_province_cities , fplak =f_plak , fpostalcode =f_postalcode , fvahed=f_vahed
                ,fstreet =f_street ,  fmapAddress=f_mapAddress , fmapCenter=f_mapCenter
                
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  stores (fcomissionP,fname,   factive  ,flatinName ,fimages ,flayout ,  fctitle , fdesc , fidwebuser , fname_og ,fencode_og   ,fsabtNo_og  ,faddress_og 
              , ftell_og  ,fshenaseMeli_og  ,is_new , is_official , is_trusted ,  frate ,on_no_return ,on_commitment ,on_time_shipping,
               fid_province_cities , fplak ,  fpostalcode,fvahed , fstreet ,  fmapAddress , fmapCenter ,fBankInfo , fsupportMobile  )
               VALUES (f_comissionP ,f_name,  f_active       ,f_latinName  ,f_images   ,f_layout ,  f_ctitle , f_desc ,f_idwebuser , f_name_og ,f_encode_og   ,f_sabtNo_og  ,f_address_og  
               , f_tell_og  ,f_shenaseMeli_og  ,i_s_new , i_s_official , i_s_trusted ,   100 , 100, 100, 100 ,
               f_id_province_cities , f_plak , f_postalcode,f_vahed , f_street, f_mapAddress , f_mapCenter ,f_BankInfo , f_supportMobile ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPstory_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPstory_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
 IN `f_extra` LONGTEXT CHARSET utf8mb4,
 IN `f_items` LONGTEXT CHARSET utf8mb4,
 
 
IN `f_desc` LONGTEXT CHARSET utf8mb4,
 IN `f_allowSellersAdd` TINYINT ,
IN `f_active` TINYINT
)
BEGIN

 

IF i_d > 0 THEN
       UPDATE story
            SET 
               fname=f_name , factive=f_active,   fdesc=f_desc  , fextra=f_extra  , fitems=f_items , fallowSellersAdd=f_allowSellersAdd
                  
                  
         WHERE id = i_d ;
		 select i_d  as id;
  END IF;
  IF i_d = 0 THEN
              INSERT  INTO  story (  fname ,fextra , factive ,   fdesc  ,fitems  , fallowSellersAdd   )
               VALUES ( f_name , f_extra, f_active,      f_desc  ,f_items  , f_allowSellersAdd  ) ;
    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPtags_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPtags_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_idwebuser` BIGINT, 
IN `f_name` VARCHAR(900) CHARSET utf8mb4, 
 
 IN `f_images` VARCHAR(1900) CHARSET utf8mb4, 
 IN `f_layout`longtext CHARSET utf8mb4, 
 
  IN `f_ctitle` VARCHAR(555) CHARSET utf8mb4,   
  IN `f_desc` VARCHAR(955) CHARSET utf8mb4,  
IN `f_active` TINYINT
)
BEGIN

declare co integer ;
       set   co  =  (select count(id ) as id   from tags where fname = f_name  ) ;
       
       if  co > 0  then
        set i_d =   (select  id       from tags where fname = f_name  limit 1 ) ;
       end if ;


  IF i_d > 0 THEN
      
   
       UPDATE tags
            SET 
                fname=f_name , factive=f_active , fctitle= f_ctitle , fdesc=f_desc ,  fimages=f_images , flayout =f_layout  
               ,  flast_update = now()
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  tags (fname,   factive    ,fimages ,flayout   , fctitle ,fdesc , fidwebuser)
               VALUES (f_name,  f_active       ,f_images   ,f_layout  , f_ctitle,f_desc , f_idwebuser ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `sptblexcelemailsSenderSettings_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `sptblexcelemailsSenderSettings_AddUpdate`(IN   f_title   VARCHAR(150) CHARSET utf8mb4, IN  f_data  longtext  CHARSET utf8mb4   )
BEGIN

  
 
   if (select count(*) from emailsend_settings where ftitle = f_title ) > 0 then    
  update emailsend_settings set fdata=f_data   where ftitle = f_title    ;
  else  
  INSERT INTO emailsend_settings  (fdata, ftitle) VALUES  
 (f_data , f_title ) ;
  end if; 



END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `sptblexcelemails_list_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `sptblexcelemails_list_AddUpdate`(IN   f_email   VARCHAR(150) CHARSET utf8mb4, IN   f_name   VARCHAR(150)  CHARSET utf8mb4 , IN   u_tm_id   VARCHAR(150)  CHARSET utf8mb4, IN   u_tm_source   VARCHAR(150)  CHARSET utf8mb4
, IN   u_rl   VARCHAR(150)  CHARSET utf8mb4, IN   u_tm_title   VARCHAR(150)  CHARSET utf8mb4, IN   f_title   VARCHAR(150)  CHARSET utf8mb4, IN   c_hecked   integer  )
BEGIN

  
 
   if (select count(*) from excelemails_list where femail = f_email ) > 0 then    
  update excelemails_list set fname=f_name , utm_id=u_tm_id , utm_source=u_tm_source , url=u_rl , utm_title=u_tm_title
  , checked=c_hecked  where ftitle = f_title   and  femail = f_email ;
  else  
  INSERT INTO excelemails_list  (femail, fname, utm_id ,utm_source ,url,utm_title ,ftitle,checked ) VALUES  
 (f_email, f_name, u_tm_id ,u_tm_source ,u_rl,u_tm_title ,f_title,c_hecked ) ;
  end if; 



END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `spTblHolidaysGet` */;
DELIMITER ;;
CREATE  PROCEDURE `spTblHolidaysGet`()
BEGIN
 select FldId , FldTitle, DATE_FORMAT( FldDate,'%Y/%m/%d') AS FldDate   from tblholidays where flddeleted=0 ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `sptblUsers_Insert` */;
DELIMITER ;;
CREATE  PROCEDURE `sptblUsers_Insert`(
IN `F_ldUsername` VARCHAR(2250) CHARSET utf8mb4,
 IN `F_ldPassword` VARCHAR(2250) CHARSET utf8mb4, 
 IN `F_ldname` VARCHAR(950) CHARSET utf8mb4,
 IN `F_ldLastName` VARCHAR(950) CHARSET utf8mb4,
 IN `F_ldEmail` VARCHAR(150) CHARSET utf8mb4,
 IN `F_ldMobile` VARCHAR(20) CHARSET utf8mb4,
 IN `F_ldActivation` TINYINT(1),
 IN `F_ldType` TINYINT(5),
 IN `F_ldIsAdmin` TINYINT(1),
 IN `F_ldNeedPassChange` TINYINT(1))
BEGIN
 declare id bigint ;
 
set F_ldMobile=LTRIM(rtrim(F_ldMobile));
set F_ldUsername=LTRIM(rtrim(F_ldUsername));
set F_ldPassword=LTRIM(rtrim(F_ldPassword));

 
set id= (select fldid from tblusers where FldUsername=F_ldUsername  or   FldMobile = F_ldMobile limit 1);
if  id>0  then
		update tblusers set FldUsername=F_ldUsername ,   FldMobile = F_ldMobile  ,  FldNeddChangePass=F_ldNeedPassChange  , fldemail=F_ldEmail , FldType = F_ldType ,
		FldPass =F_ldPassword ,  FldIsActive =F_ldActivation  , FldIsAdmin = F_ldIsAdmin  , FldDeleted=0  where fldid =id ;
		select id ;
		 
		else
		 
		INSERT INTO  tblusers(FldUsername, FldPass, Fldname , FldLastName , FldType ,  FldIsActive,  FldIsAdmin ,  FldEmail, FldMobile,   FldNeddChangePass)
						  values(F_ldUsername, F_ldPassword, F_ldname , F_ldLastName ,F_ldType ,  F_ldActivation , F_ldIsAdmin ,  F_ldEmail, F_ldMobile, F_ldNeedPassChange);
		select LAST_INSERT_ID() as id;
end if;


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `sptblWebSettingsPortall_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `sptblWebSettingsPortall_AddUpdate`(IN `F_ldKey` VARCHAR(150) CHARSET utf8mb4, IN `F_ldValue` LONGTEXT CHARSET utf8mb4)
BEGIN


 
UPDATE     tblwebsettingsportall   SET    FldValue =F_ldValue  where FldKey=F_ldKey     ;



END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `sptblWebUsers_ChangePasswordNewPortall` */;
DELIMITER ;;
CREATE  PROCEDURE `sptblWebUsers_ChangePasswordNewPortall`(
in F_ldId int,
 in U_serName varchar(200)  CHARSET utf8mb4,
 in O_ldPassword varchar(200)  CHARSET utf8mb4, 
 in N_ewPassword varchar(200)  CHARSET utf8mb4)
BEGIN

declare IdWebuser int ;
set IdWebuser = -1 ;
set IdWebuser = (select  FldId from tblwebusers where FldId=F_ldId and FldPassword=O_ldPassword   and FldUsername = U_serName) ;


if IdWebuser = -1 or IdWebuser is null  then
 
    select -1 as id ;
 
else
 
    update  tblwebusers set FldPassword=N_ewPassword,   FldNeedPassChange = 0, FldPasswordChangeDate = now()
        where FldId=IdWebuser ;
    select IdWebuser as id;
end if ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `sptblWebUsers_CheckedLogin` */;
DELIMITER ;;
CREATE  PROCEDURE `sptblWebUsers_CheckedLogin`( IN F_ldUsername varchar(50) CHARSET utf8mb4, 
 IN F_ldPassword varchar(200)  CHARSET utf8mb4)
BEGIN

declare F_ldNationalCode varchar(20);
declare IS_Customer tinyint(1);
declare IS_Level1  tinyint(1);
declare IS_Admin  tinyint(1);
declare IS_Seller  tinyint(1);
declare Id_Customer bigint;
declare Id_Level1 bigint;
declare currentID int;
declare tmp varchar(900);

set tmp = ( select  CONCAT( FldId,'___#____',ifnull(FldNationalCode,0) ,'___#____', FldId ,'___#____', ifnull(FldIdLevel1,0) ,'___#____',ifnull(FldIsAdmin,0),'___#____',ifnull(FldIsSeller,0))  as res
from tblwebusers where FldUsername=F_ldUsername and  (FldPassword)=(F_ldPassword) and FldDeleted=0 and FldActivation = 1 );

set currentID =( SELECT SPLIT_STR(tmp,'___#____',1));
set F_ldNationalCode =( SELECT SPLIT_STR(tmp,'___#____',2));
set Id_Customer =( SELECT SPLIT_STR(tmp,'___#____',3));
set Id_Level1 =( SELECT SPLIT_STR(tmp,'___#____',4));
set IS_Admin =( SELECT SPLIT_STR(tmp,'___#____',5));
set IS_Seller =( SELECT SPLIT_STR(tmp,'___#____',6));




 

 if (select COUNT(*) from nobat_level1  where  fldid = Id_Level1  and FldDeleted = 0  )>0 then
  
   set IS_Level1=1 ;
  end if;

if currentID > 0 then
 
	UPDATE tblwebusers
       SET  FldLastLogin  = now()
    WHERE FldId = currentID ;
end if;

if Id_Customer>0 then
set IS_Customer=1 ;
end if;
select *, ifnull(IS_Customer,0)  as IS_Customer,  ifnull(IS_Level1,0)  as IS_Level1 ,  ifnull(IS_Admin,0)  as IS_Admin ,  ifnull(IS_Seller,0)  as IS_Seller 
from tblwebusers where FldId = currentID ;





END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `sptblWebUsers_Insert` */;
DELIMITER ;;
CREATE  PROCEDURE `sptblWebUsers_Insert`(
IN `F_ldUsername` VARCHAR(2250) CHARSET utf8mb4, 
IN `F_ldPassword` VARCHAR(2250) CHARSET utf8mb4, 
IN `F_ldIdCustomer` INT, 
IN `F_ldActivation` TINYINT(1), 
IN `F_ldNationalCode` VARCHAR(20) CHARSET utf8mb4, 
IN `F_ldEmail` VARCHAR(200) CHARSET utf8mb4, 
IN `F_ldMobile` VARCHAR(200) CHARSET utf8mb4, 
IN `F_ldLastPassType` TINYINT(1), 

IN `f_name_og` VARCHAR(445) CHARSET utf8mb4, 
IN `f_encode_og` VARCHAR(45) CHARSET utf8mb4, 
IN `f_shenaseMeli_og` VARCHAR(45) CHARSET utf8mb4, 
IN `f_sabtNo_og` VARCHAR(45) CHARSET utf8mb4, 
IN `f_address_og` VARCHAR(1045) CHARSET utf8mb4, 
IN `f_tell_og` VARCHAR(45) CHARSET utf8mb4, 



IN `F_ldNeedPassChange` TINYINT(1))
BEGIN
 declare id bigint ;
set F_ldNationalCode=LTRIM(rtrim(F_ldNationalCode));
set F_ldMobile=LTRIM(rtrim(F_ldMobile));
set F_ldUsername=LTRIM(rtrim(F_ldUsername));
set F_ldPassword=LTRIM(rtrim(F_ldPassword));

 



set id= (select fldid from tblwebusers where FldUsername=F_ldUsername  or FldMobile = F_ldMobile);
if  id>0  then
		update tblwebusers set     FldNeedPassChange=1    ,fname_og=f_name_og ,fencode_og=f_encode_og , fshenaseMeli_og=f_shenaseMeli_og ,
        fsabtNo_og=f_sabtNo_og, faddress_og=f_address_og , ftell_og=f_tell_og ,
		FldPassword =F_ldPassword , FldActivation =F_ldActivation  , FldDeleted=0  where fldid =id ;
		select id ;
		 
 else
		 
		INSERT INTO  tblwebusers(FldUsername, FldPassword,  FldActivation, FldNationalCode, FldEmail, FldMobile,  FldNeedPassChange , fmnulist,
       fname_og , fencode_og , fshenaseMeli_og ,fsabtNo_og ,faddress_og , ftell_og )
						  values(F_ldUsername, F_ldPassword,  F_ldActivation, F_ldNationalCode, F_ldEmail, F_ldMobile, F_ldNeedPassChange , "webuser" ,
                         f_name_og , fencode_og , f_shenaseMeli_og ,f_sabtNo_og ,f_address_og , f_tell_og  );
		select LAST_INSERT_ID() as id;
end if;


END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `sptblWebUser_ExistEmail` */;
DELIMITER ;;
CREATE  PROCEDURE `sptblWebUser_ExistEmail`(IN  Email VARCHAR(200) CHARSET utf8mb4)
BEGIN

 select ifnull(count( * ),0) as result  from tblwebusers where FldEmail=Email ;



 

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `sptblWebUser_ExistNationalCode` */;
DELIMITER ;;
CREATE  PROCEDURE `sptblWebUser_ExistNationalCode`(IN `nationalCode` VARCHAR(10) CHARSET utf8mb4, IN `checkAll` TINYINT(1))
BEGIN

declare cnt   int  ;
declare currentID int;

set cnt =( select  count(*) from tblwebusers where FldNationalCode=nationalCode and FldDeleted=0) ;
if ifnull(cnt, 0) > 0 then
 
	set cnt = -1 ;
end if ;

 



select ifnull(cnt,0) as result ;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `sptblWebUser_ExistUserName` */;
DELIMITER ;;
CREATE  PROCEDURE `sptblWebUser_ExistUserName`(IN  UserName VARCHAR(100) CHARSET utf8mb4)
BEGIN

 select ifnull(count( * ),0) as result  from tblwebusers where FldUsername=UserName ;



 

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPtbl_faq_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPtbl_faq_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_question` VARCHAR(255) CHARSET utf8mb4, 
IN `f_answer` LONGTEXT CHARSET utf8mb4,
IN `f_images` LONGTEXT CHARSET utf8mb4,
IN `f_author` VARCHAR(255) CHARSET utf8mb4, 
IN `f_idcatags`  mediumtext CHARSET utf8mb4, 
IN `f_keys` VARCHAR(1255) CHARSET utf8mb4, 
IN `f_active` TINYINT
)
BEGIN
 

  IF i_d > 0 THEN
      
   
       UPDATE  tbl_faq
            SET 
                fquestion=f_question , factive=f_active,fimages=f_images  , fidcatags=f_idcatags   , flast_update=now() ,
                fanswer=f_answer , fauthor=f_author   ,fkeys=f_keys 
                
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  tbl_faq  (fquestion,fanswer,fauthor,fidcatags,fkeys,factive,fimages,flast_update
             )
               VALUES (f_question,f_answer,f_author,f_idcatags,f_keys,f_active,f_images,now()
                   ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPtbl_faq_UpdateHTML` */;
DELIMITER ;;
CREATE  PROCEDURE `SPtbl_faq_UpdateHTML`(
IN `i_d` BIGINT, 
IN `f_html` LONGTEXT CHARSET utf8mb4
)
BEGIN

 

  IF i_d > 0 THEN
      
   
       UPDATE  tbl_faq
            SET 
                fhtml=f_html   , flast_update=now()      WHERE id = i_d ; 
                select i_d  as id;
   
  END IF;

  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPtbl_forms_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPtbl_forms_AddUpdate`(
IN `i_d` BIGINT, 
 IN `f_title` varchar(400) CHARSET utf8mb4,
 IN `f_author` varchar(400) CHARSET utf8mb4,
 IN `f_mobiletoSms` varchar(400) CHARSET utf8mb4, 
 IN `f_emailtoSend` varchar(400) CHARSET utf8mb4,
  IN `f_redirectto` varchar(400) CHARSET utf8mb4,
  IN `f_btntext` varchar(100) CHARSET utf8mb4,
   IN `f_successMsg` varchar(550) CHARSET utf8mb4,
   IN `f_failMsg` varchar(550) CHARSET utf8mb4,
 
IN `f_layout` LONGTEXT CHARSET utf8mb4,
 
 
 
IN `f_active` TINYINT
)
BEGIN
 

  IF i_d > 0 THEN
      
   
       UPDATE  tbl_forms
            SET 
                flayout=f_layout , factive=f_active,  flast_update=now()    ,ftitle=f_title  , fauthor=f_author , fredirectto=f_redirectto
                , fmobiletoSms =f_mobiletoSms ,  femailtoSend=f_emailtoSend  , fbtntext =  f_btntext , fsuccessMsg  = f_successMsg  , ffailMsg  = f_failMsg
               
         WHERE id = i_d ;

		 select i_d  as id;
   
  END IF;

  IF i_d = 0 THEN
 
             
              INSERT  INTO  tbl_forms  (flayout,factive,flast_update ,ftitle , fauthor,fmobiletoSms,femailtoSend , fbtntext , fsuccessMsg , ffailMsg ,fredirectto )   
              VALUES (f_layout,f_active,now() ,f_title ,f_author , f_mobiletoSms  , f_emailtoSend  ,f_btntext  , f_successMsg , f_failMsg ,f_redirectto ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPtbl_review_and_rate_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPtbl_review_and_rate_AddUpdate`(
 
 in      i_d bigint,
 in     f_idwebuser bigint,
  in    f_idref bigint,  
  in    f_iditem bigint,

in    f_idstore bigint,
in    f_idproducts_varients bigint,
 in     f_type varchar(400)   CHARSET utf8mb4 ,
 in     f_rate int(10),
 
 in     f_text longtext   CHARSET utf8mb4 ,
in     f_cons longtext   CHARSET utf8mb4 ,
in     f_positivePoints longtext   CHARSET utf8mb4 ,
 in     f_anonymous tinyint(2),
 in     f_title varchar(400)   CHARSET utf8mb4 ,
 in     f_extra longtext   CHARSET utf8mb4 ,
 in     f_suggest tinyint(2)
 )
BEGIN

   DECLARE   varid bigint ;
   
   
   if f_rate<20 then
   set f_rate=20 ;
end if;
     

      IF  i_d > 0  then
	  
		UPDATE  tbl_review_and_rate
            SET 
               frate = f_rate,         fcons = f_cons, 
			   ftext=f_text , fpositivePoints=f_positivePoints ,
               ftitle=f_title,
				 fstatus=1 , fdeleted= 0 ,
				 fsuggest = f_suggest , fanonymous=f_anonymous , flastUpdate=now()
         WHERE   id = i_d  ;

		 select i_d as id ;

		end if ;
      IF i_d = 0 then
          
		
		     SET varid =   (   SELECT   id   FROM tbl_review_and_rate  WHERE  fidwebuser=f_idwebuser  AND  fidref = f_idref and fiditem =f_iditem  limit 1  ) ;
		  IF  varid > 0 then
           SET i_d = varid ;
 end if ;
             IF i_d > 0 then
			  
         UPDATE tbl_review_and_rate    SET   frate = f_rate,         fcons = f_cons, 
			   ftext=f_text , fpositivePoints=f_positivePoints ,
               ftitle=f_title,
				 fstatus=1 , fdeleted= 0 ,
				 fsuggest = f_suggest , fanonymous=f_anonymous , flastUpdate=now()
		 WHERE id = i_d ;
		 
		  SELECT i_d as id ;
         END if;
      IF i_d = 0 then
          
             INSERT tbl_review_and_rate (fiditem,fidref ,  fidwebuser, frate    , 
		 ftext , fsuggest ,ftype ,fcons ,  fpositivePoints , ftitle  , fanonymous ,fextra,fidstore,fidproducts_varients)    VALUES (f_iditem,f_idref ,  f_idwebuser, f_rate ,
		 f_text , f_suggest ,f_type ,f_cons ,  f_positivePoints , f_title ,f_anonymous , f_extra , f_idstore,f_idproducts_varients) 

;
			 
            SELECT last_insert_id() as id ;

         END if ;
   END if ;
     
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPTiketsDetails_Add` */;
DELIMITER ;;
CREATE  PROCEDURE `SPTiketsDetails_Add`(
 
IN `f_idtiket`int, 
 
IN `f_text` longtext CHARSET utf8mb4,
IN `f_data`  longtext CHARSET utf8mb4 ,
IN `f_userId`  int ,
IN `f_type` varchar(200) CHARSET utf8mb4,
 IN `f_inseruser` VARCHAR(255) CHARSET utf8mb4 
)
BEGIN
    INSERT  INTO   codeman_tiketdetails   ( ftext   , fidtiket  ,  fdata   ,fuserId     ,ftype   ,finsertuser          )
   VALUES (f_text  ,    f_idtiket  ,   f_data      ,f_userId  ,f_type ,f_inseruser ) ;

    SELECT  LAST_INSERT_ID() as id;
  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPTikets_Add` */;
DELIMITER ;;
CREATE  PROCEDURE `SPTikets_Add`(
 
 
IN `f_idtype`int, 
IN `f_subject` VARCHAR(255) CHARSET utf8mb4,
IN `f_userId`  int ,
 IN `f_inseruser` VARCHAR(255) CHARSET utf8mb4 
)
BEGIN
   INSERT  INTO  codeman_tikets   (  fidtype  ,fsubject  , fuserId    ,finsertuser             )
   VALUES (    f_idtype , f_subject  , f_userId  ,f_inseruser    ) ;
                  

    SELECT  LAST_INSERT_ID() as id;
  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPuser_favorite_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPuser_favorite_AddUpdate`(
 
IN `i_dwebuser` BIGINT, 
 IN `i_dproduct` BIGINT ,IN `f_idVariantProduct` BIGINT 
)
BEGIN

 declare i_d bigint  ;
 set i_d =(select id from user_favorite where idwebuser=i_dwebuser and idproduct=i_dproduct) ;

  IF i_d  is null THEN
      
    INSERT  INTO  user_favorite (             idwebuser ,   idproduct  , fidVariantProduct      )
               VALUES (         i_dwebuser ,   i_dproduct  , f_idVariantProduct      ) ;
      
      else
   
    delete from user_favorite  WHERE id = i_d ;
		 
  END IF;

 
 
     select * from       user_favorite  where    idwebuser=i_dwebuser ;
             
                  
 
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPvisitors_search_history_updateUserSearchHistory` */;
DELIMITER ;;
CREATE  PROCEDURE `SPvisitors_search_history_updateUserSearchHistory`(IN m_count int ,IN m_max int ,IN f__search varchar(2500) CHARSET utf8mb4)
BEGIN

declare maxcount  int;
set maxcount = ( SELECT MAX(fresultCount)
    FROM visitors_search_history
    WHERE fsearch = f__search) ;
    
if     m_max > maxcount  then
set maxcount = m_max ;
end if;
    
    
UPDATE visitors_search_history
SET    fcount = fcount - 1  + m_count   ,  fresultCount= maxcount 
WHERE fsearch = f__search;








END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPwallet_Add` */;
DELIMITER ;;
CREATE  PROCEDURE `SPwallet_Add`(
IN `f_idwebuser` BIGINT, 
IN `f_deposit` BIGINT, 
IN `f_withdrawal` BIGINT, 
IN `f_desc` LONGTEXT CHARSET utf8mb4,
IN `f_extra` LONGTEXT CHARSET utf8mb4,
IN `f_ref` LONGTEXT CHARSET utf8mb4,
IN `f_insertedUser` BIGINT ,
IN `f_insertedUserFullName` varchar(450) CHARSET utf8mb4,
IN `f_type_ref` LONGTEXT CHARSET utf8mb4 
)
BEGIN
declare balance bigint  ;
START TRANSACTION;

if  f_deposit < 0 or f_withdrawal < 0 then
select -1 as balance;
end if;

if f_deposit > 0 then 
set f_withdrawal = 0 ;
 INSERT  INTO wallet   (  fidwebuser ,  fdeposit    ,  fwithdrawal     ,  fdesc   , fextra     ,   fref   ,    ftype_ref ,finsertedUser , finsertedUserFullName  )
               VALUES ( f_idwebuser ,  f_deposit    ,  0     ,  f_desc   , f_extra     ,   f_ref   ,    f_type_ref  ,f_insertedUser  , f_insertedUserFullName) ;
               
                SELECT  LAST_INSERT_ID() as id;
end if;

if f_withdrawal > 0 then 

set f_deposit = 0 ;

set balance = (	select ifnull( sum(fdeposit) -   sum(fwithdrawal)  , 0 ) as Balance   from   wallet      where     ftype_ref != 'tempTransaction'    and      fidwebuser  = f_idwebuser);

if balance >=  f_withdrawal  then 

 INSERT  INTO wallet   (  fidwebuser ,  fdeposit    ,  fwithdrawal     ,  fdesc   , fextra     ,   fref   ,    ftype_ref   ,finsertedUser  , finsertedUserFullName)
               VALUES ( f_idwebuser ,  0    ,  f_withdrawal     ,  f_desc   , f_extra     ,   f_ref   ,    f_type_ref  ,f_insertedUser ,f_insertedUserFullName  ) ;
               
                SELECT  LAST_INSERT_ID() as id;
       else 
       select -2  as balance ;
                end if ;
end if;
             
   
 COMMIT;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPwallet_Balance` */;
DELIMITER ;;
CREATE  PROCEDURE `SPwallet_Balance`(
IN `f_idwebuser` BIGINT
)
BEGIN

START TRANSACTION;


			select ifnull( sum(fdeposit) -   sum(fwithdrawal)  , 0 ) as Balance   from   wallet      where    fdeleted=0 and      fidwebuser  = f_idwebuser
               and   ftype_ref != 'tempTransaction' ;
   
 COMMIT;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPwallet_Balance_all` */;
DELIMITER ;;
CREATE  PROCEDURE `SPwallet_Balance_all`(
IN `f_idwebuser` BIGINT
)
BEGIN

START TRANSACTION;


			select ifnull( sum(fdeposit) -   sum(fwithdrawal)  , 0 ) as Balance   from   wallet    where  fdeleted=0  
              and   ftype_ref != 'tempTransaction'  ;
   
 COMMIT;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `SPWebuser_bill_address_AddUpdate` */;
DELIMITER ;;
CREATE  PROCEDURE `SPWebuser_bill_address_AddUpdate`(
IN `i_d` BIGINT, 
IN `f_id_province_cities` int, 
IN `f_plak` VARCHAR(255) CHARSET utf8mb4, 
IN `f_vahed` VARCHAR(255) CHARSET utf8mb4, 
IN `f_postalcode` VARCHAR(255) CHARSET utf8mb4, 
IN `f_name` VARCHAR(255) CHARSET utf8mb4, 
IN `f_mobile` VARCHAR(255) CHARSET utf8mb4, 
IN `f_lastname` VARCHAR(255) CHARSET utf8mb4, 
IN `f_street` VARCHAR(255) CHARSET utf8mb4, 
 IN `f_idwebuser` BIGINT, 
 IN `f_mapCenter` VARCHAR(255) CHARSET utf8mb4, 
  IN `f_mapAddress` longtext CHARSET utf8mb4, 
IN `f_active` TINYINT
)
BEGIN

 

IF i_d > 0 THEN
       UPDATE webuser_bill_address
            SET  fid_province_cities=f_id_province_cities , fplak =f_plak ,flastname = f_lastname,fmobile =f_mobile ,fname =f_name ,fpostalcode =f_postalcode , fvahed=f_vahed
                ,fstreet =f_street ,factive =f_active , fmapAddress=f_mapAddress , fmapCenter=f_mapCenter
                  
         WHERE id = i_d ;
		 select i_d  as id;
  END IF;
  IF i_d = 0 THEN
              INSERT  INTO  webuser_bill_address (  fid_province_cities , fplak ,flastname ,fmobile ,fname , fpostalcode,fvahed , fstreet, factive ,fidwebuser ,
              fmapAddress , fmapCenter )
               VALUES (  f_id_province_cities , f_plak ,f_lastname ,f_mobile ,f_name , f_postalcode,f_vahed , f_street, f_active ,f_idwebuser ,
               f_mapAddress , f_mapCenter ) ;
    SELECT  LAST_INSERT_ID() as id;
  END IF;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `updateVariableProductStokManager` */;
DELIMITER ;;
CREATE  PROCEDURE `updateVariableProductStokManager`(IN `i_d`  bigint )
BEGIN
   select "no_Manage_stock" as type ,  count(*) as count , "" as max    from productview  where id= i_d    
   and (   (fManage_stock_quantity =0)    )
union
select "Manage_stock" as type , count(*) as count , max(fstock_quantity) as max   from productview  where id= i_d    
 and (    (fManage_stock_quantity =1 and fstock_quantity > 0) );

END ;;
DELIMITER ;

--
-- Final view structure for view `bill_coupon_info`
--

/*!50001 DROP VIEW IF EXISTS `bill_coupon_info`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `bill_coupon_info` AS select `bc`.`idbillcoupon` AS `idbillcoupon`,`b`.`id` AS `bid`,`b`.`fidwebuser` AS `bfidwebuser`,`b`.`fidbillpaymethods` AS `bfidbillpaymethods`,`b`.`fstatus` AS `bfstatus`,`b`.`fname` AS `bfname`,`b`.`flastname` AS `bflastname`,`b`.`fmobile` AS `bfmobile`,`b`.`faddress` AS `bfaddress`,`b`.`fdesc` AS `bfdesc`,`b`.`inserttime` AS `binserttime`,`b`.`fextra` AS `bfextra`,`b`.`ftransa` AS `bftransa`,`b`.`fidtransaction` AS `bfidtransaction`,`b`.`ftranUID` AS `bftranUID`,`bm`.`id` AS `bmid`,`bm`.`ftype` AS `bmftype`,`bm`.`fname` AS `bmname`,`bm`.`fdesc` AS `bmdesc`,`bm`.`fextra` AS `bmfextra` from ((`billing` `b` join `billpaymethods` `bm` on(`b`.`fidbillpaymethods` = `bm`.`id`)) join `billcoupon_used` `bc` on(`bc`.`id` = `b`.`fidbillcoupon_used`)) */;

--
-- Final view structure for view `billinfo`
--

/*!50001 DROP VIEW IF EXISTS `billinfo`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `billinfo` AS select `billing`.`id` AS `id`,`billing`.`faddedByAdminID` AS `faddedByAdminID`,`billing`.`fidwebuser` AS `fidwebuser`,`billing`.`fidbillpaymethods` AS `fidbillpaymethods`,`billing`.`fidbillcoupon_used` AS `fidbillcoupon_used`,`billing`.`idbillcarriermethods` AS `idbillcarriermethods`,`billing`.`idwebuser_bill_address` AS `idwebuser_bill_address`,`billing`.`fstatus` AS `fstatus`,`billing`.`fsubstatus` AS `fsubstatus`,`billing`.`fname` AS `fname`,`billing`.`flastname` AS `flastname`,`billing`.`fmobile` AS `fmobile`,`billing`.`ffiledata` AS `ffiledata`,`billing`.`faddress` AS `faddress`,`billing`.`fdeleverRangeStart` AS `fdeleverRangeStart`,`billing`.`fdeleverRangeEnd` AS `fdeleverRangeEnd`,`billing`.`fpostData` AS `fpostData`,`billing`.`fdesc` AS `fdesc`,`billing`.`inserttime` AS `inserttime`,`billing`.`fextra` AS `fextra`,`RETURNBILLPRICE`(`billing`.`id`) AS `billprice`,`billing`.`ftransa` AS `ftransa`,`billing`.`fidtransaction` AS `fidtransaction`,`billing`.`ftranUID` AS `ftranUID`,`billing`.`fip` AS `fip`,`billing`.`femail` AS `femail`,`billing`.`fbillpriceAll` AS `fbillpriceAll`,`billing`.`fpayPriceAll` AS `fpayPriceAll`,`billing`.`fdiscountAll` AS `fdiscountAll`,`billing`.`fdeliveryCode` AS `fdeliveryCode`,`billing`.`fcarrierPriceAll` AS `fcarrierPriceAll`,`FFFFCONVERTMILLADYTOGHAMARY`(`billing`.`inserttime`) AS `pinserttime`,`bd`.`fidproduct` AS `fidproduct`,`bd`.`id` AS `bd_id`,`bd`.`fprice` AS `fprice`,`bd`.`fstatus` AS `bd_fstatus`,`bd`.`fdesc` AS `bd_fdesc`,`bd`.`fextra` AS `bd_fextra`,`bd`.`fcount` AS `fcount`,`bd`.`fpriceUnit` AS `fpriceUnit`,`bd`.`fpriceAll` AS `fpriceAll`,`bd`.`fparent` AS `fparent`,`bd`.`ftype` AS `ftype`,`bd`.`fname` AS `bd_fname`,`bd`.`fidstore` AS `fidstore`,`bd`.`foff` AS `foff`,`bd`.`fimage` AS `fimage`,`bd`.`fValuevariabelDependenc1` AS `fValuevariabelDependenc1`,`bd`.`fValuevariabelDependenc2` AS `fValuevariabelDependenc2`,`bp`.`ftype` AS `bp_ftype`,`bp`.`fname` AS `bp_fname`,`bp`.`fdesc` AS `bp_fdesc`,`bp`.`factive` AS `bp_factive`,`bp`.`fextra` AS `bp_fextra`,`bp`.`fname` AS `paymethod`,`bd`.`fisService` AS `fisService`,`bd`.`fis_down` AS `fis_down`,`bp`.`ftype` AS `paymethod_ftype`,`RETURNBILLPRODUCTSIMAGE`(`billing`.`id`) AS `images`,(select `store_settings`.`fldval` from `store_settings` where `store_settings`.`fldkey` = 'STORE_AWAIT_PAYMENT_MIN') - floor(time_to_sec(timediff(current_timestamp(),`billing`.`inserttime`)) / 60) AS `timeractive` from ((`billing` join `billing_details` `bd` on(`billing`.`id` = `bd`.`fidbilling`)) left join `billpaymethods` `bp` on(`billing`.`fidbillpaymethods` = `bp`.`id`)) where `billing`.`fdeleted` = 0 and `bd`.`fdeleted` = 0 */;

--
-- Final view structure for view `mainbasket`
--

/*!50001 DROP VIEW IF EXISTS `mainbasket`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `mainbasket` AS select `b`.`idwebuser` AS `idwebuser`,`b`.`idproduct` AS `idproduct`,`b`.`idtempUser` AS `idtempUser`,`b`.`type` AS `type`,`b`.`idexternalRequest` AS `idexternalRequest`,`b`.`count` AS `count`,`b`.`fextra` AS `fextra`,`b`.`id` AS `id_basket`,`p`.`id` AS `id`,`v`.`id` AS `ID_varient_product`,`p`.`fsku` AS `fsku`,`p`.`fzarib` AS `fzarib`,`p`.`fname` AS `fname`,`v`.`fprice` AS `fprice`,`v`.`fweight` AS `fweight`,`RETURN_PRODUCT_PRICEUNIT`(`v`.`id`,`v`.`fis_amazing`) AS `fpriceUnit`,`RETURN_PRODUCT_PRICEUNIT`(`v`.`id`,`v`.`fis_amazing`) * `b`.`count` AS `fpriceAll`,`v`.`fis_amazing` AS `fis_amazing`,`v`.`amazing_startDate` AS `amazing_startDate`,`v`.`amazing_endDate` AS `amazing_endDate`,`b`.`inserttime` AS `addtobasketTime`,`p`.`fimages` AS `fimages`,`RETURN_CARRIERNAMEBYID`(`p`.`fidCarrierId`) AS `CarriersData`,`p`.`fidCarrierId` AS `fidCarrierId`,`p`.`factive` AS `factive`,`v`.`foff` AS `foff`,`v`.`fronding` AS `fronding`,`v`.`amazing_foff` AS `amazing_foff`,`v`.`fdate_update_price` AS `fdate_update_price`,`p`.`fis_down` AS `fis_down`,`p`.`fis_virtual` AS `fis_virtual`,`p`.`fisService` AS `fisService`,`v`.`fis_Single_sale` AS `fis_Single_sale`,`p`.`fidCateg` AS `fidCateg`,`v`.`fvariabelDependenc1desc` AS `fvariabelDependenc1desc`,`v`.`fvariabelDependenc2desc` AS `fvariabelDependenc2desc`,`v`.`fmax_sell_quantity` AS `fmax_sell_quantity`,`p`.`fkeys` AS `fkeys`,`v`.`fis_freeShip` AS `fis_freeShip`,`v`.`fidproduct` AS `fparent`,`RETURN_STORENAMEBYID`(`s`.`id`) AS `storeName`,`s`.`fimages` AS `storeLogo`,`s`.`furl` AS `storeUrl`,`s`.`frate` AS `storeRate`,`s`.`fcode` AS `storeCode`,`s`.`is_new` AS `storeis_new`,`s`.`is_official` AS `storeis_official`,`s`.`is_trusted` AS `storeis_trusted`,`v`.`fcanShappingByMainStore` AS `fcanShappingByMainStore`,`v`.`fManage_stock_quantity` AS `fManage_stock_quantity`,`v`.`fstock_quantity` AS `fstock_quantity`,`v`.`fcanShappingBySeller` AS `fcanShappingBySeller`,`v`.`fdaystoSendMainStore` AS `fdaystoSendMainStore`,`s`.`id` AS `storeId`,`p`.`furl` AS `furl` from (((`buy_basket` `b` join `products_varients` `v` on(`v`.`id` = `b`.`idproduct`)) join `products` `p` on(`p`.`id` = `v`.`fidproduct`)) join `stores` `s` on(`s`.`id` = `v`.`fidstore`)) where `p`.`factive` = 1 and `v`.`factive` = 1 and `p`.`fdeleted` = 0 and `s`.`factive` = 1 and `s`.`fdeleted` = 0 and `v`.`fdeleted` = 0 */;

--
-- Final view structure for view `mainbasket_next`
--

/*!50001 DROP VIEW IF EXISTS `mainbasket_next`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `mainbasket_next` AS select `b`.`idwebuser` AS `idwebuser`,`b`.`idproduct` AS `idproduct`,`b`.`idtempUser` AS `idtempUser`,`b`.`type` AS `type`,`b`.`count` AS `count`,`b`.`fextra` AS `fextra`,`b`.`id` AS `id_basket`,`p`.`id` AS `id`,`p`.`fsku` AS `fsku`,`p`.`fname` AS `fname`,`v`.`fprice` AS `fprice`,`RETURN_PRODUCT_PRICEUNIT`(`v`.`id`,`v`.`fis_amazing`) AS `fpriceUnit`,`RETURN_PRODUCT_PRICEUNIT`(`v`.`id`,`v`.`fis_amazing`) * `b`.`count` AS `fpriceAll`,`p`.`fimages` AS `fimages`,`p`.`factive` AS `factive`,`RETURN_CARRIERNAMEBYID`(`p`.`fidCarrierId`) AS `CarriersData`,`v`.`foff` AS `foff`,`v`.`fronding` AS `fronding`,`v`.`amazing_foff` AS `amazing_foff`,`v`.`fis_amazing` AS `fis_amazing`,`v`.`amazing_startDate` AS `amazing_startDate`,`v`.`amazing_endDate` AS `amazing_endDate`,`v`.`fdate_update_price` AS `fdate_update_price`,`p`.`fis_down` AS `fis_down`,`p`.`fzarib` AS `fzarib`,`p`.`fis_virtual` AS `fis_virtual`,`v`.`fis_Single_sale` AS `fis_Single_sale`,`v`.`fvariabelDependenc1desc` AS `fvariabelDependenc1desc`,`v`.`fvariabelDependenc2desc` AS `fvariabelDependenc2desc`,`p`.`fidCateg` AS `fidCateg`,`v`.`fmax_sell_quantity` AS `fmax_sell_quantity`,`p`.`fkeys` AS `fkeys`,`v`.`fis_freeShip` AS `fis_freeShip`,`v`.`fidproduct` AS `fparent`,`RETURN_STORENAMEBYID`(`s`.`id`) AS `storeName`,`s`.`fimages` AS `storeLogo`,`s`.`furl` AS `storeUrl`,`s`.`frate` AS `storeRate`,`s`.`fcode` AS `storeCode`,`s`.`is_new` AS `storeis_new`,`s`.`is_official` AS `storeis_official`,`s`.`is_trusted` AS `storeis_trusted`,`s`.`id` AS `storeId`,`p`.`furl` AS `furl` from (((`buy_basket_next` `b` join `products_varients` `v` on(`v`.`id` = `b`.`idproduct`)) join `products` `p` on(`p`.`id` = `v`.`fidproduct`)) join `stores` `s` on(`s`.`id` = `v`.`fidstore`)) where `p`.`factive` = 1 and `v`.`factive` = 1 and `p`.`fdeleted` = 0 and `s`.`factive` = 1 and `s`.`fdeleted` = 0 and `v`.`fdeleted` = 0 */;

--
-- Final view structure for view `oneproductattributes`
--

/*!50001 DROP VIEW IF EXISTS `oneproductattributes`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `oneproductattributes` AS select `pa`.`id` AS `paid`,`pa`.`idproduct` AS `paidproduct`,`pa`.`forder` AS `forder`,`pa`.`idatribute` AS `paidatribute`,`pa`.`fenable_variation` AS `fenable_variation`,`pa`.`fattribute_visibility` AS `fattribute_visibility`,`pa`.`fview_mode` AS `fview_mode`,case `pa`.`fenable_variation` when 1 then (select group_concat(`product_attribute_variant`.`fvalue` separator ',') from `product_attribute_variant` where `product_attribute_variant`.`fidproduct_attribute` = `pa`.`id` group by `product_attribute_variant`.`fidproduct_attribute`) else `pa`.`fvalue` end AS `pafvalue`,case `pa`.`fenable_variation` when 1 then (select json_arrayagg(json_object('id',`product_attribute_variant`.`id`,'fvalue',`product_attribute_variant`.`fvalue`,'fdesc',`product_attribute_variant`.`fdesc`)) from `product_attribute_variant` where `product_attribute_variant`.`fidproduct_attribute` = `pa`.`id`) else `pa`.`fvalue` end AS `jsonValue`,`paa`.`id` AS `paaid`,`paa`.`fkey` AS `paafkey`,`postscatag`.`fname` AS `category_name`,`postscatag`.`forder` AS `category_order`,`paa`.`factive` AS `paafactive`,`paa`.`ftype` AS `paaftype` from ((`product_attribute` `pa` join `product_allattribute` `paa` on(`paa`.`id` = `pa`.`idatribute`)) join `postscatag` on(`postscatag`.`id` = `paa`.`fidCateg`)) */;

--
-- Final view structure for view `product_export_to_excel`
--

/*!50001 DROP VIEW IF EXISTS `product_export_to_excel`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `product_export_to_excel` AS select `p`.`id` AS `id`,`v`.`id` AS `varient_id`,`s`.`fcode` AS `storeCode`,`p`.`fname` AS `fname`,`v`.`fprice` AS `fprice`,`RETURN_PRODUCT_PRICEUNIT`(`v`.`id`,`v`.`fis_amazing`) AS `fpriceUnit`,`p`.`fdesc` AS `fdesc`,`p`.`fimages` AS `fimages`,`p`.`fctitle` AS `fctitle`,`p`.`finfo2` AS `finfo2`,`v`.`fcustomBuyBoxdesc` AS `fcustomBuyBoxdesc`,`p`.`flatiName` AS `flatiName`,`p`.`fzarib` AS `fzarib`,`p`.`factive` AS `factive`,`p`.`fpicAlt` AS `fpicAlt`,`v`.`factive` AS `V_factive`,`v`.`fis_freeShip` AS `fis_freeShip`,`v`.`fronding` AS `fronding`,`p`.`finfo1` AS `finfo1`,`v`.`foff` AS `foff`,`v`.`amazing_foff` AS `amazing_foff`,`p`.`furl` AS `furl`,`v`.`fdate_update_price` AS `fdate_update_price`,`p`.`fidCateg` AS `fidCateg`,`p`.`fkeys` AS `fkeys`,`p`.`fis_down` AS `fis_down`,`p`.`fis_virtual` AS `fis_virtual`,`v`.`fis_Single_sale` AS `fis_Single_sale`,`v`.`flow_stock_amount` AS `flow_stock_amount`,`v`.`fdaystoSendMainStore` AS `fdaystoSendMainStore`,`v`.`fcanShappingByMainStore` AS `fcanShappingByMainStore`,`v`.`fdaystoSendCustomerByMainStore` AS `fdaystoSendCustomerByMainStore`,`v`.`fdaystoSendCustomerBySeller` AS `fdaystoSendCustomerBySeller`,`v`.`finMainStoreStock` AS `finMainStoreStock`,`v`.`fcanShappingBySeller` AS `fcanShappingBySeller`,`v`.`fvariabelDependenc1desc` AS `fvariabelDependenc1desc`,`v`.`fvariabelDependenc2desc` AS `fvariabelDependenc2desc`,`v`.`fmax_sell_quantity` AS `fmax_sell_quantity`,`p`.`fsku` AS `fsku`,`v`.`fManage_stock_quantity` AS `fManage_stock_quantity`,case ifnull(`v`.`fManage_stock_quantity`,0) when 0 then 0 else (select `RETURNSTOCK_QUANTITY`(`p`.`id`,`v`.`fstock_quantity`) AS `b`) end AS `fstock_quantity`,`v`.`fis_soon` AS `fis_soon`,`v`.`fis_amazing` AS `fis_amazing`,`p`.`fid_brand` AS `fid_brand`,`RETURN_PRODUCT_COLORS`(`p`.`id`) AS `ProductColors` from ((`products` `p` join `products_varients` `v` on(`v`.`fidproduct` = `p`.`id`)) join `stores` `s` on(`s`.`id` = `v`.`fidstore`)) where ifnull(`p`.`fhidden`,0) = 0 order by `v`.`id` desc */;

--
-- Final view structure for view `product_mini`
--

/*!50001 DROP VIEW IF EXISTS `product_mini`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `product_mini` AS select `p`.`id` AS `id`,`p`.`fseen` AS `fseen`,`v`.`id` AS `varient_id`,`s`.`id` AS `storeId`,`s`.`fcode` AS `storeCode`,`p`.`fname` AS `fname`,`v`.`fprice` AS `fprice`,`RETURN_PRODUCT_PRICEUNIT`(`v`.`id`,`v`.`fis_amazing`) AS `fpriceUnit`,`p`.`fdesc` AS `fdesc`,`p`.`fdefult_variabels` AS `fdefult_variabels`,`p`.`fimages` AS `fimages`,`p`.`frate` AS `frate`,`p`.`fctitle` AS `fctitle`,`p`.`fzarib` AS `fzarib`,`p`.`fpicAlt` AS `fpicAlt`,`p`.`fcomments` AS `fcomments`,`v`.`fsellcount` AS `fsellcount`,`v`.`fronding` AS `fronding`,`p`.`fsuggests` AS `fsuggests`,`p`.`finfo2` AS `finfo2`,`v`.`fcustomBuyBoxdesc` AS `fcustomBuyBoxdesc`,`p`.`flatiName` AS `flatiName`,`p`.`factive` AS `factive`,`v`.`factive` AS `V_factive`,`v`.`fis_freeShip` AS `fis_freeShip`,`p`.`finfo1` AS `finfo1`,`v`.`foff` AS `foff`,`v`.`amazing_foff` AS `amazing_foff`,`p`.`furl` AS `furl`,`v`.`fdate_update_price` AS `fdate_update_price`,`p`.`fidCateg` AS `fidCateg`,`p`.`fkeys` AS `fkeys`,`p`.`fis_down` AS `fis_down`,`p`.`fis_virtual` AS `fis_virtual`,`v`.`fis_Single_sale` AS `fis_Single_sale`,`v`.`flow_stock_amount` AS `flow_stock_amount`,`v`.`fweight` AS `fweight`,`v`.`flength` AS `flength`,`v`.`fdaystoSendMainStore` AS `fdaystoSendMainStore`,`v`.`fcanShappingByMainStore` AS `fcanShappingByMainStore`,`v`.`fdaystoSendCustomerByMainStore` AS `fdaystoSendCustomerByMainStore`,`v`.`fdaystoSendCustomerBySeller` AS `fdaystoSendCustomerBySeller`,`v`.`finMainStoreStock` AS `finMainStoreStock`,`v`.`fcanShappingBySeller` AS `fcanShappingBySeller`,`p`.`flayout` AS `flayout`,`v`.`fwidth` AS `fwidth`,`v`.`fvariabelDependenc1desc` AS `fvariabelDependenc1desc`,`v`.`fheight` AS `fheight`,`v`.`fvariabelDependenc2desc` AS `fvariabelDependenc2desc`,`v`.`fmax_sell_quantity` AS `fmax_sell_quantity`,`p`.`fsku` AS `fsku`,`v`.`fManage_stock_quantity` AS `fManage_stock_quantity`,case ifnull(`v`.`fManage_stock_quantity`,0) when 0 then 0 else (select `RETURNSTOCK_QUANTITY`(`p`.`id`,`v`.`fstock_quantity`) AS `b`) end AS `fstock_quantity`,`v`.`fis_soon` AS `fis_soon`,`v`.`fis_amazing` AS `fis_amazing`,`p`.`fid_brand` AS `fid_brand`,`RETURN_CARRIERNAMEBYID`(`p`.`fidCarrierId`) AS `CarriersData`,`RETURN_PRODUCT_COLORS`(`p`.`id`) AS `ProductColors`,`FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`v`.`amazing_startDate`) AS `amazing_startDate_fa`,`FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`v`.`amazing_endDate`) AS `amazing_endDate_fa`,`v`.`amazing_startDate` AS `amazing_startDate`,`v`.`amazing_endDate` AS `amazing_endDate`,`v`.`amazing_startTime` AS `amazing_startTime`,`v`.`amazing_endTime` AS `amazing_endTime` from ((`products` `p` join `products_varients` `v` on(`v`.`fidproduct` = `p`.`id`)) join `stores` `s` on(`s`.`id` = `v`.`fidstore`)) where ifnull(`p`.`fhidden`,0) = 0 and `p`.`fdeleted` = 0 and `v`.`fdeleted` = 0 and `v`.`factive` = 1 and `p`.`fdefult_variabels` = `v`.`id` and `p`.`factive` = 1 and (`v`.`fcanShappingByMainStore` = 1 or `v`.`fcanShappingBySeller` = 1) */;

--
-- Final view structure for view `product_mini_new`
--

/*!50001 DROP VIEW IF EXISTS `product_mini_new`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `product_mini_new` AS select `product_mini_new_base`.`id` AS `id`,`product_mini_new_base`.`fseen` AS `fseen`,`product_mini_new_base`.`varient_id` AS `varient_id`,`product_mini_new_base`.`storeId` AS `storeId`,`product_mini_new_base`.`storeCode` AS `storeCode`,`product_mini_new_base`.`fname` AS `fname`,`product_mini_new_base`.`fprice` AS `fprice`,`product_mini_new_base`.`fdesc` AS `fdesc`,`product_mini_new_base`.`fdefult_variabels` AS `fdefult_variabels`,`product_mini_new_base`.`fimages` AS `fimages`,`product_mini_new_base`.`frate` AS `frate`,`product_mini_new_base`.`fctitle` AS `fctitle`,`product_mini_new_base`.`fzarib` AS `fzarib`,`product_mini_new_base`.`fpicAlt` AS `fpicAlt`,`product_mini_new_base`.`fcomments` AS `fcomments`,`product_mini_new_base`.`fsellcount` AS `fsellcount`,`product_mini_new_base`.`fronding` AS `fronding`,`product_mini_new_base`.`fsuggests` AS `fsuggests`,`product_mini_new_base`.`finfo2` AS `finfo2`,`product_mini_new_base`.`fcustomBuyBoxdesc` AS `fcustomBuyBoxdesc`,`product_mini_new_base`.`flatiName` AS `flatiName`,`product_mini_new_base`.`factive` AS `factive`,`product_mini_new_base`.`V_factive` AS `V_factive`,`product_mini_new_base`.`fis_freeShip` AS `fis_freeShip`,`product_mini_new_base`.`finfo1` AS `finfo1`,`product_mini_new_base`.`foff` AS `foff`,`product_mini_new_base`.`amazing_foff` AS `amazing_foff`,`product_mini_new_base`.`furl` AS `furl`,`product_mini_new_base`.`fdate_update_price` AS `fdate_update_price`,`product_mini_new_base`.`fidCateg` AS `fidCateg`,`product_mini_new_base`.`fkeys` AS `fkeys`,`product_mini_new_base`.`fis_down` AS `fis_down`,`product_mini_new_base`.`fis_virtual` AS `fis_virtual`,`product_mini_new_base`.`fis_Single_sale` AS `fis_Single_sale`,`product_mini_new_base`.`flow_stock_amount` AS `flow_stock_amount`,`product_mini_new_base`.`fweight` AS `fweight`,`product_mini_new_base`.`flength` AS `flength`,`product_mini_new_base`.`fdaystoSendMainStore` AS `fdaystoSendMainStore`,`product_mini_new_base`.`fcanShappingByMainStore` AS `fcanShappingByMainStore`,`product_mini_new_base`.`fdaystoSendCustomerByMainStore` AS `fdaystoSendCustomerByMainStore`,`product_mini_new_base`.`fdaystoSendCustomerBySeller` AS `fdaystoSendCustomerBySeller`,`product_mini_new_base`.`finMainStoreStock` AS `finMainStoreStock`,`product_mini_new_base`.`fcanShappingBySeller` AS `fcanShappingBySeller`,`product_mini_new_base`.`flayout` AS `flayout`,`product_mini_new_base`.`fwidth` AS `fwidth`,`product_mini_new_base`.`fvariabelDependenc1desc` AS `fvariabelDependenc1desc`,`product_mini_new_base`.`fheight` AS `fheight`,`product_mini_new_base`.`fvariabelDependenc2desc` AS `fvariabelDependenc2desc`,`product_mini_new_base`.`fmax_sell_quantity` AS `fmax_sell_quantity`,`product_mini_new_base`.`fsku` AS `fsku`,`product_mini_new_base`.`fManage_stock_quantity` AS `fManage_stock_quantity`,`product_mini_new_base`.`fstock_quantity` AS `fstock_quantity`,`product_mini_new_base`.`fis_soon` AS `fis_soon`,`product_mini_new_base`.`fis_amazing` AS `fis_amazing`,`product_mini_new_base`.`fid_brand` AS `fid_brand`,`product_mini_new_base`.`fpriceUnit` AS `fpriceUnit`,`product_mini_new_base`.`fidCarrierId` AS `fidCarrierId`,`product_mini_new_base`.`amazing_startDate_fa` AS `amazing_startDate_fa`,`product_mini_new_base`.`amazing_endDate_fa` AS `amazing_endDate_fa`,`product_mini_new_base`.`amazing_startDate` AS `amazing_startDate`,`product_mini_new_base`.`amazing_endDate` AS `amazing_endDate`,`product_mini_new_base`.`amazing_startTime` AS `amazing_startTime`,`product_mini_new_base`.`amazing_endTime` AS `amazing_endTime` from `product_mini_new_base` where `product_mini_new_base`.`fdefult_variabels` = `product_mini_new_base`.`varient_id` */;

--
-- Final view structure for view `product_mini_new_base`
--

/*!50001 DROP VIEW IF EXISTS `product_mini_new_base`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `product_mini_new_base` AS select `p`.`id` AS `id`,`p`.`fseen` AS `fseen`,`v`.`id` AS `varient_id`,`s`.`id` AS `storeId`,`s`.`fcode` AS `storeCode`,`p`.`fname` AS `fname`,`v`.`fprice` AS `fprice`,`p`.`fdesc` AS `fdesc`,`p`.`fdefult_variabels` AS `fdefult_variabels`,`p`.`fimages` AS `fimages`,`p`.`frate` AS `frate`,`p`.`fctitle` AS `fctitle`,`p`.`fzarib` AS `fzarib`,`p`.`fpicAlt` AS `fpicAlt`,`p`.`fcomments` AS `fcomments`,`v`.`fsellcount` AS `fsellcount`,`v`.`fronding` AS `fronding`,`p`.`fsuggests` AS `fsuggests`,`p`.`finfo2` AS `finfo2`,`v`.`fcustomBuyBoxdesc` AS `fcustomBuyBoxdesc`,`p`.`flatiName` AS `flatiName`,`p`.`factive` AS `factive`,`v`.`factive` AS `V_factive`,`v`.`fis_freeShip` AS `fis_freeShip`,`p`.`finfo1` AS `finfo1`,`v`.`foff` AS `foff`,`v`.`amazing_foff` AS `amazing_foff`,`p`.`furl` AS `furl`,`v`.`fdate_update_price` AS `fdate_update_price`,`p`.`fidCateg` AS `fidCateg`,`p`.`fkeys` AS `fkeys`,`p`.`fis_down` AS `fis_down`,`p`.`fis_virtual` AS `fis_virtual`,`v`.`fis_Single_sale` AS `fis_Single_sale`,`v`.`flow_stock_amount` AS `flow_stock_amount`,`v`.`fweight` AS `fweight`,`v`.`flength` AS `flength`,`v`.`fdaystoSendMainStore` AS `fdaystoSendMainStore`,`v`.`fcanShappingByMainStore` AS `fcanShappingByMainStore`,`v`.`fdaystoSendCustomerByMainStore` AS `fdaystoSendCustomerByMainStore`,`v`.`fdaystoSendCustomerBySeller` AS `fdaystoSendCustomerBySeller`,`v`.`finMainStoreStock` AS `finMainStoreStock`,`v`.`fcanShappingBySeller` AS `fcanShappingBySeller`,`p`.`flayout` AS `flayout`,`v`.`fwidth` AS `fwidth`,`v`.`fvariabelDependenc1desc` AS `fvariabelDependenc1desc`,`v`.`fheight` AS `fheight`,`v`.`fvariabelDependenc2desc` AS `fvariabelDependenc2desc`,`v`.`fmax_sell_quantity` AS `fmax_sell_quantity`,`p`.`fsku` AS `fsku`,`v`.`fManage_stock_quantity` AS `fManage_stock_quantity`,case ifnull(`v`.`fManage_stock_quantity`,0) when 0 then 0 else (select `RETURNSTOCK_QUANTITY`(`p`.`id`,`v`.`fstock_quantity`) AS `b`) end AS `fstock_quantity`,`v`.`fis_soon` AS `fis_soon`,`v`.`fis_amazing` AS `fis_amazing`,`p`.`fid_brand` AS `fid_brand`,`RETURN_PRODUCT_PRICEUNIT`(`v`.`id`,`v`.`fis_amazing`) AS `fpriceUnit`,`p`.`fidCarrierId` AS `fidCarrierId`,`FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`v`.`amazing_startDate`) AS `amazing_startDate_fa`,`FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`v`.`amazing_endDate`) AS `amazing_endDate_fa`,`v`.`amazing_startDate` AS `amazing_startDate`,`v`.`amazing_endDate` AS `amazing_endDate`,`v`.`amazing_startTime` AS `amazing_startTime`,`v`.`amazing_endTime` AS `amazing_endTime` from ((`products` `p` join `products_varients` `v` on(`v`.`fidproduct` = `p`.`id`)) join `stores` `s` on(`s`.`id` = `v`.`fidstore`)) where ifnull(`p`.`fhidden`,0) = 0 and `p`.`fdeleted` = 0 and `v`.`fdeleted` = 0 and `v`.`factive` = 1 and `p`.`factive` = 1 and (`v`.`fcanShappingByMainStore` = 1 or `v`.`fcanShappingBySeller` = 1) */;

--
-- Final view structure for view `product_mini_new_not_check_default_varients`
--

/*!50001 DROP VIEW IF EXISTS `product_mini_new_not_check_default_varients`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `product_mini_new_not_check_default_varients` AS select `product_mini_new_base`.`id` AS `id`,`product_mini_new_base`.`fseen` AS `fseen`,`product_mini_new_base`.`varient_id` AS `varient_id`,`product_mini_new_base`.`storeId` AS `storeId`,`product_mini_new_base`.`storeCode` AS `storeCode`,`product_mini_new_base`.`fname` AS `fname`,`product_mini_new_base`.`fprice` AS `fprice`,`product_mini_new_base`.`fdesc` AS `fdesc`,`product_mini_new_base`.`fdefult_variabels` AS `fdefult_variabels`,`product_mini_new_base`.`fimages` AS `fimages`,`product_mini_new_base`.`frate` AS `frate`,`product_mini_new_base`.`fctitle` AS `fctitle`,`product_mini_new_base`.`fzarib` AS `fzarib`,`product_mini_new_base`.`fpicAlt` AS `fpicAlt`,`product_mini_new_base`.`fcomments` AS `fcomments`,`product_mini_new_base`.`fsellcount` AS `fsellcount`,`product_mini_new_base`.`fronding` AS `fronding`,`product_mini_new_base`.`fsuggests` AS `fsuggests`,`product_mini_new_base`.`finfo2` AS `finfo2`,`product_mini_new_base`.`fcustomBuyBoxdesc` AS `fcustomBuyBoxdesc`,`product_mini_new_base`.`flatiName` AS `flatiName`,`product_mini_new_base`.`factive` AS `factive`,`product_mini_new_base`.`V_factive` AS `V_factive`,`product_mini_new_base`.`fis_freeShip` AS `fis_freeShip`,`product_mini_new_base`.`finfo1` AS `finfo1`,`product_mini_new_base`.`foff` AS `foff`,`product_mini_new_base`.`amazing_foff` AS `amazing_foff`,`product_mini_new_base`.`furl` AS `furl`,`product_mini_new_base`.`fdate_update_price` AS `fdate_update_price`,`product_mini_new_base`.`fidCateg` AS `fidCateg`,`product_mini_new_base`.`fkeys` AS `fkeys`,`product_mini_new_base`.`fis_down` AS `fis_down`,`product_mini_new_base`.`fis_virtual` AS `fis_virtual`,`product_mini_new_base`.`fis_Single_sale` AS `fis_Single_sale`,`product_mini_new_base`.`flow_stock_amount` AS `flow_stock_amount`,`product_mini_new_base`.`fweight` AS `fweight`,`product_mini_new_base`.`flength` AS `flength`,`product_mini_new_base`.`fdaystoSendMainStore` AS `fdaystoSendMainStore`,`product_mini_new_base`.`fcanShappingByMainStore` AS `fcanShappingByMainStore`,`product_mini_new_base`.`fdaystoSendCustomerByMainStore` AS `fdaystoSendCustomerByMainStore`,`product_mini_new_base`.`fdaystoSendCustomerBySeller` AS `fdaystoSendCustomerBySeller`,`product_mini_new_base`.`finMainStoreStock` AS `finMainStoreStock`,`product_mini_new_base`.`fcanShappingBySeller` AS `fcanShappingBySeller`,`product_mini_new_base`.`flayout` AS `flayout`,`product_mini_new_base`.`fwidth` AS `fwidth`,`product_mini_new_base`.`fvariabelDependenc1desc` AS `fvariabelDependenc1desc`,`product_mini_new_base`.`fheight` AS `fheight`,`product_mini_new_base`.`fvariabelDependenc2desc` AS `fvariabelDependenc2desc`,`product_mini_new_base`.`fmax_sell_quantity` AS `fmax_sell_quantity`,`product_mini_new_base`.`fsku` AS `fsku`,`product_mini_new_base`.`fManage_stock_quantity` AS `fManage_stock_quantity`,`product_mini_new_base`.`fstock_quantity` AS `fstock_quantity`,`product_mini_new_base`.`fis_soon` AS `fis_soon`,`product_mini_new_base`.`fis_amazing` AS `fis_amazing`,`product_mini_new_base`.`fid_brand` AS `fid_brand`,`product_mini_new_base`.`fpriceUnit` AS `fpriceUnit`,`product_mini_new_base`.`fidCarrierId` AS `fidCarrierId`,`product_mini_new_base`.`amazing_startDate_fa` AS `amazing_startDate_fa`,`product_mini_new_base`.`amazing_endDate_fa` AS `amazing_endDate_fa`,`product_mini_new_base`.`amazing_startDate` AS `amazing_startDate`,`product_mini_new_base`.`amazing_endDate` AS `amazing_endDate`,`product_mini_new_base`.`amazing_startTime` AS `amazing_startTime`,`product_mini_new_base`.`amazing_endTime` AS `amazing_endTime` from `product_mini_new_base` */;

--
-- Final view structure for view `productview`
--

/*!50001 DROP VIEW IF EXISTS `productview`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `productview` AS select case ifnull(`p`.`fid_brand`,0) when 0 then 'متفرقه' else (select ifnull(`product_brand`.`fname`,'متفرقه') AS `b` from `product_brand` where `product_brand`.`id` = `p`.`fid_brand` and `product_brand`.`factive` = 1) end AS `brand`,`RETURN_CARRIERNAMEBYID`(`p`.`fidCarrierId`) AS `CarriersData`,case ifnull(`p`.`fidCateg`,0) when 0 then '' else (select ifnull(`postscatag`.`fname`,'') AS `b` from `postscatag` where `postscatag`.`id` = `p`.`fidCateg` and `postscatag`.`factive` = 1) end AS `Categ`,`p`.`id` AS `id`,`p`.`fzarib` AS `fzarib`,`RETURN_PRODUCT_IN_ORDER_COUNT`(`p`.`id`) AS `product_in_order_count`,`RETURN_PRODUCT_SELL_COUNT`(`p`.`id`) AS `product_sell_count`,`p`.`fname` AS `fname`,`p`.`flatiName` AS `flatiName`,`v`.`fprice` AS `fprice`,`p`.`frate` AS `frate`,`p`.`fcomments` AS `fcomments`,`p`.`fsuggests` AS `fsuggests`,`v`.`fsellcount` AS `fsellcount`,`v`.`fronding` AS `fronding`,`p`.`fctitle` AS `fctitle`,`p`.`fpicAlt` AS `fpicAlt`,`p`.`fdesc` AS `fdesc`,`p`.`fcomissionP` AS `fcomissionP`,`v`.`fis_freeShip` AS `fis_freeShip`,`v`.`fgarantidesc` AS `fgarantidesc`,`p`.`finfo1` AS `finfo1`,`p`.`finfo2` AS `finfo2`,`p`.`fimages` AS `fimages`,`p`.`flayout` AS `flayout`,`p`.`factive` AS `factive`,`v`.`foff` AS `foff`,`v`.`amazing_foff` AS `amazing_foff`,`v`.`fdate_update_price` AS `fdate_update_price`,`p`.`finserttime` AS `finserttime`,`p`.`fdeleted` AS `fdeleted`,`p`.`fidCateg` AS `fidCateg`,`p`.`fkeys` AS `fkeys`,`p`.`furl` AS `furl`,`v`.`ftype` AS `ftype`,`p`.`fis_down` AS `fis_down`,`p`.`fis_virtual` AS `fis_virtual`,`v`.`fcustomBuyBoxdesc` AS `fcustomBuyBoxdesc`,`v`.`fis_soon` AS `fis_soon`,`v`.`fis_amazing` AS `fis_amazing`,`v`.`fis_Single_sale` AS `fis_Single_sale`,`v`.`amazing_startDate` AS `amazing_startDate`,`v`.`amazing_endDate` AS `amazing_endDate`,`FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`v`.`amazing_startDate`) AS `amazing_startDate_fa`,`FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`v`.`amazing_endDate`) AS `amazing_endDate_fa`,`v`.`amazing_startTime` AS `amazing_startTime`,`v`.`amazing_endTime` AS `amazing_endTime`,`v`.`fManage_stock_quantity` AS `fManage_stock_quantity`,`v`.`fstock_quantity` AS `fstock_quantity`,`v`.`flow_stock_amount` AS `flow_stock_amount`,`v`.`fweight` AS `fweight`,`v`.`flength` AS `flength`,`v`.`fwidth` AS `fwidth`,`v`.`fheight` AS `fheight`,`v`.`fmax_sell_quantity` AS `fmax_sell_quantity`,`p`.`fsku` AS `fsku`,`v`.`id` AS `varient_id`,`RETURN_PRODUCT_COLORS`(`p`.`id`) AS `ProductColors`,`v`.`fvariabelDependenc1` AS `fvariabelDependenc1`,`v`.`fvariabelDependenc2` AS `fvariabelDependenc2`,`p`.`fdefult_variabels` AS `fdefult_variabels`,`p`.`fid_brand` AS `fid_brand` from (`products` `p` join `products_varients` `v` on(`v`.`fidproduct` = `p`.`id`)) where `p`.`fdeleted` = 0 and `v`.`fdeleted` = 0 and `v`.`factive` = 1 and `p`.`factive` = 1 and (`v`.`fcanShappingByMainStore` = 1 or `v`.`fcanShappingBySeller` = 1) */;

--
-- Final view structure for view `productview_fullhtml`
--

/*!50001 DROP VIEW IF EXISTS `productview_fullhtml`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `productview_fullhtml` AS select case ifnull(`p`.`fid_brand`,0) when 0 then 'متفرقه' else (select ifnull(`product_brand`.`fname`,'متفرقه') AS `b` from `product_brand` where `product_brand`.`id` = `p`.`fid_brand` and `product_brand`.`factive` = 1) end AS `brand`,`RETURN_CARRIERNAMEBYID`(`p`.`fidCarrierId`) AS `CarriersData`,case ifnull(`p`.`fidCateg`,0) when 0 then '' else (select ifnull(`postscatag`.`fname`,'') AS `b` from `postscatag` where `postscatag`.`id` = `p`.`fidCateg` and `postscatag`.`factive` = 1) end AS `Categ`,`p`.`id` AS `id`,`RETURN_PRODUCT_IN_ORDER_COUNT`(`p`.`id`) AS `product_in_order_count`,`RETURN_PRODUCT_SELL_COUNT`(`p`.`id`) AS `product_sell_count`,`RETURN_CATEGURY_PARENTS_STR`(`p`.`fidCateg`) AS `cataglevels`,`p`.`fname` AS `fname`,`p`.`flatiName` AS `flatiName`,`v`.`fprice` AS `fprice`,`p`.`fdesc` AS `fdesc`,`p`.`fctitle` AS `fctitle`,`p`.`fpicAlt` AS `fpicAlt`,`v`.`fis_freeShip` AS `fis_freeShip`,`v`.`fgarantidesc` AS `fgarantidesc`,`v`.`fronding` AS `fronding`,`v`.`fcustomBuyBoxdesc` AS `fcustomBuyBoxdesc`,`p`.`finfo1` AS `finfo1`,`p`.`finfo2` AS `finfo2`,`p`.`fimages` AS `fimages`,`p`.`fzarib` AS `fzarib`,`p`.`fcomissionP` AS `fcomissionP`,`p`.`factive` AS `factive`,`v`.`foff` AS `foff`,`v`.`amazing_foff` AS `amazing_foff`,`p`.`frate` AS `frate`,`p`.`fcomments` AS `fcomments`,`v`.`fsellcount` AS `fsellcount`,`p`.`fsuggests` AS `fsuggests`,`v`.`fdate_update_price` AS `fdate_update_price`,`v`.`finserttime` AS `finserttime`,`p`.`fdeleted` AS `fdeleted`,`p`.`fidCateg` AS `fidCateg`,`p`.`fkeys` AS `fkeys`,`p`.`furl` AS `furl`,`p`.`fhtml` AS `fhtml`,`p`.`fscript` AS `fscript`,`v`.`ftype` AS `ftype`,`p`.`flayout` AS `flayout`,`p`.`fis_down` AS `fis_down`,`p`.`fis_virtual` AS `fis_virtual`,`v`.`fis_soon` AS `fis_soon`,`v`.`fis_amazing` AS `fis_amazing`,`v`.`fis_Single_sale` AS `fis_Single_sale`,`v`.`amazing_startDate` AS `amazing_startDate`,`FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`v`.`amazing_startDate`) AS `amazing_startDate_fa`,`FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`v`.`amazing_endDate`) AS `amazing_endDate_fa`,`v`.`amazing_endDate` AS `amazing_endDate`,`v`.`amazing_startTime` AS `amazing_startTime`,`v`.`amazing_endTime` AS `amazing_endTime`,`v`.`fManage_stock_quantity` AS `fManage_stock_quantity`,`v`.`fstock_quantity` AS `fstock_quantity`,`v`.`flow_stock_amount` AS `flow_stock_amount`,`v`.`fweight` AS `fweight`,`v`.`flength` AS `flength`,`v`.`fwidth` AS `fwidth`,`v`.`fheight` AS `fheight`,`v`.`fmax_sell_quantity` AS `fmax_sell_quantity`,`p`.`fsku` AS `fsku`,`v`.`id` AS `varient_id`,`v`.`fvariabelDependenc1` AS `fvariabelDependenc1`,`v`.`fvariabelDependenc2` AS `fvariabelDependenc2`,`p`.`fdefult_variabels` AS `fdefult_variabels`,`p`.`fid_brand` AS `fid_brand`,`RETURN_BRANDIMAGEBYID`(`p`.`fid_brand`) AS `brandImage` from (`products` `p` join `products_varients` `v` on(`v`.`fidproduct` = `p`.`id`)) where `p`.`fdeleted` = 0 and `v`.`fdeleted` = 0 and `v`.`factive` = 1 and `p`.`factive` = 1 order by `v`.`id` desc */;

--
-- Final view structure for view `service_view`
--

/*!50001 DROP VIEW IF EXISTS `service_view`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `service_view` AS select `s`.`id` AS `id`,`s`.`fidbilling_details` AS `fidbilling_details`,`s`.`fdesc` AS `fdesc`,`s`.`fstatus` AS `fstatus`,`s`.`ftype` AS `ftype`,`s`.`inserttime` AS `inserttime`,`s`.`fextra` AS `fextra`,`s`.`fdeleted` AS `fdeleted`,`s`.`fexpireDate` AS `fexpireDate`,`p`.`fname` AS `fname`,`p`.`fname_en` AS `fname_en`,`p`.`fimages` AS `fimages`,`p`.`id` AS `fidproduct`,`b`.`fidwebuser` AS `fidwebuser`,concat(`b`.`fname`,' ',`b`.`flastname`) AS `username` from (((`services` `s` join `billing_details` `d` on(`d`.`id` = `s`.`fidbilling_details`)) join `products` `p` on(`p`.`id` = `d`.`fidproduct`)) join `billing` `b` on(`b`.`id` = `d`.`fidbilling`)) */;

--
-- Final view structure for view `store_varient_product_info`
--

/*!50001 DROP VIEW IF EXISTS `store_varient_product_info`*/;
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013  SQL SECURITY DEFINER */
/*!50001 VIEW `store_varient_product_info` AS select `pv`.`id` AS `id`,`pv`.`id` AS `ID_varient_product`,`pv`.`fgarantidesc` AS `fgarantidesc`,`pv`.`fidproduct` AS `fidproduct`,`pv`.`fidstore` AS `fidstore`,`pv`.`fprice` AS `fprice`,`pv`.`factive` AS `factive`,`pv`.`foff` AS `foff`,`pv`.`fdate_update_price` AS `fdate_update_price`,`pv`.`fdeleted` AS `fdeleted`,`pv`.`fis_amazing` AS `fis_amazing`,`pv`.`fis_Single_sale` AS `fis_Single_sale`,`pv`.`amazing_startDate` AS `amazing_startDate`,`pv`.`fcustomBuyBoxdesc` AS `fcustomBuyBoxdesc`,`pv`.`amazing_endDate` AS `amazing_endDate`,`pv`.`amazing_startTime` AS `amazing_startTime`,`pv`.`amazing_endTime` AS `amazing_endTime`,`pv`.`fManage_stock_quantity` AS `fManage_stock_quantity`,`pv`.`fstock_quantity` AS `fstock_quantity`,`pv`.`flow_stock_amount` AS `flow_stock_amount`,`pv`.`fweight` AS `fweight`,`pv`.`flength` AS `flength`,`pv`.`fis_soon` AS `fis_soon`,`pv`.`fwidth` AS `fwidth`,`pv`.`fheight` AS `fheight`,`pv`.`fmax_sell_quantity` AS `fmax_sell_quantity`,`pv`.`fvariabelDependenc1` AS `fvariabelDependenc1`,`pv`.`fvariabelDependenc2` AS `fvariabelDependenc2`,`pv`.`fvariabelDependenc1desc` AS `fvariabelDependenc1desc`,`pv`.`fvariabelDependenc2desc` AS `fvariabelDependenc2desc`,`pv`.`finfo1` AS `finfo1`,`pv`.`finfo2` AS `finfo2`,`pv`.`fsellcount` AS `fsellcount`,`pv`.`fdown_extra` AS `fdown_extra`,`pv`.`amazing_foff` AS `amazing_foff`,`pv`.`fis_freeShip` AS `fis_freeShip`,`pv`.`fcanShappingByMainStore` AS `fcanShappingByMainStore`,`pv`.`fcanShappingBySeller` AS `fcanShappingBySeller`,`pv`.`fdaystoSendMainStore` AS `fdaystoSendMainStore`,`pv`.`finMainStoreStock` AS `finMainStoreStock`,`pv`.`fdaystoSendCustomerByMainStore` AS `fdaystoSendCustomerByMainStore`,`pv`.`fdaystoSendCustomerBySeller` AS `fdaystoSendCustomerBySeller`,`pv`.`ftype` AS `ftype`,`pv`.`frate` AS `frate`,`pv`.`fsuggests` AS `fsuggests`,`pv`.`fcomments` AS `fcomments`,`pv`.`fronding` AS `fronding`,`RETURN_STORENAMEBYID`(`s`.`id`) AS `storeName`,`s`.`fimages` AS `storeLogo`,`s`.`furl` AS `storeUrl`,`s`.`fcode` AS `storeCode`,`s`.`frate` AS `storeRate`,`s`.`fcomments` AS `storeComments`,`s`.`fsuggests` AS `storeSuggests`,`s`.`fimages` AS `storeImages`,`p`.`fzarib` AS `fzarib`,`RETURN_CARRIERNAMEBYID`(`p`.`fidCarrierId`) AS `CarriersData`,`s`.`on_time_shipping` AS `store_on_time_shipping`,`s`.`on_commitment` AS `store_on_commitment`,`s`.`on_no_return` AS `store_on_no_return`,`s`.`finserttime` AS `store_Inserttime`,`s`.`is_new` AS `storeis_new`,`s`.`is_official` AS `storeis_official`,`s`.`is_trusted` AS `storeis_trusted`,`RETURNPRODUCTS_VARIENTS_EXTRA`(`pv`.`id`) AS `products_varients_extra`,`RETURNPRODUCTS_EXTRA`(`p`.`id`) AS `products_extra`,`RETURN_PRODUCT_PRICEUNIT`(`pv`.`id`,`pv`.`fis_amazing`) AS `fpriceUnit`,`FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`pv`.`amazing_startDate`) AS `amazing_startDate_fa`,`FFFFCONVERTMILLADYTOGHAMARY_BYNULL`(`pv`.`amazing_endDate`) AS `amazing_endDate_fa` from ((`products_varients` `pv` join `stores` `s` on(`pv`.`fidstore` = `s`.`id`)) join `products` `p` on(`p`.`id` = `pv`.`fidproduct`)) where `pv`.`fdeleted` = 0 and `pv`.`factive` = 1 and `s`.`fdeleted` = 0 and `s`.`factive` = 1 and (`pv`.`fcanShappingByMainStore` = 1 or `pv`.`fcanShappingBySeller` = 1) */;


