<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Locker;
use App\Models\ClientLocation;
use App\Models\Client;

class LockerController extends Controller
{
    /**
     * Display a listing of all lockers.
     */
    public function index(Request $request)
    {
        $query = Locker::with(['location', 'customer']);

        // Search by locker number
        if ($request->filled('search')) {
            $query->where('locker_number', 'like', '%' . $request->search . '%');
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Filter by size
        if ($request->filled('size')) {
            $query->where('locker_size', $request->size);
        }

        // Filter by type
        if ($request->filled('type')) {
            $query->where('locker_type', 'like', '%' . $request->type . '%');
        }

        // Filter by location
        if ($request->filled('location')) {
            $query->where('location_id', $request->location);
        }

        // Get counts for all 5 statuses
        $stats = [
            'total' => Locker::count(),
            'available' => Locker::available()->count(),
            'reserved' => Locker::reserved()->count(),
            'occupied' => Locker::occupied()->count(),
            'maintenance' => Locker::maintenance()->count(),
            'blocked' => Locker::blocked()->count(),
        ];

        $lockers = $query->orderBy('locker_number')->paginate(12);

        return view('lockers.index', compact('lockers', 'stats'));
    }

    /**
     * Display available lockers.
     */
    public function available(Request $request)
    {
        $query = Locker::available()->with(['location', 'customer']);

        // Apply filters
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('locker_number', 'like', "%{$search}%")
                  ->orWhere('locker_type', 'like', "%{$search}%");
        }

        if ($request->filled('size')) {
            $query->where('locker_size', $request->size);
        }

        if ($request->filled('type')) {
            $query->where('locker_type', $request->type);
        }

        if ($request->filled('location')) {
            $query->where('location_id', $request->location);
        }

        // Get counts for all sizes from available lockers
        $sizeStats = [
            'small' => Locker::available()->where('locker_size', 'small')->count(),
            'medium' => Locker::available()->where('locker_size', 'medium')->count(),
            'large' => Locker::available()->where('locker_size', 'large')->count(),
            'extra_large' => Locker::where('locker_size', 'Extra Large')->where('status', 'available')->count(),
        ];

        $lockers = $query->orderBy('locker_number')->paginate(12);

        return view('lockers.available', compact('lockers', 'sizeStats'));
    }

    /**
     * Show the form for creating a new locker.
     */
    public function create()
    {
        $locations = ClientLocation::orderBy('name')->get();
        $customers = Client::orderBy('name')->get();
        
        return view('lockers.create', compact('locations', 'customers'));
    }

    /**
     * Store a newly created locker in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'locker_number' => 'required|string|max:255|unique:lockers,locker_number',
            'locker_size' => 'required|in:small,medium,large,Extra_large',
            'locker_type' => 'required|string|max:255',
            'status' => 'required|in:available,occupied,maintenance',
            'location_id' => 'nullable|exists:client_locations,id',
            'customer_id' => 'nullable|exists:clients,id',
        ]);

        // If status is occupied, customer_id is required
        if ($validated['status'] === 'occupied' && empty($validated['customer_id'])) {
            return back()->withInput()->withErrors([
                'customer_id' => 'Customer is required when locker status is occupied.'
            ]);
        }

        Locker::create($validated);

        return redirect()->route('lockers.index')
            ->with('success', 'Locker created successfully.');
    }

    /**
     * Display the specified locker.
     */
    public function show(Locker $locker)
    {
        $locker->load(['location', 'customer', 'lockerRegistrations']);
        
        return view('lockers.show', compact('locker'));
    }

    /**
     * Show the form for editing the specified locker.
     */
    public function edit(Locker $locker)
    {
        $locations = ClientLocation::orderBy('name')->get();
        $customers = Client::orderBy('name')->get();
        
        return view('lockers.edit', compact('locker', 'locations', 'customers'));
    }

    /**
     * Update the specified locker in storage.
     */
    public function update(Request $request, Locker $locker)
    {
        $validated = $request->validate([
            'locker_number' => 'required|string|max:255|unique:lockers,locker_number,' . $locker->id,
            'locker_size' => 'required|in:small,medium,large,Extra_large',
            'locker_type' => 'required|string|max:255',
            'status' => 'required|in:available,occupied,maintenance',
            'location_id' => 'nullable|exists:client_locations,id',
            'customer_id' => 'nullable|exists:clients,id',
        ]);

        // If status is occupied, customer_id is required
        if ($validated['status'] === 'occupied' && empty($validated['customer_id'])) {
            return back()->withInput()->withErrors([
                'customer_id' => 'Customer is required when locker status is occupied.'
            ]);
        }

        // If status is changing to available, clear customer_id
        if ($validated['status'] === 'available') {
            $validated['customer_id'] = null;
        }

        $locker->update($validated);

        return redirect()->route('lockers.index')
            ->with('success', 'Locker updated successfully.');
    }

    /**
     * Remove the specified locker from storage.
     */
    public function destroy(Locker $locker)
    {
        // Check if locker has active registrations
        if ($locker->lockerRegistrations()->where('status', 'Active')->exists()) {
            return back()->with('error', 'Cannot delete locker with active registrations.');
        }

        $locker->delete();

        return redirect()->route('lockers.index')
            ->with('success', 'Locker deleted successfully.');
    }

    /**
     * Assign a locker to a customer.
     */
    public function assign(Request $request, Locker $locker)
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:clients,id',
            'notes' => 'nullable|string',
        ]);

        // Update locker status and customer
        $locker->update([
            'status' => 'occupied',
            'customer_id' => $validated['customer_id'],
        ]);

        return redirect()->route('lockers.index')
            ->with('success', 'Locker assigned successfully.');
    }

    /**
     * Release a locker from customer.
     */
    public function release(Locker $locker)
    {
        $locker->update([
            'status' => 'available',
            'customer_id' => null,
        ]);

        return redirect()->route('lockers.index')
            ->with('success', 'Locker released successfully.');
    }

    /**
     * API endpoint for search/filter.
     */
    public function apiSearch(Request $request)
    {
        $query = Locker::with(['location', 'customer']);

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('locker_number', 'like', "%{$search}%")
                  ->orWhere('locker_type', 'like', "%{$search}%");
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('size')) {
            $query->where('locker_size', $request->size);
        }

        $lockers = $query->orderBy('locker_number')->paginate(12);

        return response()->json($lockers);
    }
}
