|
1
|
|
|
<?php |
|
2
|
|
|
namespace Xetaravel\Http\Controllers\Shop; |
|
3
|
|
|
|
|
4
|
|
|
use Illuminate\Support\Facades\Auth; |
|
5
|
|
|
use Illuminate\Http\Request; |
|
6
|
|
|
use Xetaravel\Models\ShopItem; |
|
7
|
|
|
use Xetaravel\Notifications\ShopItemNotification; |
|
8
|
|
|
|
|
9
|
|
|
class ItemController extends Controller |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* Buy the item by his id. |
|
13
|
|
|
* |
|
14
|
|
|
* @return \Illuminate\Http\RedirectResponse |
|
15
|
|
|
*/ |
|
16
|
|
|
public function buy(Request $request) |
|
17
|
|
|
{ |
|
18
|
|
|
$item = ShopItem::findOrFail($request->input('item_id')); |
|
19
|
|
|
$user = Auth::user(); |
|
20
|
|
|
|
|
21
|
|
|
if ($item->hasUser($user)) { |
|
22
|
|
|
return back() |
|
23
|
|
|
->with('danger', 'You already own this item !'); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
if ($item->quantity == 0) { |
|
27
|
|
|
return back() |
|
28
|
|
|
->with('danger', 'There\'s no more quantity for this item.'); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
if (!is_null($item->start_at) && $item->start_at->timestamp >= time()) { |
|
32
|
|
|
return back() |
|
33
|
|
|
->with('danger', 'The sale of the item has not yet beginning.'); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
if (!is_null($item->end_at) && $item->end_at->timestamp <= time()) { |
|
37
|
|
|
return back() |
|
38
|
|
|
->with('danger', 'The sale of the item has been finished.'); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
if ($user->rubies_total < $item->price) { |
|
42
|
|
|
return back() |
|
43
|
|
|
->with('danger', 'You don\'t have enough rubies !.'); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
// Attach the new shop_item to the user. |
|
47
|
|
|
$result = $user->shopItems()->syncWithoutDetaching($item); |
|
48
|
|
|
|
|
49
|
|
|
// Decrement user rubies by the price. |
|
50
|
|
|
$user->decrement('rubies_total', $item->price); |
|
51
|
|
|
|
|
52
|
|
|
// If the quantity is limited, then decrement the quantity. |
|
53
|
|
|
if ($item->quantity >= 1) { |
|
54
|
|
|
$item->quantity--; |
|
55
|
|
|
$item->save(); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
if (!empty($result['attached'])) { |
|
59
|
|
|
$user->notify(new ShopItemNotification($item)); |
|
60
|
|
|
|
|
61
|
|
|
return back() |
|
62
|
|
|
->with('success', 'You have successfully bought the item <b>' . e($item->title) . '</b>'); |
|
63
|
|
|
} else { |
|
64
|
|
|
return back() |
|
65
|
|
|
->with('danger', 'Can not sync the item to your account !'); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|