<?php

namespace App\Http\Controllers;

use App\Models\Equipment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;

class EquipmentController extends Controller
{
    /**
     * Display a listing of the equipment.
     */
    public function index(Request $request)
    {
        $query = Equipment::ordered();

        // Filter by type
        if ($request->has('type') && in_array($request->type, array_keys(Equipment::getTypes()))) {
            $query->ofType($request->type);
        }

        // Filter by status
        if ($request->has('status')) {
            if ($request->status === 'active') {
                $query->active();
            } elseif ($request->status === 'inactive') {
                $query->where('is_active', false);
            }
        }

        // Search by name or description
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        $equipment = $query->paginate(10);
        $types = Equipment::getTypes();

        return view('equipment.index', compact('equipment', 'types'));
    }

    /**
     * Show the form for creating a new equipment.
     */
    public function create()
    {
        $types = Equipment::getTypes();
        return view('equipment.create', compact('types'));
    }

    /**
     * Store a newly created equipment in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'type' => 'required|in:' . implode(',', array_keys(Equipment::getTypes())),
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'is_active' => 'boolean',
            'sort_order' => 'nullable|integer|min:0',
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i|after:start_time',
            'slot_duration' => 'required|integer|min:15|max:120',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $data = $validator->validated();
        $data['is_active'] = $request->has('is_active');
        $data['sort_order'] = $data['sort_order'] ?? 0;

        // Handle image upload
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('equipment', 'public');
            $data['image'] = $imagePath;
        }

        Equipment::create($data);

        return redirect()->route('equipment.index')
            ->with('success', 'Equipment created successfully.');
    }

    /**
     * Display the specified equipment.
     */
    public function show(Equipment $equipment)
    {
        $equipment->load('reservations.user');
        return view('equipment.show', compact('equipment'));
    }

    /**
     * Show the form for editing the specified equipment.
     */
    public function edit(Equipment $equipment)
    {
        $types = Equipment::getTypes();
        return view('equipment.edit', compact('equipment', 'types'));
    }

    /**
     * Update the specified equipment in storage.
     */
    public function update(Request $request, Equipment $equipment)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'type' => 'required|in:' . implode(',', array_keys(Equipment::getTypes())),
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'is_active' => 'boolean',
            'sort_order' => 'nullable|integer|min:0',
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i|after:start_time',
            'slot_duration' => 'required|integer|min:15|max:120',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $data = $validator->validated();
        $data['is_active'] = $request->has('is_active');
        $data['sort_order'] = $data['sort_order'] ?? 0;

        // Handle image upload
        if ($request->hasFile('image')) {
            // Delete old image if exists
            if ($equipment->image) {
                Storage::disk('public')->delete($equipment->image);
            }
            
            $imagePath = $request->file('image')->store('equipment', 'public');
            $data['image'] = $imagePath;
        }

        $equipment->update($data);

        return redirect()->route('equipment.index')
            ->with('success', 'Equipment updated successfully.');
    }

    /**
     * Remove the specified equipment from storage.
     */
    public function destroy(Equipment $equipment)
    {
        // Check if equipment has active reservations
        $activeReservations = $equipment->reservations()
            ->where('status', 'confirmed')
            ->where('reservation_date', '>=', now()->toDateString())
            ->count();

        if ($activeReservations > 0) {
            return redirect()->back()
                ->with('error', 'Cannot delete equipment with active reservations.');
        }

        // Delete image if exists
        if ($equipment->image) {
            Storage::disk('public')->delete($equipment->image);
        }

        $equipment->delete();

        return redirect()->route('equipment.index')
            ->with('success', 'Equipment deleted successfully.');
    }

    /**
     * Toggle the active status of the equipment.
     */
    public function toggleActive(Equipment $equipment)
    {
        $equipment->update(['is_active' => !$equipment->is_active]);

        $status = $equipment->is_active ? 'activated' : 'deactivated';
        return redirect()->back()
            ->with('success', "Equipment {$status} successfully.");
    }

    /**
     * Get time slots for a specific date.
     */
    public function getTimeSlots(Request $request, Equipment $equipment)
    {
        $request->validate([
            'date' => 'required|date|after_or_equal:today',
        ]);

        $date = $request->date;
        
        // Additional check to ensure the date is not in the past
        # update this to check if the date not current date
        $currentDate = Carbon::now()->toDateString();
        if (Carbon::parse($date)->startOfDay()->isPast() && $date != $currentDate) {
            return response()->json([
                'success' => false,
                'message' => 'Cannot retrieve time slots for past dates.',
                'data' => [
                    'equipment' => $equipment->toApiArray(),
                    'date' => $date,
                    'available_slots' => [],
                    'total_available' => 0,
                ]
            ], 400);
        }
        
        $availableSlots = $equipment->getAvailableSlotsForDate($date);

        return response()->json([
            'success' => true,
            'data' => [
                'equipment' => $equipment->toApiArray(),
                'date' => $date,
                'available_slots' => $availableSlots,
                'total_available' => count($availableSlots),
            ],
            'message' => 'Available time slots retrieved successfully'
        ]);
    }

    /**
     * Get equipment statistics.
     */
    public function statistics()
    {
        $stats = [
            'total' => Equipment::count(),
            'active' => Equipment::active()->count(),
            'by_type' => [],
            'total_reservations' => 0,
            'today_reservations' => 0,
            'upcoming_reservations' => 0,
        ];

        // Get count by type
        foreach (Equipment::getTypes() as $type => $name) {
            $equipment = Equipment::ofType($type);
            $stats['by_type'][$type] = [
                'name' => $name,
                'total' => $equipment->count(),
                'active' => $equipment->active()->count(),
            ];
        }

        // Get reservation statistics
        $stats['total_reservations'] = \App\Models\EquipmentReservation::count();
        $stats['today_reservations'] = \App\Models\EquipmentReservation::forDate(now()->toDateString())->count();
        $stats['upcoming_reservations'] = \App\Models\EquipmentReservation::where('reservation_date', '>', now()->toDateString())->count();

        return view('equipment.statistics', compact('stats'));
    }
}
