"""
URL configuration for branch_system project.
"""
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
from loans import views as loans_views
from payments import views as payments_views
import os

@login_required
@require_POST
def session_ping(request):
    return JsonResponse({'status': 'ok'})

@login_required
def home_redirect(request):
    return RedirectView.as_view(url='/dashboard/', permanent=False)(request)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='landing.html'), name='landing'),  # Haven Grazuri homepage
    path('app/', home_redirect, name='home'),  # Backend app entry
    path('dashboard/', loans_views.dashboard, name='dashboard'),
    path('api/loan-data/', loans_views.api_loan_data, name='api_loan_data'),
    path('api/recent-activity/', loans_views.api_recent_activity, name='api_recent_activity'),
    path('api/session-ping/', session_ping, name='session_ping'),
    path('loans/', include('loans.urls')),
    path('', include('users.urls')),
    path('reports/', include('reports.urls')),
    path('utils/', include('utils.urls')),
    path('payments/', include('payments.urls')),
    path('expenses/', include('expenses.urls')),
    
    # M-Pesa callback URLs at root level
    path('mpesa/validation/', payments_views.MpesaValidationView.as_view(), name='mpesa_validation_root'),
    path('mpesa/confirmation/', payments_views.MpesaConfirmationView.as_view(), name='mpesa_confirmation_root'),
]

# Media files serving - Enable for production fallback
# Apache should serve media files directly, but Django handles fallback
if settings.DEBUG or True:  # Always serve media files through Django as fallback
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# Serve frontend static files
urlpatterns += static('/css/', document_root=os.path.join(settings.BASE_DIR, 'frontend', 'frontend', 'css'))
urlpatterns += static('/js/', document_root=os.path.join(settings.BASE_DIR, 'frontend', 'frontend', 'js'))
urlpatterns += static('/images/', document_root=os.path.join(settings.BASE_DIR, 'frontend', 'frontend', 'images'))
urlpatterns += static('/fonts/', document_root=os.path.join(settings.BASE_DIR, 'frontend', 'frontend', 'fonts'))

# Customize admin site
admin.site.site_header = "Haven Grazuri Investment Limited - Admin"
admin.site.site_title = "Haven Grazuri Investment Limited"
admin.site.index_title = "Welcome to Haven Grazuri Investment Limited Administration"
