84 lines
2.4 KiB
PHP
84 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Barang;
|
|
use App\Models\Pesanan;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class CheckoutController extends Controller
|
|
{
|
|
public function __construct()
|
|
{
|
|
$this->middleware('auth');
|
|
}
|
|
|
|
public function index(Request $request)
|
|
{
|
|
$request->validate([
|
|
'barang_id' => 'required|exists:barang,id',
|
|
'jumlah' => 'required|integer|min:1',
|
|
]);
|
|
|
|
$barang = Barang::findOrFail($request->barang_id);
|
|
|
|
if ($barang->stok < $request->jumlah) {
|
|
return redirect()->back()->with('error', 'Stok tidak mencukupi');
|
|
}
|
|
|
|
$total = $barang->harga * $request->jumlah;
|
|
|
|
return view('checkout.index', compact('barang', 'total'));
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$request->validate([
|
|
'barang_id' => 'required|exists:barang,id',
|
|
'jumlah' => 'required|integer|min:1',
|
|
'alamat' => 'required|string',
|
|
'metode_pembayaran' => 'required|in:transfer_bank,e_wallet',
|
|
'catatan' => 'nullable|string',
|
|
]);
|
|
|
|
try {
|
|
DB::beginTransaction();
|
|
|
|
$barang = Barang::findOrFail($request->barang_id);
|
|
|
|
if ($barang->stok < $request->jumlah) {
|
|
throw new \Exception('Stok tidak mencukupi');
|
|
}
|
|
|
|
$total = $barang->harga * $request->jumlah;
|
|
|
|
$pesanan = Pesanan::create([
|
|
'user_id' => Auth::id(),
|
|
'barang_id' => $barang->id,
|
|
'jumlah' => $request->jumlah,
|
|
'total_harga' => $total,
|
|
'status' => 'menunggu_pembayaran',
|
|
'alamat_pengiriman' => $request->alamat,
|
|
'metode_pembayaran' => $request->metode_pembayaran,
|
|
'catatan' => $request->catatan,
|
|
]);
|
|
|
|
$barang->update([
|
|
'stok' => $barang->stok - $request->jumlah
|
|
]);
|
|
|
|
DB::commit();
|
|
|
|
return redirect()->route('pesanan.show', $pesanan->id)
|
|
->with('success', 'Pesanan berhasil dibuat. Silakan lakukan pembayaran.');
|
|
|
|
} catch (\Exception $e) {
|
|
DB::rollBack();
|
|
return redirect()->back()
|
|
->with('error', 'Terjadi kesalahan: ' . $e->getMessage())
|
|
->withInput();
|
|
}
|
|
}
|
|
}
|