from ._base import *


def promo_code_view(request):
    return render(request, 'account/promo_code.html')
def transfer_d_points_view(request):
    # Renderizar la plantilla para la transferencia de puntos
    return render(request, 'account/transfer_d_points.html')    
def vote_points_view(request):
    # Verificar si el usuario tiene un `username` en la sesión
    username = request.session.get('username')
    if not username:
        return redirect('login')

    # Obtener el `account_id` basado en el `username`
    with connections['acore_auth'].cursor() as cursor:
        cursor.execute("SELECT id FROM account WHERE username = %s", [username])
        account_data = cursor.fetchone()
    
    if not account_data:
        return JsonResponse({'success': False, 'message': 'Cuenta no encontrada.'})

    account_id = account_data[0]

    if request.method == 'POST':
        vote_url = request.POST.get('vote').strip()

        site = VoteSite.objects.filter(url=vote_url).first()
        if not site:
            return JsonResponse({'success': False, 'message': 'Sitio de votación no encontrado.'})

        # Verificar si ya ha votado en las últimas 12 horas y 30 minutos
        last_vote = VoteLog.objects.filter(account_id=account_id, vote_site=site).order_by('-created_at').first()
        now = timezone.now()
        if last_vote:
            time_diff = now - last_vote.created_at
            cooldown_period = timedelta(hours=12, minutes=30)
            
            if time_diff < cooldown_period:
                remaining_time = cooldown_period - time_diff
                hours, remainder = divmod(remaining_time.seconds, 3600)
                minutes, _ = divmod(remainder, 60)
                return JsonResponse({
                    'success': False,
                    'message': f'<span class="red-form-response">Tienes que esperar {hours} horas y {minutes} minutos antes de volver a votar.</span>'
                })

        # Acreditar puntos al usuario y registrar el voto
        user_points = HomeApiPoints.objects.filter(accountID=account_id).first()
        if user_points:
            user_points.vp += site.points
            user_points.save()
        else:
            HomeApiPoints.objects.create(accountID=account_id, vp=site.points, dp=0)

        # Registrar el voto
        VoteLog.objects.create(account_id=account_id, vote_site=site, last_vote_time=now)

        return JsonResponse({'success': True, 'message': f'Has votado en {site.name}. Se han acreditado {site.points} PV.'})

    vote_sites = VoteSite.objects.all()
    return render(request, 'account/vote_points.html', {
        'vote_sites': vote_sites,
        'vote_sites_data': [
            {'name': s.name, 'image_url': s.image_url, 'points': s.points, 'url': s.url}
            for s in vote_sites
        ],
    })
def d_points_view(request):
    """
    Vista para la página de D-Points.
    Simplemente renderiza la plantilla d_points.html.
    """
    return render(request, 'account/d_points.html')
def points_history_view(request):
    return render(request, 'account/points_history.html')
def trans_history_view(request):
    """
    Vista para mostrar el historial de transacciones de la cuenta y sus personajes.
    """
    username = request.session.get('username')  # Obtener el nombre de usuario de la sesión
    
    if username:
        # Filtramos las transacciones que corresponden al usuario y a los personajes asociados
        transactions = StripeLog.objects.filter(username=username)
    else:
        transactions = []
    
    transactions_data = [
        {
            'account_id': t.account_id,
            'username': t.username,
            'character_name': t.character_name,
            'acore_ip': t.acore_ip,
            'email': t.email,
            'product_name': t.product_name,
            'amount': f"{t.amount} €",
            'timestamp': t.timestamp.strftime('%d-%m-%Y %H:%M:%S') if t.timestamp else '',
            'mode': t.mode,
        }
        for t in transactions
    ]

    # Renderizamos la vista con el historial de transacciones
    return render(request, 'account/trans_history.html', {
        'transactions': transactions,
        'transactions_data': transactions_data,
    })
def trade_points_view(request):
    """
    Vista para la página de intercambio de puntos.
    """
    return render(request, 'account/trade_points.html')    
