from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Course
from .forms import CourseForm

def course_list(request):
    courses = Course.objects.all()
    return render(request, 'courses/course_list.html', {'courses': courses})

def course_detail(request, pk):
    course = get_object_or_404(Course, pk=pk)
    return render(request, 'courses/course_detail.html', {'course': course})

@login_required
def create_course(request):
    if not hasattr(request.user, 'instructor'):
        messages.error(request, 'У вас нет прав для создания курсов.')
        return redirect('courses:list')
    
    if request.method == 'POST':
        form = CourseForm(request.POST)
        if form.is_valid():
            course = form.save(commit=False)
            course.instructor = request.user
            course.save()
            messages.success(request, 'Курс успешно создан.')
            return redirect('courses:list')
    else:
        form = CourseForm()
    
    return render(request, 'courses/course_form.html', {'form': form, 'action': 'create'})

@login_required
def update_course(request, pk):
    course = get_object_or_404(Course, pk=pk)
    
    if not hasattr(request.user, 'instructor') or course.instructor != request.user:
        messages.error(request, 'У вас нет прав для редактирования этого курса.')
        return redirect('courses:list')
    
    if request.method == 'POST':
        form = CourseForm(request.POST, instance=course)
        if form.is_valid():
            form.save()
            messages.success(request, 'Курс успешно обновлен.')
            return redirect('courses:list')
    else:
        form = CourseForm(instance=course)
    
    return render(request, 'courses/course_form.html', {'form': form, 'action': 'update'})

@login_required
def delete_course(request, pk):
    course = get_object_or_404(Course, pk=pk)
    
    if not hasattr(request.user, 'instructor') or course.instructor != request.user:
        messages.error(request, 'У вас нет прав для удаления этого курса.')
        return redirect('courses:list')
    
    if request.method == 'POST':
        course.delete()
        messages.success(request, 'Курс успешно удален.')
        return redirect('courses:list')
    
    return render(request, 'courses/course_confirm_delete.html', {'course': course}) 