<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GymClass;
use App\Models\Trainer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\DB;

class GymClassController extends Controller
{


    
    /**
     * Display the classes management page
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
{
    try {
        \Log::info('Attempting to load classes index');
    try {
        return view('admin.pages.classes');
    } catch (\Exception $e) {
        \Log::error('Classes index error: '.$e->getMessage());
        \Log::error($e->getTraceAsString());
        return response()->view('errors.500', [], 500);
    }
        // Check if admin is authenticated
        if (!auth()->guard('admin')->check()) {
            return redirect()->route('admin.login');
        }

        // Get data needed for the view
        $upcomingClasses = GymClass::where('status', 'active')
            ->whereDate('schedule->date', '>=', now()->toDateString())
            ->orderBy('schedule->date')
            ->with('trainer:id,first_name,last_name')
            ->limit(5)
            ->get();

        return view('admin.pages.classes', [
            'upcomingClasses' => $upcomingClasses
        ]);

    } catch (\Exception $e) {
        Log::error('Error accessing classes index page: ' . $e->getMessage());
        return response()->view('errors.500', [], 500);
    }
}

    /**
     * Get classes for DataTables
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        try {
            if ($request->ajax()) {
        $classes = GymClass::with('trainer')->select();
        return datatables()->of($classes)->toJson();
    }
    abort(404);

            Log::info('Fetching classes for DataTables');

            $query = GymClass::with(['trainer' => function($query) {
                $query->select('id', 'first_name', 'last_name');
            }])->latest();

            return DataTables::eloquent($query)
                ->addIndexColumn()
                ->addColumn('trainer', function($row) {
                    return $row->trainer ? $row->trainer->full_name : 'N/A';
                })
                ->addColumn('schedule', function($row) {
                    try {
                        $schedule = json_decode($row->schedule, true);
                        $days = $schedule['day_of_week'] ?? '';
                        $formattedDays = $days ? implode(', ', array_map(function($day) {
                            return trim(substr($day, 0, 3));
                        }, explode(',', $days))) : '';
                        
                        return $formattedDays . ' ' . ($schedule['time'] ?? '');
                    } catch (\Exception $e) {
                        Log::error("Error parsing schedule for class {$row->id}: " . $e->getMessage());
                        return 'Schedule error';
                    }
                })
                ->addColumn('capacity', function($row) {
                    return ($row->current_attendees ?? 0) . ' / ' . $row->max_capacity;
                })
                ->addColumn('status', function($row) {
                    $badgeClass = [
                        'active' => 'bg-success',
                        'cancelled' => 'bg-danger',
                        'completed' => 'bg-secondary'
                    ][$row->status] ?? 'bg-info';
                    
                    return '<span class="badge ' . $badgeClass . '">' . ucfirst($row->status) . '</span>';
                })
                ->addColumn('action', function($row) {
                    return '
                        <div class="d-flex gap-2">
                            <button class="btn btn-sm btn-info view-class" data-id="' . $row->id . '" title="View">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-primary edit-class" data-id="' . $row->id . '" title="Edit">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger delete-class" data-id="' . $row->id . '" title="Delete">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    ';
                })
                ->rawColumns(['status', 'action'])
                ->make(true);

        } catch (\Exception $e) {
            Log::error('Error in classes list method: ' . $e->getMessage());
            return response()->json(['error' => 'Server error'], 500);
        }
    }

    /**
     * Get trainers for class creation form
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function create()
    {
        try {
            $trainers = Trainer::where('status', 'active')
                ->select('id', 'first_name', 'last_name')
                ->get()
                ->map(function($trainer) {
                    $trainer->full_name = $trainer->first_name . ' ' . $trainer->last_name;
                    return $trainer;
                });

            Log::info('Fetched active trainers for class creation');
            return response()->json($trainers);

        } catch (\Exception $e) {
            Log::error('Error fetching trainers: ' . $e->getMessage());
            return response()->json(['error' => 'Failed to load trainers'], 500);
        }
    }

    /**
     * Store a newly created class
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'description' => 'nullable|string',
                'trainer_id' => 'required|exists:trainers,id',
                'class_date' => 'required|date|after_or_equal:today',
                'class_time' => 'required|date_format:H:i',
                'duration_minutes' => 'required|integer|min:15|max:240',
                'max_capacity' => 'required|integer|min:1|max:50',
            ]);

            $schedule = [
                'day_of_week' => date('l', strtotime($validated['class_date'])),
                'date' => $validated['class_date'],
                'time' => $validated['class_time']
            ];

            $class = GymClass::create([
                'name' => $validated['name'],
                'description' => $validated['description'],
                'trainer_id' => $validated['trainer_id'],
                'schedule' => json_encode($schedule),
                'duration_minutes' => $validated['duration_minutes'],
                'max_capacity' => $validated['max_capacity'],
                'status' => 'active',
                'current_attendees' => 0
            ]);

            DB::commit();
            Log::info("Created new class: {$class->id} - {$class->name}");

            return response()->json([
                'success' => true,
                'message' => 'Class created successfully',
                'data' => $class
            ]);

        } catch (\Illuminate\Validation\ValidationException $e) {
            DB::rollBack();
            Log::warning('Class creation validation failed: ' . json_encode($request->all()));
            return response()->json([
                'success' => false,
                'errors' => $e->errors()
            ], 422);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error creating class: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to create class'
            ], 500);
        }
    }

    /**
     * Display the specified class
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        try {
            $class = GymClass::with(['trainer' => function($query) {
                $query->select('id', 'first_name', 'last_name', 'specialization');
            }])->findOrFail($id);

            Log::info("Fetched class details for class ID: {$id}");
            return response()->json([
                'success' => true,
                'data' => $class
            ]);

        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            Log::warning("Class not found: {$id}");
            return response()->json([
                'success' => false,
                'message' => 'Class not found'
            ], 404);

        } catch (\Exception $e) {
            Log::error("Error fetching class {$id}: " . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch class details'
            ], 500);
        }
    }

    /**
     * Show the form for editing the specified class
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit($id)
    {
        try {
            $class = GymClass::findOrFail($id);
            $trainers = Trainer::where('status', 'active')
                ->select('id', 'first_name', 'last_name')
                ->get();

            Log::info("Fetched class for editing: {$id}");
            return response()->json([
                'success' => true,
                'class' => $class,
                'trainers' => $trainers
            ]);

        } catch (\Exception $e) {
            Log::error("Error fetching class for edit {$id}: " . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to load class data'
            ], 500);
        }
    }

    /**
     * Update the specified class
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        DB::beginTransaction();
        try {
            $class = GymClass::findOrFail($id);

            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'description' => 'nullable|string',
                'trainer_id' => 'required|exists:trainers,id',
                'class_date' => 'required|date',
                'class_time' => 'required|date_format:H:i',
                'duration_minutes' => 'required|integer|min:15|max:240',
                'max_capacity' => 'required|integer|min:1|max:50',
                'status' => 'required|in:active,cancelled,completed'
            ]);

            $schedule = [
                'day_of_week' => date('l', strtotime($validated['class_date'])),
                'date' => $validated['class_date'],
                'time' => $validated['class_time']
            ];

            $class->update([
                'name' => $validated['name'],
                'description' => $validated['description'],
                'trainer_id' => $validated['trainer_id'],
                'schedule' => json_encode($schedule),
                'duration_minutes' => $validated['duration_minutes'],
                'max_capacity' => $validated['max_capacity'],
                'status' => $validated['status']
            ]);

            DB::commit();
            Log::info("Updated class: {$id}");

            return response()->json([
                'success' => true,
                'message' => 'Class updated successfully',
                'data' => $class
            ]);

        } catch (\Illuminate\Validation\ValidationException $e) {
            DB::rollBack();
            Log::warning("Class update validation failed for {$id}: " . json_encode($request->all()));
            return response()->json([
                'success' => false,
                'errors' => $e->errors()
            ], 422);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("Error updating class {$id}: " . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to update class'
            ], 500);
        }
    }

    /**
     * Remove the specified class
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            $class = GymClass::findOrFail($id);
            $class->delete();

            DB::commit();
            Log::info("Deleted class: {$id}");

            return response()->json([
                'success' => true,
                'message' => 'Class deleted successfully'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("Error deleting class {$id}: " . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete class'
            ], 500);
        }
    }

    /**
     * Get upcoming classes
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function upcomingClasses()
    {
        try {
            $classes = GymClass::where('status', 'active')
                ->whereDate('schedule->date', '>=', now()->toDateString())
                ->orderBy('schedule->date')
                ->with('trainer:id,first_name,last_name')
                ->limit(5)
                ->get();

            Log::info('Fetched upcoming classes');
            return response()->json($classes);

        } catch (\Exception $e) {
            Log::error('Error fetching upcoming classes: ' . $e->getMessage());
            return response()->json([], 500);
        }
    }

    /**
     * Get class statistics
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function stats()
    {
        try {
            $stats = [
                'total_classes' => GymClass::count(),
                'active_classes' => GymClass::where('status', 'active')->count(),
                'average_attendance' => GymClass::where('status', 'completed')
                    ->avg(DB::raw('(current_attendees/max_capacity)*100'))
            ];

            Log::info('Fetched class statistics');
            return response()->json($stats);

        } catch (\Exception $e) {
            Log::error('Error fetching class stats: ' . $e->getMessage());
            return response()->json([
                'error' => 'Failed to load statistics'
            ], 500);
        }
    }
}