<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Reservasi;

class RiwayatController extends Controller
{
    public function index()
    {
        // Mengambil semua riwayat pesanan user yang login
        $riwayats = Reservasi::where('user_id', auth()->id())
                            ->with(['meja', 'transaksi', 'detailPesanan.menu'])
                            ->orderBy('created_at', 'desc')
                            ->get();
        
        return view('riwayat', compact('riwayats'));
    }

    public function show($id)
    {
        // Menampilkan detail riwayat pesanan
        $riwayat = Reservasi::with(['meja', 'transaksi', 'detailPesanan.menu'])
                           ->where('user_id', auth()->id())
                           ->findOrFail($id);
        
        // Redirect ke halaman detail transaksi jika ada transaksi
        if ($riwayat->transaksi) {
            return redirect()->route('transaksi.show', $riwayat->transaksi->id);
        }
        
        return view('riwayat.show', compact('riwayat'));
    }

    public function filter(Request $request)
    {
        // Validasi input
        $request->validate([
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date'
        ]);

        // Filter riwayat berdasarkan tanggal
        $riwayats = Reservasi::where('user_id', auth()->id())
                            ->whereBetween('date', [
                                $request->start_date,
                                $request->end_date
                            ])
                            ->with(['meja', 'transaksi', 'detailPesanan.menu'])
                            ->orderBy('created_at', 'desc')
                            ->get();
        
        return view('riwayat', compact('riwayats'));
    }
}