<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Booking;
use App\Models\Pricelist;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;

class BookingController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
    }

    //milik user untuk upload
    public function getBookings($customerId)
    {
        $bookings = Booking::where('customer_id', $customerId)->get();
        
        return response()->json($bookings);
    }    

    public function getBookingsCustomer()
    {
        try {
            // Ambil semua booking yang statusnya bukan 'declined'
            $bookings = Booking::where('status', '!=', 'declined')->get();
    
            // Ubah data booking ke format yang bisa dibaca FullCalendar
            $bookingsData = $bookings->map(function ($booking) {
                $color = '#007bff'; // Default warna
    
                // Tentukan warna berdasarkan status
                switch ($booking->status) {
                    case 'approved':
                        $color = '#dc3545'; // Merah
                        break;
                    case 'pending':
                        $color = '#facc15'; // Kuning
                        break;
                }
    
                return [
                    'title' => $booking->produk . ' - ' . $booking->paket,
                    'start' => $booking->tanggal_pemotretan,
                    'color' => $color,
                    'status' => $booking->status
                ];
            });
    
            return response()->json($bookingsData);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Gagal mengambil data booking',
                'message' => $e->getMessage()
            ], 500);
        }
    }
    public function uploadBuktiPelunasan(Request $request, $bookingId)
{
    $request->validate([
        'bukti_pelunasan' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        'pelunasan' => 'required|numeric',
    ]);

    $booking = Booking::findOrFail($bookingId);

    if ($request->hasFile('bukti_pelunasan')) {
        $file = $request->file('bukti_pelunasan');
        $filename = time() . '_' . $file->getClientOriginalName();

        // Simpan ke public/images/bukti_pelunasan
        $file->move(public_path('images/bukti_pelunasan'), $filename);

        // Simpan nama file saja di database
        $booking->bukti_pelunasan = $filename;
    }

    $booking->pelunasan = $request->pelunasan;
    $booking->status = 'lunas'; // Update status jika perlu

    $saved = $booking->save();

    \Log::info('Booking ID ' . $booking->id . ' berhasil diperbarui? ' . ($saved ? 'Ya' : 'Tidak'));

    return redirect()->back()->with('success', 'Bukti pelunasan berhasil diunggah.');
}


             
    public function uploadBukti(Request $request, $id)
{
    $request->validate([
        'bukti_transfer' => 'required|image|mimes:jpg,jpeg,png|max:10240',
    ]);

    $booking = Booking::findOrFail($id);

    if ((int) $booking->customer_id !== (int) Auth::id()) {
        abort(403, 'Anda tidak berhak upload bukti untuk booking ini.');
    }

    $destination = public_path('images/bukti_transfer');

    if (!file_exists($destination)) {
        mkdir($destination, 0755, true);
    }

    if (!is_writable($destination)) {
        return back()->withErrors(['bukti_transfer' => 'Folder upload tidak bisa ditulis.']);
    }

    $file = $request->file('bukti_transfer');
    $filename = time() . '_' . $file->getClientOriginalName();

    $file->move($destination, $filename);

    // Simpan path relatif supaya bisa dipanggil pakai asset()
    $booking->bukti_transfer = 'bukti_transfer/' . $filename;
    $booking->save();

    return back()->with('success', 'Bukti transfer berhasil diupload.');
}
  public function index()
    {
        // Mengambil semua booking untuk pengguna yang login
        $bookings = Booking::where('customer_id', Auth::id())
            ->select('produk', 'tanggal_pemotretan')
            ->get()
            ->map(function ($booking) {
                return [
                    'title' => $booking->produk,
                    'start' => $booking->tanggal_pemotretan->format('Y-m-d'),
                ];
            });

        return view('booking.index', compact('bookings'));
    }
    public function create()
    {
        $bookedDates = Booking::pluck('tanggal_pemotretan')->toArray();
        $bookings = Booking::where('customer_id', Auth::id())->orderBy('created_at', 'desc')->get();
        $pricelists = Pricelist::all(); // Pastikan mengambil data terbaru

        $paketPerProduk = $pricelists->mapWithKeys(function ($item) {
            return [strtolower($item->judul) => $item->paket ?? []];
        });

        return view('customer.booking', compact('bookedDates', 'bookings', 'pricelists', 'paketPerProduk'));
    }
    public function keranjang()
    {
        $bookedDates = Booking::pluck('tanggal_pemotretan')->toArray();
        $bookings = Booking::where('customer_id', Auth::id())->orderBy('created_at', 'desc')->get();
        $pricelists = Pricelist::all(); // Pastikan mengambil data terbaru

        $paketPerProduk = $pricelists->mapWithKeys(function ($item) {
            return [strtolower($item->judul) => $item->paket ?? []];
        });

        return view('customer.keranjang', compact('bookedDates', 'bookings', 'pricelists', 'paketPerProduk'));
    }

    

public function store(Request $request)
{
    $user = Auth::user();

    if (!$user || $user->role !== 'customer') {
        return redirect()->back()->with('error', 'Hanya customer yang bisa melakukan booking.');
    }

    $request->validate([
        'produk' => 'required|exists:pricelists,judul',
        'paket' => 'required|string',
        'tanggal_pemotretan' => 'required|date',
        'payment_method' => 'required|string',
        'total_harga' => 'required|numeric',
    ]);

    $produk = Pricelist::where('judul', $request->produk)->firstOrFail();
    $tanggal = $request->tanggal_pemotretan;

    $fullDayConflict = Booking::where('tanggal_pemotretan', $tanggal)
        ->where('durasi_booking', 'full_day')
        ->exists();

    if ($fullDayConflict) {
        return redirect()->back()->with('error', 'Tanggal ini sudah dibooking penuh oleh produk lain.');
    }

    if ($produk->durasi_booking === 'full_day') {
        $anyBooking = Booking::where('tanggal_pemotretan', $tanggal)->exists();

        if ($anyBooking) {
            return redirect()->back()->with('error', 'Sudah ada booking lain di tanggal tersebut. Produk full day tidak bisa dibooking.');
        }
    }

    if ($produk->durasi_booking === 'slot') {
        $jumlahSlotBooking = Booking::where('tanggal_pemotretan', $tanggal)
            ->where('durasi_booking', 'slot')
            ->count();

        if ($jumlahSlotBooking >= 3) {
            return redirect()->back()->with('error', 'Booking slot pada tanggal ini sudah penuh (maksimal 3).');
        }
    }

    // ✅ Simpan booking
    Booking::create([
        'customer_id' => $user->id,
        'produk' => $produk->judul,
        'paket' => $request->paket,
        'tanggal_pemotretan' => $tanggal,
        'payment_method' => $request->payment_method,
        'total_harga' => $request->total_harga,
        'durasi_booking' => $produk->durasi_booking,
        'status' => 'pending', // atau bisa kamu hapus kalau tidak pakai status
    ]);

    return redirect()->back()->with('success', 'Booking berhasil dibuat!');
}
    // ðŸ“Œ Tampilkan Daftar Booking untuk User (Karyawan/Admin)
    public function indexUser()
    {
        $bookings = Booking::where('status', 'pending')->get();
        return view('user.booking', compact('bookings'));
    }

    // ðŸ“Œ Terima Booking
    public function accept($id)
    {
        $booking = Booking::findOrFail($id);
        $booking->status = 'accepted';
        $booking->save();

        return redirect()->route('user.booking')->with('success', 'Booking diterima.');
    }

    // ðŸ“Œ Tolak Booking
    public function decline($id)
    {
        $booking = Booking::findOrFail($id);
        $booking->status = 'declined';
        $booking->save();

        return redirect()->route('user.booking')->with('error', 'Booking ditolak.');
    }
}