# sales/views/customers.py
import logging
import json
import csv
import string
from datetime import datetime, timedelta
from decimal import Decimal

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from django.db import transaction
from django.db.models import Sum, Count, Q, F
from django.core.exceptions import PermissionDenied

from inventory.models import Product
from core.models import Branch
from core.utils import check_limit_or_block, filter_orders_by_user_branch
from accounts.decorators import role_required, perm_required
from sales.models import (
    POSOrder, POSOrderItem, PaymentTransaction,
    DailySalesSummary, UnusualTransaction, Customer,
)
from sales.forms import POSOrderForm, POSOrderItemForm

logger = logging.getLogger(__name__)


@login_required
@perm_required('can_view_credit_sales')
def credit_customers(request):
    company = getattr(request, 'company', None)
    q = request.GET.get("q", "").strip()

    credit_orders = POSOrder.objects.filter(
        Q(payment_status__iexact='credit') |
        Q(balance_amount__gt=0)
    ).order_by('-created_at')
    if company:
        credit_orders = credit_orders.filter(company=company)

    if q:
        credit_orders = credit_orders.filter(
            Q(customer_name__icontains=q) |
            Q(customer_phone__icontains=q)
        )

    return render(request, 'sales/credit_customers.html', {
        'credit_orders': credit_orders,
        'user_role': request.user.role,
        'user_name': request.user.get_full_name() or request.user.username,
    })



from accounts.models import CustomUser
from decimal import Decimal
from django.db.models import F


@login_required
@role_required(['admin'])

def clear_credit(request, order_id):
    order = get_object_or_404(POSOrder, id=order_id, company=request.company)

    if request.method == "POST":
        amount = request.POST.get("amount")

        try:
            amount = Decimal(amount)
        except:
            messages.error(request, "Invalid amount")
            return redirect(request.META.get("HTTP_REFERER", "/"))

        order.clear_credit(amount)
        messages.success(request, "Customer credit cleared successfully.")
        return redirect("sales:credit_customers")

    return render(request, "sales/clear_credit.html", {"order": order})


# ═══════════════════════════════════════════════════════════
#  FEATURE 2: P&L REPORT
# ═══════════════════════════════════════════════════════════

@login_required
@perm_required('can_view_customers')
def customer_list(request):
      # Customer already imported via sales.models
    from django.db.models import Sum, Count, Q
    company = getattr(request, 'company', None)

    q   = request.GET.get('q', '').strip()
    tab = request.GET.get('tab', 'all')  # all | credit | history

    # ── All registered customers ──────────────────────────────────────
    customers = Customer.objects.all()
    if company:
        customers = customers.filter(company=company)
    if q:
        customers = customers.filter(
            Q(name__icontains=q) | Q(phone__icontains=q) | Q(email__icontains=q)
        )

    # ── Customers with pending credit (from POSOrder) ─────────────────
    credit_orders = POSOrder.objects.filter(
        Q(payment_status='credit') | Q(payment_status='partial') | Q(balance_amount__gt=0)
    ).order_by('-created_at')
    if company:
        credit_orders = credit_orders.filter(company=company)
    if q:
        credit_orders = credit_orders.filter(
            Q(customer_name__icontains=q) | Q(customer_phone__icontains=q)
        )

    # Group credit by customer name for summary
    credit_summary = credit_orders.values('customer_name', 'customer_phone').annotate(
        total_owed=Sum('balance_amount'),
        orders_count=Count('id')
    ).order_by('-total_owed')

    # ── Payment history (fully paid credit orders) ─────────────────────
    payment_history = POSOrder.objects.filter(
        payment_status='full',
        amount_paid__gt=0,
    ).exclude(customer_name='').order_by('-updated_at')
    
    if company:
        payment_history = payment_history.filter(company=company)
        
    if q:
        payment_history = payment_history.filter(
            Q(customer_name__icontains=q) | Q(customer_phone__icontains=q)
        )

    # Summary stats for header
    total_outstanding_qs = POSOrder.objects.filter(balance_amount__gt=0)
    if company:
        total_outstanding_qs = total_outstanding_qs.filter(company=company)
    total_outstanding = total_outstanding_qs.aggregate(total=Sum('balance_amount'))['total'] or 0
    total_credit_customers = credit_orders.values('customer_name').distinct().count()

    return render(request, 'sales/customer_list.html', {
        'customers':          customers,
        'credit_summary':     credit_summary,
        'credit_orders':      credit_orders[:100],
        'payment_history':    payment_history[:100],
        'tab':                tab,
        'q':                  q,
        'total_outstanding':  total_outstanding,
        'total_credit_customers': total_credit_customers,
        'user_role': request.user.role,
        'user_name': request.user.get_full_name() or request.user.username,
    })


@login_required
@perm_required('can_manage_customers')
def customer_create(request):
      # Customer already imported via sales.models
    from core.utils import check_limit_or_block
    from django.core.exceptions import PermissionDenied
    from accounts.audit import log_action
    from core.email_utils import send_credit_customer_alert

    if request.method == 'POST':
        try:
            check_limit_or_block('customers', request=request)
        except PermissionDenied as e:
            messages.error(request, str(e))
            return redirect('sales:customer_list')

        name = request.POST.get('name', '').strip()
        phone = request.POST.get('phone', '').strip()
        email = request.POST.get('email', '').strip()
        address = request.POST.get('address', '').strip()
        notes = request.POST.get('notes', '').strip()

        if not name:
            messages.error(request, 'Customer name is required.')
            return render(request, 'sales/customer_form.html', {
                'mode': 'create', 'user_role': request.user.role,
                'user_name': request.user.get_full_name() or request.user.username,
            })

        customer = Customer.objects.create(
            company=getattr(request, 'company', None),
            name=name, phone=phone, email=email,
            address=address, notes=notes,
            created_by=request.user.username
        )
        log_action(request, 'add_customer', target=f'Customer: {customer.name}')
        messages.success(request, f'Customer "{name}" added successfully.')
        return redirect('sales:customer_list')

    return render(request, 'sales/customer_form.html', {
        'mode': 'create',
        'user_role': request.user.role,
        'user_name': request.user.get_full_name() or request.user.username,
    })


@login_required
@perm_required('can_manage_customers')
def customer_edit(request, pk):
      # Customer already imported via sales.models
    from accounts.audit import log_action

    customer = get_object_or_404(Customer, pk=pk, company=request.company)

    if request.method == 'POST':
        customer.name = request.POST.get('name', customer.name).strip()
        customer.phone = request.POST.get('phone', customer.phone).strip()
        customer.email = request.POST.get('email', customer.email).strip()
        customer.address = request.POST.get('address', customer.address).strip()
        customer.notes = request.POST.get('notes', customer.notes).strip()
        customer.save()
        log_action(request, 'edit_customer', target=f'Customer: {customer.name}')
        messages.success(request, 'Customer updated.')
        return redirect('sales:customer_list')

    return render(request, 'sales/customer_form.html', {
        'mode': 'edit', 'customer': customer,
        'user_role': request.user.role,
        'user_name': request.user.get_full_name() or request.user.username,
    })


@login_required
@role_required(['admin'])

def customer_delete(request, pk):
      # Customer already imported via sales.models
    from accounts.audit import log_action

    customer = get_object_or_404(Customer, pk=pk, company=request.company)
    if request.method == 'POST':
        name = customer.name
        customer.delete()
        log_action(request, 'delete_customer', target=f'Customer: {name}')
        messages.success(request, f'Customer "{name}" deleted.')
        return redirect('sales:customer_list')
    return redirect('sales:customer_list')


# ═══════════════════════════════════════════════════════════
#  FEATURE 10: BARCODE POS PAGE
# ═══════════════════════════════════════════════════════════

@login_required

def customer_detail(request, pk):
    """View full profile for a registered Customer."""
      # Customer already imported via sales.models
    from django.db.models import Sum

    company = getattr(request, 'company', None)
    cs = getattr(company, 'settings', None)
    currency_symbol = cs.currency_symbol if cs else '₦'

    customer = get_object_or_404(Customer, pk=pk, company=request.company)
    orders = customer.orders.order_by('-created_at')
    if company:
        orders = orders.filter(company=company)
    credit_orders = orders.filter(balance_amount__gt=0)

    context = {
        'customer': customer,
        'orders': orders,
        'credit_orders': credit_orders,
        'currency_symbol': currency_symbol,
    }
    return render(request, 'sales/customer_detail.html', context)



