public function updateProduct()
 {
     if (Input::has('pk')) {
         if (!Request::ajax()) {
             return App::abort(404);
         }
         return self::updateQuickEdit();
     }
     $prevURL = Request::header('referer');
     if (!Request::isMethod('post')) {
         return App::abort(404);
     }
     if (Input::has('id')) {
         $create = false;
         try {
             $product = Product::findorFail((int) Input::get('id'));
         } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
             return App::abort(404);
         }
         $message = 'has been updated successful';
     } else {
         $create = true;
         $product = new Product();
         $message = 'has been created successful';
     }
     if (!Input::has('categories')) {
         return Redirect::to($prevURL)->with('flash_error', ['Please choose at least one category.'])->withInput();
     }
     $product->name = Input::get('name');
     $product->short_name = Str::slug($product->name);
     $product->sku = Input::get('sku');
     $product->sell_price = Input::has('sell_price') ? round((double) str_replace(',', '', Input::get('sell_price')), 2) : 0;
     $product->margin_up = (double) Input::get('margin_up');
     $product->product_type_id = (int) Input::get('product_type_id');
     $product->order_no = (int) Input::get('order_no');
     $product->custom_size = Input::has('custom_size') ? 1 : 0;
     $product->active = Input::has('active') ? 1 : 0;
     $product->meta_title = e(Input::get('meta_title'));
     $product->meta_description = e(Input::get('meta_description'));
     $product->short_description = e(Input::get('short_description'));
     $product->description = Input::get('description');
     $product->default_view = json_encode(Input::has('default_view') ? Input::get('default_view') : []);
     $product->svg_layout_id = Input::has('svg_layout_id') ? Input::get('svg_layout_id') : 0;
     $pass = $product->valid();
     if (Input::hasFile('svg_file')) {
         $file = Input::file('svg_file');
         // if( $file->getMimeType() === 'image/svg+xml' ) {
         $path = public_path() . DS . 'assets' . DS . 'svg';
         if (!File::exists($path)) {
             File::makeDirectory($path);
         }
         $fileName = md5($file->getClientOriginalName()) . '.svg';
         if ($file->move($path, $fileName)) {
             if (isset($product->svg_file) && File::exists(public_path() . DS . $product->svg_file)) {
                 File::delete($product->svg_file);
             }
             $product->svg_file = 'assets/svg/' . $fileName;
         }
         /*} else {
         			return Redirect::to($prevURL)->with('flash_error',['SVG file is not valid.'])->withInput();
         		}*/
     }
     if ($pass->passes()) {
         $product->save();
         // Category, Option Group, Option ==================================================================
         $arr = ['categories' => 'categories', 'optionGroups' => 'option_group_id', 'options' => 'option_id'];
         foreach ($arr as $key => $value) {
             $old = $product->{$key}->toArray();
             $arrData = Input::has($value) ? Input::get($value) : [];
             $arrOld = $remove = $add = [];
             if (!empty($old)) {
                 foreach ($old as $val) {
                     $arrOld[] = $val['id'];
                     if (!in_array($val['id'], $arrData)) {
                         $remove[] = $val['id'];
                     }
                 }
             }
             foreach ($arrData as $id) {
                 if (!in_array($id, $arrOld)) {
                     $add[] = $id;
                 }
             }
             if (!empty($remove)) {
                 $product->{$key}()->detach($remove);
             }
             if (!empty($add)) {
                 $product->{$key}()->attach($add);
             }
         }
         // End ==============================================================================================
         // Images ===========================================================================================
         $path = public_path() . DS . 'assets' . DS . 'images' . DS . 'products';
         $removeImages = $createImages = [];
         if (Input::has('images')) {
             $images = Input::get('images');
             foreach ($images as $key => $image) {
                 $data = ['main' => 0, 'view' => []];
                 if (isset($image['delete']) && $image['delete']) {
                     $removeImages[] = $image['id'];
                     unset($images[$key]);
                     continue;
                 }
                 if (isset($image['view']) && !empty($image['view'])) {
                     foreach ($image['view'] as $optionGroupID => $optionID) {
                         if (!$optionID) {
                             continue;
                         }
                         $data['view'][$optionID] = $optionID;
                     }
                     $data['view'] = array_values($data['view']);
                 }
                 if (isset($image['main'])) {
                     $data['main'] = 1;
                 }
                 $data = json_encode($data);
                 $image_id = 0;
                 if (Input::hasFile("images.{$key}.file")) {
                     $file = Input::file("images.{$key}.file");
                     $image_id = VIImage::upload($file, $path, 500);
                 } else {
                     if (isset($image['choose_image'])) {
                         $image_id = $image['choose_image'];
                     }
                 }
                 if ($image_id != 0) {
                     if (isset($image['id'])) {
                         $product->images()->updateExistingPivot($image['id'], ['image_id' => $image_id, 'option' => $data]);
                     } else {
                         $createImages[$image_id] = ['option' => $data, 'imageable_id' => $product->id, 'imageable_type' => 'Product'];
                     }
                 } else {
                     if (isset($image['new'])) {
                         continue;
                     } else {
                         $product->images()->updateExistingPivot($image['id'], ['option' => $data]);
                     }
                 }
             }
             if (!empty($removeImages)) {
                 $product->images()->detach($removeImages);
             }
             if (!empty($createImages)) {
                 $product->images()->attach($createImages);
             }
         }
         // End ==============================================================================================
         // Price breaks =====================================================================================
         $removePB = $createPB = [];
         if (Input::has('price_breaks')) {
             $price_breaks = Input::get('price_breaks');
             foreach ($price_breaks as $id => $pk) {
                 $pk['sell_price'] = str_replace(',', '', $pk['sell_price']);
                 if (isset($pk['id'])) {
                     if (isset($pk['delete']) && $pk['delete']) {
                         $removePB[] = $pk['id'];
                     } else {
                         $product->priceBreaks()->where('price_breaks.id', $pk['id'])->update(['range_from' => (int) $pk['range_from'], 'range_to' => (int) $pk['range_to'], 'sell_price' => (double) $pk['sell_price']]);
                     }
                 } else {
                     $createPB[] = new PriceBreak(['range_from' => (int) $pk['range_from'], 'range_to' => (int) $pk['range_to'], 'sell_price' => (double) $pk['sell_price']]);
                 }
             }
             if (!empty($removePB)) {
                 PriceBreak::destroy($removePB);
             }
             if (!empty($createPB)) {
                 $product->priceBreaks()->saveMany($createPB);
             }
         }
         // End ==============================================================================================
         // Price lists ======================================================================================
         $removeSL = $createSL = [];
         if (Input::has('price_lists')) {
             $size_lists = Input::get('price_lists');
             foreach ($size_lists as $id => $sl) {
                 $arr = [];
                 foreach (['sizew', 'sizeh', 'cost_price', 'sell_price', 'bigger_price', 'sell_percent', 'bigger_percent'] as $float) {
                     $sl[$float] = (double) str_replace(',', '', $sl[$float]);
                     $arr[$float] = $sl[$float];
                 }
                 $arr['default'] = 0;
                 if (isset($sl['default'])) {
                     $arr['default'] = 1;
                 }
                 if (isset($sl['id'])) {
                     if (isset($sl['delete']) && $sl['delete']) {
                         $removeSL[] = $sl['id'];
                     } else {
                         $product->sizeLists()->where('size_lists.id', $sl['id'])->update($arr);
                     }
                 } else {
                     $createSL[] = new SizeList($arr);
                 }
             }
             if (!empty($removeSL)) {
                 SizeList::destroy($removeSL);
             }
             if (!empty($createSL)) {
                 $product->sizeLists()->saveMany($createSL);
             }
         }
         // End ==============================================================================================
         if (Input::has('continue')) {
             if ($create) {
                 $prevURL = URL . '/admin/products/edit-product/' . $product->id;
             }
             return Redirect::to($prevURL)->with('flash_success', "<b>{$product->name}</b> {$message}.");
         }
         return Redirect::to(URL . '/admin/products')->with('flash_success', "<b>{$product->name}</b> {$message}.");
     }
     return Redirect::to($prevURL)->with('flash_error', $pass->messages()->all())->withInput();
 }
 public function updateConfigure()
 {
     if (Input::has('pk')) {
         if (!Request::ajax()) {
             return App::abort(404);
         }
         return self::updateQuickEdit();
     } else {
         if (Request::ajax()) {
             $arrReturn = ['status' => 'error'];
             $configure = new Configure();
             $configure->cname = Input::get('cname');
             $configure->ckey = Input::get('ckey');
             if (Input::hasFile('cvalue')) {
                 $path = app_path('files');
                 if (!File::exists($path)) {
                     File::makeDirectory($path, 493, true);
                 }
                 $path = str_replace(['\\', '/'], DS, $path);
                 $file = Input::file('cvalue');
                 $file->move($path, $configure->ckey . '.' . $file->getClientOriginalExtension());
                 $configure->cvalue = $path . DS . $configure->ckey . '.' . $file->getClientOriginalExtension();
             } else {
                 $configure->cvalue = Input::get('cvalue');
             }
             $configure->cdescription = Input::get('cdescription');
             $configure->active = Input::has('active') ? 1 : 0;
             $pass = $configure->valid();
             if ($pass) {
                 $configure->save();
                 $arrReturn = ['status' => 'ok'];
                 $arrReturn['message'] = $configure->cname . ' has been saved';
                 $arrReturn['data'] = $configure;
             } else {
                 $arrReturn['message'] = '';
                 $arrErr = $pass->messages()->all();
                 foreach ($arrErr as $value) {
                     $arrReturn['message'] .= "{$value}\n";
                 }
             }
             $response = Response::json($arrReturn);
             $response->header('Content-Type', 'application/json');
             return $response;
         }
     }
     $arrPost = Input::all();
     unset($arrPost['_token']);
     foreach ($arrPost as $key => $value) {
         if (in_array($key, ['main_logo', 'favicon'])) {
             if (!Input::hasFile($key)) {
                 continue;
             }
             if ($key == 'main_logo') {
                 $path = public_path('assets' . DS . 'images' . DS . 'logos');
                 $width = 400;
                 $name = 'logo';
             } else {
                 if ($key == 'favicon') {
                     $path = public_path('assets' . DS . 'images' . DS . 'favicons');
                     $width = 16;
                     $name = 'favicon';
                 }
             }
             $configure = Configure::firstOrNew(['ckey' => $key]);
             $configure->ckey = $key;
             $configure->cname = Str::title(str_replace('_', ' ', $key));
             if (!empty($configure->cvalue) && File::exists(public_path($configure->cvalue))) {
                 File::delete(public_path($configure->cvalue));
             }
             $path = VIImage::upload(Input::file($key), $path, $width, false, $name);
             $path = str_replace(public_path() . DS, '', $path);
             $configure->cvalue = str_replace(DS, '/', $path);
             $configure->save();
         } else {
             $configure = Configure::firstOrNew(['ckey' => $key]);
             $configure->ckey = $key;
             $configure->cname = Str::title(str_replace('_', ' ', $key));
             $configure->cvalue = $value;
             $configure->save();
             if ($key == 'mask') {
                 Cache::tags('images')->flush();
                 Cache::forever('mask', $value);
             }
         }
     }
     return Redirect::to(URL . '/admin/configures')->with('flash_success', 'Main Configure has been saved.');
 }
 public function uploadFile()
 {
     if (Auth::user()->check()) {
         if (Input::hasFile('myfiles')) {
             $name = Input::get('name');
             $short_name = Str::slug($name);
             $description = Input::get('description');
             $keywords = Input::get('keywords');
             $keywords = rtrim(trim($keywords), ',');
             $model = Input::get('model');
             $model = rtrim(trim($model), ',');
             $artist = Input::get('artist');
             $age_from = Input::get('age_from');
             $age_to = Input::get('age_to');
             $gender = Input::get('gender');
             $number_people = Input::get('number_people');
             $type_id = Input::get('type_id');
             $arr_category_ids = Input::get('category_id');
             $faker = Faker::create();
             $destination_store = Input::get('destination_store');
             //insert to images table
             // $keywords = '';
             // for( $i = 0; $i < $faker->numberBetween(4, 9); $i++ ) {
             //     $keywords .= $faker->word.',';
             // }
             // $keywords = rtrim($keywords, ',');
             // $name = $faker->name;
             // $short_name = Str::slug($name);
             // $gender = $faker->randomElement($array = array ('male','female','both','any'));
             // $age_from = $faker->numberBetween(0, 90);
             // $age_to = $faker->numberBetween(0, 90);
             // while($age_from >$age_to){
             //     $age_from = $faker->numberBetween(0, 90);
             //     $age_to = $faker->numberBetween(0, 90);
             // }
             $ethnicity = $faker->randomElement($array = array('african', 'african_american', 'black', 'brazilian', 'chinese', 'caucasian', 'east_asian', 'hispanic', 'japanese', 'middle_eastern', 'native_american', 'pacific_islander', 'south_asian', 'southeast_asian', 'other', 'any'));
             //$number_people = $faker->numberBetween(0, 10);
             $editorial = $faker->numberBetween(0, 1);
             //$type_id = $faker->numberBetween(1, 3);
             $color_extractor = new ColorExtractor();
             $myfiles = Input::file('myfiles');
             $mime_type = $myfiles[0]->getClientMimeType();
             switch ($mime_type) {
                 case 'image/jpeg':
                     $palette_obj = $color_extractor->loadJpeg($myfiles[0]);
                     break;
                 case 'image/png':
                     $palette_obj = $color_extractor->loadPng($myfiles[0]);
                     break;
                 case 'image/gif':
                     $palette_obj = $color_extractor->loadGif($myfiles[0]);
                     break;
                 default:
                     # code...
                     break;
             }
             $main_color = '';
             if (is_object($palette_obj)) {
                 $arr_palette = $palette_obj->extract(5);
                 if (!empty($arr_palette)) {
                     $main_color = strtolower($arr_palette[0]);
                     for ($i = 1; $i < count($arr_palette); $i++) {
                         $main_color .= ',' . strtolower($arr_palette[$i]);
                     }
                 }
             }
             $image_id = VIImage::insertGetId(['name' => $name, 'short_name' => $short_name, 'description' => $description, 'keywords' => $keywords, 'main_color' => $main_color, 'type_id' => $type_id, 'model' => $model, 'artist' => $artist, 'gender' => $gender, 'age_from' => $age_from, 'age_to' => $age_to, 'ethnicity' => $ethnicity, 'number_people' => $number_people, 'editorial' => $editorial, 'author_id' => Auth::user()->get()->id, 'store' => $destination_store]);
             //insert into statistic_images table
             StatisticImage::create(['image_id' => $image_id, 'view' => '0', 'download' => '0']);
             //insert into images_categories table
             if (!empty($arr_category_ids)) {
                 foreach ($arr_category_ids as $category_id) {
                     ImageCategory::create(['image_id' => $image_id, 'category_id' => $category_id]);
                 }
             }
             $result = array();
             for ($i = 0; $i < count($myfiles); $i++) {
                 $file = $myfiles[$i];
                 $extension = strtolower($file->getClientOriginalExtension());
                 $file_name = $faker->lexify($string = '???????????????????');
                 $url = $file_name . "." . $extension;
                 //get image's information
                 $file_content = file_get_contents($file);
                 $image = new Imagick();
                 $image->pingImageBlob($file_content);
                 $dpi = $image->getImageResolution();
                 $dpi = $dpi['x'] > $dpi['y'] ? $dpi['x'] : $dpi['y'];
                 $size = $image->getImageLength();
                 $width = $image->getImageWidth();
                 $height = $image->getImageHeight();
                 $result[$i]['filename'] = $file->getClientOriginalName();
                 $result[$i]['result'] = true;
                 if ($destination_store == 'dropbox') {
                     try {
                         $this->filesystem->write($url, $file_content);
                     } catch (\Dropbox\Exception $e) {
                         $result[$i]['result'] = false;
                         echo $e->getMessage();
                     }
                 } else {
                     $upload_folder = 'assets' . DS . 'upload' . DS . 'images' . DS . $image_id;
                     $imgDir = public_path() . DS . $upload_folder;
                     if (!File::exists($imgDir)) {
                         File::makeDirectory($imgDir, 0755);
                     }
                     $url = $upload_folder . DS . $url;
                     $url = str_replace('\\', '/', $url);
                     if (!VIImage::upload($file, $imgDir, $width, true, $file_name)) {
                         $result[$i]['result'] = false;
                     }
                 }
                 //insert to image_details table
                 $id = VIImageDetail::insertGetId(['path' => $url, 'height' => $height, 'width' => $width, 'ratio' => $width / $height, 'dpi' => $dpi, 'size' => $size, 'extension' => $extension, 'type' => 'main', 'size_type' => $i + 1, 'image_id' => $image_id]);
                 if (!$id) {
                     $result[$i]['result'] = false;
                 }
             }
             Session::flash('message', $result);
         } else {
             Session::flash('message', 'Please choose the image!');
         }
         return Redirect::route('upload-page');
     }
     return Redirect::route('account-sign-in');
 }
 public function updateAdmin()
 {
     if (Request::ajax() && Input::has('pk')) {
         $arrPost = Input::all();
         if ($arrPost['name'] == 'active') {
             $arrPost['value'] = (int) $arrPost['value'];
         }
         Admin::where('id', $arrPost['pk'])->update([$arrPost['name'] => $arrPost['value']]);
         return Response::json(['status' => 'ok']);
     }
     $prevURL = Request::header('referer');
     if (!Request::isMethod('post')) {
         return App::abort(404);
     }
     if (Input::has('id')) {
         $create = false;
         try {
             $admin = Admin::findorFail((int) Input::get('id'));
         } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
             return App::abort(404);
         }
         $message = 'has been updated successful';
         unset($admin->password);
         if (Input::has('password')) {
             if (Input::has('password') && Input::has('password_confirmation')) {
                 $password = Input::get('password');
                 $admin->password = Input::get('password');
                 $admin->password_confirmation = Input::get('password_confirmation');
             }
         }
     } else {
         $create = true;
         $admin = new Admin();
         $message = 'has been created successful';
         $password = Input::get('password');
         $admin->password = $password;
         $admin->password_confirmation = Input::get('password_confirmation');
     }
     $admin->email = Input::get('email');
     $admin->first_name = Input::get('first_name');
     $admin->last_name = Input::get('last_name');
     $admin->active = Input::has('active') ? 1 : 0;
     $oldRole = 0;
     if (isset($admin->role_id) && $admin->role_id) {
         $oldRole = $admin->role_id;
     }
     $admin->role_id = Input::has('role_id') ? Input::get('role_id') : 0;
     if (Input::hasFile('image')) {
         $oldPath = $admin->image;
         $path = VIImage::upload(Input::file('image'), public_path('assets' . DS . 'images' . DS . 'admins'), 110, false);
         $path = str_replace(public_path() . DS, '', $path);
         $admin->image = str_replace(DS, '/', $path);
         if ($oldPath == $admin->image) {
             unset($oldPath);
         }
     }
     $pass = $admin->valid();
     if ($pass->passes()) {
         if (isset($admin->password_confirmation)) {
             unset($admin->password_confirmation);
         }
         if (isset($password)) {
             $admin->password = Hash::make($password);
         }
         $admin->save();
         if ($oldRole != $admin->role_id) {
             if ($oldRole) {
                 $admin->roles()->detach($oldRole);
             }
             if ($admin->role_id) {
                 $admin->roles()->attach($admin->role_id);
             }
         }
         if (isset($oldPath) && File::exists(public_path($oldPath))) {
             File::delete(public_path($oldPath));
         }
         if (Input::has('continue')) {
             if ($create) {
                 $prevURL = URL . '/admin/admins/edit-admin/' . $admin->id;
             }
             return Redirect::to($prevURL)->with('flash_success', "<b>{$admin->first_name} {$admin->last_name}</b> {$message}.");
         }
         return Redirect::to(URL . '/admin/admins')->with('flash_success', "<b>{$admin->first_name} {$admin->last_name}</b> {$message}.");
     }
     return Redirect::to($prevURL)->with('flash_error', $pass->messages()->all())->withInput();
 }
 public function updateQuickEdit()
 {
     $arrReturn = ['status' => 'error'];
     $id = (int) Input::get('pk');
     $name = Input::get('name');
     $value = Input::get('value');
     try {
         $type = Type::findorFail($id);
         if ($name == 'image') {
             if (Input::hasFile('image')) {
                 $file = Input::file('image');
                 $path = VIImage::upload(Input::file('image'), public_path('assets' . DS . 'images' . DS . 'types'), 1360, false);
                 $path = str_replace(public_path() . DS, '', $path);
                 $path = str_replace(DS, '/', $path);
                 if ($path) {
                     $oldImg = $type->image;
                     $type->image = $path;
                 }
             }
         } else {
             $value = Input::get('value');
             if ($name == 'active') {
                 $type->active = (int) $value;
             } else {
                 $type->{$name} = $value;
             }
         }
     } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
         return App::abort(404);
     }
     $pass = $type->valid();
     if ($pass->passes()) {
         $type->save();
         if (isset($oldImg) && File::exists(public_path($oldImg))) {
             File::delete(public_path($oldImg));
         }
         $arrReturn = ['status' => 'ok'];
         $arrReturn['message'] = $type->name . ' has been saved';
         $arrReturn['image'] = $type->image;
     } else {
         $arrReturn['message'] = '';
         $arrErr = $pass->messages()->all();
         foreach ($arrErr as $value) {
             $arrReturn['message'] .= "{$value}\n";
         }
     }
     return $arrReturn;
 }
 public function updateProductCategory()
 {
     if (Input::has('pk')) {
         if (!Request::ajax()) {
             return App::abort(404);
         }
         return self::updateQuickEdit();
     }
     $prevURL = Request::header('referer');
     if (!Request::isMethod('post')) {
         return App::abort(404);
     }
     if (Input::has('id')) {
         $create = false;
         try {
             $category = ProductCategory::findorFail((int) Input::get('id'));
         } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
             return App::abort(404);
         }
         $message = 'has been updated successful';
     } else {
         $create = true;
         $category = new ProductCategory();
         $message = 'has been created successful';
     }
     $category->name = Input::get('name');
     $category->short_name = Str::slug($category->name);
     $category->parent_id = (int) Input::get('parent_id');
     $category->order_no = (int) Input::get('order_no');
     $category->active = Input::has('active') ? 1 : 0;
     $category->meta_title = e(Input::get('meta_title'));
     $category->meta_description = e(Input::get('meta_description'));
     $pass = $category->valid();
     if ($pass->passes()) {
         $action = Input::has('on_menu') ? 'add' : 'delete';
         $category = Menu::updateMenu($category, $action, 'collections/');
         $category->save();
         $imageId = 0;
         if (Input::hasFile('image')) {
             $imageId = VIImage::upload(Input::file('image'), public_path() . DS . 'assets' . DS . 'images' . DS . 'product_categories', 450, false);
         } else {
             if (Input::has('choose_image')) {
                 $imageId = Input::get('choose_image');
             }
         }
         if ($imageId) {
             $category->images()->detach();
             $category->images()->attach($imageId);
         }
         if (Input::has('continue')) {
             if ($create) {
                 $prevURL = URL . '/admin/categories/edit-category/' . $category->id;
             }
             return Redirect::to($prevURL)->with('flash_success', "<b>{$category->name}</b> {$message}.");
         }
         return Redirect::to(URL . '/admin/categories')->with('flash_success', "<b>{$category->name}</b> {$message}.");
     }
     return Redirect::to($prevURL)->with('flash_error', $pass->messages()->all())->withInput();
 }