# sales/views/staff.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 accounts.models import CustomUser

from core.utils import check_limit_or_block, filter_orders_by_user_branch
from accounts.decorators import role_required
from companies.permissions import company_feature_required
from sales.models import (
    POSOrder, POSOrderItem, PaymentTransaction,
    DailySalesSummary, UnusualTransaction, Customer,
)
from sales.forms import POSOrderForm, POSOrderItemForm

logger = logging.getLogger(__name__)


def staff_performance_dashboard(request):
    """
    Show performance metrics per cashier/staff with date and branch filtering.
    """
    today = timezone.now().date()

    # Filters from GET params
    filter_date_str = request.GET.get('date', '')
    filter_branch_id = request.GET.get('branch', '')

    try:
        filter_date = datetime.strptime(filter_date_str, '%Y-%m-%d').date() if filter_date_str else today
    except ValueError:
        filter_date = today

    # Branches for dropdown
    from core.models import Branch
    branches = Branch.objects.filter(company=request.company, is_active=True)

    # Get all cashiers & managers
    staff_qs = CustomUser.objects.filter(company=request.company, role__in=["cashier", "manager", "admin"])

    staff_stats = []

    for user in staff_qs:
        base_filter = dict(cashier=user.username, status="completed")

        # Apply branch filter
        if filter_branch_id:
            base_filter['branch_id'] = filter_branch_id

        all_orders = POSOrder.objects.filter(company=request.company, **base_filter)
        total_orders = all_orders.count()
        total_sales = all_orders.aggregate(total=Sum("final_amount"))["total"] or Decimal("0")

        # Orders on the selected date
        orders_on_date = all_orders.filter(created_at__date=filter_date)
        orders_today_count = orders_on_date.count()
        sales_on_date = orders_on_date.aggregate(total=Sum("final_amount"))["total"] or Decimal("0")

        # Profit per user using POSOrderItem + cost_price
        items = POSOrderItem.objects.filter(order__in=all_orders).select_related("product")
        profit = Decimal("0")
        for item in items:
            selling = item.unit_price or Decimal("0")
            cost = (item.product.cost_price if item.product else Decimal("0")) or Decimal("0")
            qty = item.quantity or 0
            profit += (selling - cost) * qty

        unusual_count = UnusualTransaction.objects.filter(company=request.company, order__in=all_orders).count()

        staff_stats.append({
            "user": user,
            "total_orders": total_orders,
            "total_sales": total_sales,
            "total_profit": profit,
            "unusual_transactions": unusual_count,
            "orders_on_date": orders_today_count,
            "sales_on_date": sales_on_date,
        })

    # Sort by orders on date (highest first)
    staff_stats.sort(key=lambda x: x["orders_on_date"], reverse=True)

    return render(request, "sales/staff_performance.html", {
        "staff_stats": staff_stats,
        "today": today,
        "filter_date": filter_date,
        "filter_branch_id": filter_branch_id,
        "branches": branches,
    })

from decimal import Decimal

from decimal import Decimal

@login_required
@role_required(['admin', 'manager'])
@company_feature_required('feature_suspicious_activity')
def suspicious_activity(request):
    """View flagged suspicious transactions."""
    from accounts.audit import log_action
    log_action(request, 'view_transactions', target='Suspicious Activity Page')

    qs = UnusualTransaction.objects.filter(company=request.company).select_related('order').order_by('-flagged_at')

    # Filters
    resolved_filter = request.GET.get('resolved', '')
    cashier_filter = request.GET.get('cashier', '')
    date_from_str = request.GET.get('date_from', '')
    date_to_str = request.GET.get('date_to', '')

    if resolved_filter == 'yes':
        qs = qs.filter(resolved=True)
    elif resolved_filter == 'no':
        qs = qs.filter(resolved=False)

    if cashier_filter:
        qs = qs.filter(order__cashier__icontains=cashier_filter)

    if date_from_str:
        try:
            qs = qs.filter(flagged_at__date__gte=datetime.strptime(date_from_str, '%Y-%m-%d').date())
        except ValueError:
            pass

    if date_to_str:
        try:
            qs = qs.filter(flagged_at__date__lte=datetime.strptime(date_to_str, '%Y-%m-%d').date())
        except ValueError:
            pass

    # Resolve action
    if request.method == 'POST' and request.POST.get('action') == 'resolve':
        flag_id = request.POST.get('flag_id')
        try:
            flag = UnusualTransaction.objects.get(company=request.company, id=flag_id)
            flag.resolved = True
            flag.resolved_by = request.user.username
            flag.resolved_at = timezone.now()
            flag.save()
            messages.success(request, 'Transaction marked as resolved.')
        except UnusualTransaction.DoesNotExist:
            messages.error(request, 'Flag not found.')
        return redirect('sales:suspicious_activity')

    context = {
        'flags': qs,
        'resolved_filter': resolved_filter,
        'cashier_filter': cashier_filter,
        'date_from': date_from_str,
        'date_to': date_to_str,
        'total_unresolved': UnusualTransaction.objects.filter(company=request.company, resolved=False).count(),
        'user_role': request.user.role,
        'user_name': request.user.get_full_name() or request.user.username,
    }
    return render(request, 'sales/suspicious_activity.html', context)


# ═══════════════════════════════════════════════════════════
#  FEATURE 9: CUSTOMER CRUD
# ═══════════════════════════════════════════════════════════




