<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Meja;
use App\Models\Reservasi;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;

class TableController extends Controller
{
    public function index()
    {
        $tables = Meja::orderBy('nomor_meja')->get();
        return view('admin.tables', compact('tables'));
    }

    public function store(Request $request)
    {
        try {
            $request->validate([
                'nomor_meja' => 'required|string|unique:meja,nomor_meja',
                'kapasitas' => 'required|integer|min:1',
                'kategori' => 'required|in:outdoor,vip-outdoor,vip-indoor',
                'status' => 'required|in:tersedia,tidak_tersedia',
                'deskripsi' => 'nullable|string',
                'gambar' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
            ]);

            $data = $request->except('gambar');

            if ($request->hasFile('gambar')) {
                $gambar = $request->file('gambar');
                $filename = 'meja_' . time() . '_' . Str::random(10) . '.' . $gambar->getClientOriginalExtension();
                
                // Store file in public disk
                $path = $gambar->storeAs('meja', $filename, 'public');
                if (!$path) {
                    throw new \Exception('Gagal mengupload gambar');
                }
                
                $data['gambar'] = $path;
            }

            $table = Meja::create($data);

            if ($request->ajax()) {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Meja berhasil ditambahkan',
                    'data' => $table
                ]);
            }

            return redirect()->back()->with('success', 'Meja berhasil ditambahkan');
        } catch (\Exception $e) {
            Log::error('Error in TableController@store: ' . $e->getMessage());
            
            if ($request->ajax()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Terjadi kesalahan saat menambahkan meja: ' . $e->getMessage()
                ], 500);
            }
            
            return redirect()->back()
                ->with('error', 'Terjadi kesalahan saat menambahkan meja: ' . $e->getMessage())
                ->withInput();
        }
    }

    public function update(Request $request, Meja $table)
    {
        try {
            $request->validate([
                'nomor_meja' => 'required|string|unique:meja,nomor_meja,' . $table->id,
                'kapasitas' => 'required|integer|min:1',
                'kategori' => 'required|in:outdoor,vip-outdoor,vip-indoor',
                'status' => 'required|in:tersedia,tidak_tersedia',
                'deskripsi' => 'nullable|string',
                'gambar' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
            ]);

            $data = $request->except('gambar');

            if ($request->hasFile('gambar')) {
                // Hapus gambar lama jika ada
                if ($table->gambar) {
                    Storage::disk('public')->delete($table->gambar);
                }

                $gambar = $request->file('gambar');
                $filename = 'meja_' . time() . '_' . Str::random(10) . '.' . $gambar->getClientOriginalExtension();
                
                // Store file in public disk
                $path = $gambar->storeAs('meja', $filename, 'public');
                if (!$path) {
                    throw new \Exception('Gagal mengupload gambar');
                }
                
                $data['gambar'] = $path;
            }

            $table->update($data);

            if ($request->ajax()) {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Meja berhasil diperbarui',
                    'data' => $table
                ]);
            }

            return redirect()->back()->with('success', 'Meja berhasil diperbarui');
        } catch (\Exception $e) {
            Log::error('Error in TableController@update: ' . $e->getMessage());
            
            if ($request->ajax()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Terjadi kesalahan saat memperbarui meja: ' . $e->getMessage()
                ], 500);
            }
            
            return redirect()->back()
                ->with('error', 'Terjadi kesalahan saat memperbarui meja: ' . $e->getMessage())
                ->withInput();
        }
    }

    public function destroy(Meja $table)
    {
        try {
            // Hapus gambar jika ada
            if ($table->gambar) {
                Storage::disk('public')->delete($table->gambar);
            }

            $table->delete();
            return redirect()->back()->with('success', 'Meja berhasil dihapus');
        } catch (\Exception $e) {
            Log::error('Error in TableController@destroy: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Terjadi kesalahan saat menghapus meja: ' . $e->getMessage());
        }
    }

    public function getSchedule(Request $request, $id)
    {
        $request->validate([
            'date' => 'required|date'
        ]);

        $reservations = Reservasi::where('meja_id', $id)
            ->whereDate('date', $request->date)
            ->where('status', '!=', 'cancelled')
            ->select('name', 'people', 'start_time', 'end_time', 'status')
            ->orderBy('start_time')
            ->get();

        return response()->json([
            'success' => true,
            'reservations' => $reservations
        ]);
    }
} 