<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Booking;
use App\Models\Photo;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Session;


class UserController extends Controller
{
    // ðŸ“Œ 1. Menampilkan Dashboard User
    public function dashboard()
    {
        $customers = User::where('role', 'customer')->get();
        return view('dashboard.user', compact('customers'));
    }

    // ðŸ“Œ 2. Menampilkan Daftar Booking User
public function myBookings(Request $request)
    {
        $search = $request->input('search');

        $bookings = Booking::with('customer')
            ->when($search, function ($query, $search) {
                $query->whereHas('customer', function ($q) use ($search) {
                    $q->where('name', 'like', '%' . $search . '%');
                });
            })
            ->orderBy('created_at', 'desc')
            ->get();

        return view('user.booking', compact('bookings'));
    }

    public function acceptBooking(Request $request, $id)
    {
        $booking = Booking::findOrFail($id);
    
        $booking->status = 'approved';
        $booking->dp = $request->input('dp');
        $booking->keterangan = $request->input('keterangan'); // opsional
        $booking->save();
    
        return redirect()->back()->with('success', 'Booking berhasil diterima.');
    }    
    
    public function rejectBooking(Request $request, $id)
    {
        $request->validate([
            'keterangan' => 'required|string|max:255',
        ]);

        $booking = Booking::findOrFail($id);
        $booking->status = 'declined';
        $booking->keterangan = $request->input('keterangan');
        $booking->save();

        return redirect()->back()->with('success', 'Booking berhasil ditolak.');
    }

    


    // ðŸ“Œ 5. Menampilkan Profil User
    public function profile()
    {
        $user = Auth::user();
        return view('user.profile', compact('user'));
    }

    // ðŸ“Œ 6. Mengupdate Profil User
    

    // ðŸ“Œ 1. Menampilkan Halaman Upload
    public function uploadPage()
    {
        $customers = User::where('role', 'customer')->get();
        return view('user.upload', compact('customers'));
    }

    public function storeUpload(Request $request)
    {
        $request->validate([
            'customer_id' => 'required|exists:users,id',
            'photos' => 'required',
            'photos.*' => 'image|mimes:jpeg,png,jpg|max:2048',
        ]);
    
        foreach ($request->file('photos') as $photo) {
            $path = $photo->store('photos', 'public');
            $token = Str::random(10);
    
            Photo::create([
                'customer_id' => $request->customer_id,
                'file_path' => $path,
                'token' => $token,
            ]);
        }
    
        return redirect()->route('user.upload')->with('success', 'Foto berhasil diunggah.');
    }
    
    // ðŸ“Œ 3. Menampilkan Foto Berdasarkan Token
    public function showPhotos($token)
    {
        $photos = Photo::where('token', $token)->get();
        if ($photos->isEmpty()) {
            return abort(404, 'Token tidak ditemukan.');
        }

        return view('user.view-photos', compact('photos'));
    }

    public function showCustomers(Request $request)
    {
        $search = $request->input('search');

        $customers = User::where('role', 'customer')
            ->when($search, function ($query, $search) {
                $query->where('name', 'like', '%' . $search . '%');
            })
            ->get();

        return view('user.customers', compact('customers'));
    }
    public function deleteCustomer($id)
    {
        $customer = User::findOrFail($id);
        $customer->delete();
    
        return redirect()->route('user.customers')->with('success', 'Customer berhasil dihapus.');
    }
    public function edit($id)
    {
        $customer = User::where('role', 'customer')->findOrFail($id);
        return response()->json($customer);
    }
    public function updateProfile(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $user->id,
            'password' => 'nullable|min:6|confirmed',
        ]);

        $user->name = $request->name;
        $user->email = $request->email;

        if ($request->filled('password')) {
            $user->password = Hash::make($request->password);
        }

        $user->save();

        return redirect()->route('user.profile')->with('success', 'Profil berhasil diperbarui.');
    }
    
    public function updateCustomer(Request $request, $id)
    {
        $customer = User::findOrFail($id);

        $request->validate([
            'email' => 'required|email|unique:users,email,' . $customer->id,
            'password' => 'nullable|min:6|confirmed',
        ]);

        $customer->email = $request->email;

        if ($request->filled('password')) {
            $customer->password = Hash::make($request->password);
        }

        $customer->save();

        return response()->json(['success' => true]);
    }
    public function updateKeterangan(Request $request, $id)
    {
        $booking = Booking::findOrFail($id);
        $booking->keterangan = $request->keterangan;
        $booking->save();
    
        return back()->with('success', 'Keterangan berhasil diperbarui.');
    }

}
