<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ServiceBooking;
use Illuminate\Http\Request;

class BookingsController extends Controller
{
    public function index(Request $request)
    {
        global $conn;
        $sql = "SELECT * FROM service_bookings WHERE 1=1";
        $params = [];
        
        if ($request->filled('status')) {
            $sql .= " AND status = ?";
            $params[] = $request->status;
        }
        
        if ($request->filled('search')) {
            $s = "%" . $request->search . "%";
            $sql .= " AND (customer_name LIKE ? OR customer_email LIKE ?)";
            $params[] = $s;
            $params[] = $s;
        }
        
        $sql .= " ORDER BY created_at DESC";
        
        $stmt = $conn->prepare($sql);
        $stmt->execute($params);
        $bookings_raw = $stmt->fetchAll();
        $bookings = array_map(fn($item) => (object)$item, $bookings_raw);
        
        return view('admin.bookings.index', compact('bookings'));
    }

    public function show($id)
    {
        global $conn;
        $stmt = $conn->prepare("SELECT * FROM service_bookings WHERE id = ? LIMIT 1");
        $stmt->execute([$id]);
        $booking = (object)$stmt->fetch();
        
        if (!$booking || !isset($booking->id)) abort(404);
        
        return view('admin.bookings.show', compact('booking'));
    }

    public function updateStatus(Request $request, $id)
    {
        global $conn;
        $request->validate(['status' => 'required|in:pending,confirmed,completed,cancelled']);
        
        $upd = $conn->prepare("UPDATE service_bookings SET status = ? WHERE id = ?");
        $upd->execute([$request->status, $id]);
        
        return back()->with('success', 'Booking status updated.');
    }

    public function destroy($id)
    {
        global $conn;
        $del = $conn->prepare("DELETE FROM service_bookings WHERE id = ?");
        $del->execute([$id]);
        
        return redirect()->route('admin.bookings.index')->with('success', 'Booking deleted.');
    }
}
