/**
  * Inserts single codes, generates bulks
  */
 public function procShopToolInsertCoupon()
 {
     $repository = new CouponRepository();
     $args = Context::getRequestVars();
     $args->active = (int) $args->active;
     $args->module_srl = $this->module_info->module_srl;
     $logged_info = Context::get('logged_info');
     if ($logged_info->member_srl) $args->member_srl = $logged_info->member_srl;
     $args->ip = $_SERVER['REMOTE_ADDR'];
     $coupon = new Coupon($args);
     try {
         /**
          * Update [both]
          */
         if ($coupon->isPersisted() && $exists = $repository->get($coupon->srl)) { //
             /** @var $exists Coupon */
             $coupon->type = $exists->type;
             $out = $coupon->save();
             $repository->check($out);
             if ($coupon->isGroup()) {
                 $this->setMessage("Updated group <b>{$coupon->name}</b>");
             }
             elseif ($coupon->isSingle()) {
                 $this->setMessage("Updated coupon <b>{$coupon->code}</b>");
             }
         }
         /**
          * Group Insert
          */
         elseif (is_numeric($n = Context::get('codes_number')) && $n > 1) {
             $coupon->type = Coupon::TYPE_PARENT;
             $out = $coupon->save();
             $repository->check($out);
             $length = Context::get('code_length');
             $type = Context::get('code_type');
             $pattern = Context::get('code_pattern');
             if (!strstr($pattern, 'CODE')) throw new ShopException('Pattern must contain "CODE"');
             $pattern = str_replace('CODE', 'X', $pattern);
             $separateEvery = Context::get('separate_at');
             $coupons = $coupon->generateBulk($n, $length, $type, $pattern, $separateEvery);
             $this->setMessage('Generated ' . count($coupons) . ' (grouped) coupons');
         }
         /**
          * Single insert
          */
         else {
             $coupon->type = Coupon::TYPE_SINGLE;
             $out = $coupon->save();
             $repository->check($out);
             $this->setMessage("Generated single coupon with code <b>{$coupon->code}</b>");
         }
     }
     catch (Exception $e) {
         $msg = $e->getMessage();
         if (strstr($msg, 'unique_module_code')) {
             $msg = "Code '<b>{$coupon->code}</b>' is already in use";
         }
         return new Object(-1, $msg);
     }
     $this->setRedirectUrl(getNotEncodedUrl('', 'act', 'dispShopToolDiscountCodes', 'highlight', $coupon->srl));
 }