<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Cashier;
use App\Models\Product;
use Illuminate\Support\Facades\DB;

class CashierController extends Controller
{
    public function index()
{
    $product = Product::with('category')
        ->where('status', 'aktif') // hanya ambil produk yang status-nya "aktif"
        ->orderBy('createdAt', 'DESC') // urutkan berdasarkan waktu dibuat, terbaru dulu
        ->get();

    return view('cashier', compact('product'));
}

    public function store(Request $request)
    {
        try {
            DB::beginTransaction(); // Mulai transaction untuk memastikan data consistency

            $validated = $request->validate([
                'produk_id'   => 'required|integer|exists:products,id',
                'jumlah_item' => 'required|integer|min:1',
                'total'       => 'required|numeric|min:0',
                'sub_total'   => 'required|numeric|min:0',
                'bayar'       => 'required|numeric|min:0',
                'kembalian'   => 'required|numeric|min:0',
                'diskon'      => 'nullable|numeric|min:0',
                'tipe_bayar'  => 'required|in:Cash,Qris,Debit',
            ]);

            // Ambil produk dan cek stok
            $product = Product::find($validated['produk_id']);

            if (!$product) {
                throw new \Exception('Produk tidak ditemukan');
            }

            if ($product->stok < $validated['jumlah_item']) {
                throw new \Exception("Stok produk {$product->nama_produk} tidak mencukupi");
            }

            // Kurangi stok
            $product->stok -= $validated['jumlah_item'];
            $product->save();

            // Simpan transaksi
            $cashier = Cashier::create([
                'produk_id'   => $validated['produk_id'],
                'jumlah_item' => $validated['jumlah_item'],
                'total'       => $validated['total'],
                'sub_total'   => $validated['sub_total'],
                'bayar'       => $validated['bayar'],
                'kembalian'   => $validated['kembalian'],
                'diskon'      => $validated['diskon'] ?? 0,
                'tipe_bayar'  => $validated['tipe_bayar'],
            ]);

            DB::commit(); // Commit transaction jika semua berhasil

            return response()->json([
                'status'  => 'success',
                'message' => 'Transaksi berhasil disimpan!',
                'data'    => $cashier,
            ], 201);

        } catch (\Exception $e) {
            DB::rollback(); // Rollback jika terjadi error

            return response()->json([
                'status'  => 'error',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    // public function store(Request $request)
    // {
    //     // Validasi input
    //     $validator = Validator::make($request->all(), [
    //         'produk_id'   => 'required|exists:products,id',
    //         // 'waktu_buka'  => 'required|date_format:H:i',
    //         // 'waktu_tutup' => 'required|date_format:H:i',
    //         // 'uang_modal'  => 'required|numeric|min:0',
    //         'jumlah_item' => 'required|integer|min:1',
    //         'total'       => 'required|numeric|min:0',
    //         'sub_total'   => 'required|numeric|min:0',
    //         'bayar'       => 'required|numeric|min:0',
    //         'kembalian'   => 'required|numeric|min:0',
    //         'diskon'      => 'nullable|numeric|min:0',
    //         'tipe_bayar'  => 'required|in:Cash,Qris,Debit',
    //     ]);

    //     if ($validator->fails()) {
    //         return response()->json([
    //             'status' => 'error',
    //             'errors' => $validator->errors(),
    //         ], 422);
    //     }

    //     // Simpan transaksi ke database
    //     $cashier = Cashier::create([
    //         'produk_id'   => $request->produk_id,
    //         // 'waktu_buka'  => $request->waktu_buka,
    //         // 'waktu_tutup' => $request->waktu_tutup,
    //         // 'uang_modal'  => $request->uang_modal,
    //         'jumlah_item' => $request->jumlah_item,
    //         'total'       => $request->total,
    //         'sub_total'   => $request->sub_total,
    //         'bayar'       => $request->bayar,
    //         'kembalian'   => $request->kembalian,
    //         'diskon'      => $request->diskon,
    //         'tipe_bayar'  => $request->tipe_bayar,
    //         'createdAt'   => now(),
    //         'updatedAt'   => now(),
    //     ]);

    //     return response()->json([
    //         'status'  => 'success',
    //         'message' => 'Transaksi berhasil disimpan!',
    //         'data'    => $cashier,
    //     ], 201);
    // }
}