<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$userId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Get search and filter parameters
$searchTerm = isset($_GET['search']) ? mysqli_real_escape_string($con, $_GET['search']) : '';
$filterType = isset($_GET['type']) ? mysqli_real_escape_string($con, $_GET['type']) : '';
$dateFrom = isset($_GET['date_from']) ? mysqli_real_escape_string($con, $_GET['date_from']) : '';
$dateTo = isset($_GET['date_to']) ? mysqli_real_escape_string($con, $_GET['date_to']) : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$outstandingOnly = isset($_GET['outstanding_only']) && $_GET['outstanding_only'] == '1';
$recordsPerPage = 15;
$offset = ($page - 1) * $recordsPerPage;

// Build where clause
$whereClause = "WHERE c.IsActive = 1";
$paymentWhere = "WHERE p.IsActive = 1";
if (!empty($searchTerm)) {
    $whereClause .= " AND (c.CustomerName LIKE '%$searchTerm%' OR c.Area LIKE '%$searchTerm%')";
}
if (!empty($filterType)) {
    $whereClause .= " AND c.CustomerType = '$filterType'";
}
if (!empty($dateFrom)) {
    $paymentWhere .= " AND p.TransactionDate >= '$dateFrom'";
}
if (!empty($dateTo)) {
    $paymentWhere .= " AND p.TransactionDate <= '$dateTo'";
}

// Calculate outstanding amounts and fetch customer data
$customersQuery = "SELECT 
    c.ID,
    c.CustomerName,
    c.Area,
    c.CustomerType,
    c.Mobile,
    c.AlternativePhone,
    COALESCE(SUM(CASE WHEN p.TransactionType = 'Credit' THEN p.Amount ELSE 0 END), 0) as TotalCredit,
    COALESCE(SUM(CASE WHEN p.TransactionType = 'Debit' THEN p.Amount ELSE 0 END), 0) as TotalDebit,
    (COALESCE(SUM(CASE WHEN p.TransactionType = 'Debit' THEN p.Amount ELSE 0 END), 0) - 
     COALESCE(SUM(CASE WHEN p.TransactionType = 'Credit' THEN p.Amount ELSE 0 END), 0)) as OutstandingAmount
FROM tblcustomers c
LEFT JOIN tblcustomerpayments p ON c.ID = p.CustomerID AND p.IsActive = 1" . 
    (!empty($dateFrom) || !empty($dateTo) ? " AND " . substr($paymentWhere, 6) : "") . "
$whereClause
GROUP BY c.ID, c.CustomerName, c.Area, c.CustomerType, c.Mobile, c.AlternativePhone
" . ($outstandingOnly ? "HAVING OutstandingAmount > 0\n" : "") . "
ORDER BY OutstandingAmount DESC, c.CustomerName ASC
LIMIT $offset, $recordsPerPage";

$customersResult = mysqli_query($con, $customersQuery);

// Count total records for pagination
$countQuery = "SELECT COUNT(*) as total FROM (
                SELECT c.ID,
                    (COALESCE(SUM(CASE WHEN p.TransactionType = 'Debit' THEN p.Amount ELSE 0 END), 0) - 
                     COALESCE(SUM(CASE WHEN p.TransactionType = 'Credit' THEN p.Amount ELSE 0 END), 0)) as OutstandingAmount
                FROM tblcustomers c
                LEFT JOIN tblcustomerpayments p ON c.ID = p.CustomerID AND p.IsActive = 1" . 
    (!empty($dateFrom) || !empty($dateTo) ? " AND " . substr($paymentWhere, 6) : "") . "
                $whereClause
                GROUP BY c.ID
                " . ($outstandingOnly ? "HAVING OutstandingAmount > 0" : "") . "
              ) x";
$countResult = mysqli_query($con, $countQuery);
$totalRecords = mysqli_fetch_assoc($countResult)['total'];
$totalPages = ceil($totalRecords / $recordsPerPage);

// Get summary statistics including outstanding customers count
$summaryQuery = "SELECT 
    COUNT(DISTINCT c.ID) as TotalCustomers,
    COUNT(DISTINCT CASE WHEN c.CustomerType = 'Retail' THEN c.ID END) as RetailCustomers,
    COUNT(DISTINCT CASE WHEN c.CustomerType = 'Shop' THEN c.ID END) as ShopCustomers,
    SUM(CASE WHEN p.TransactionType = 'Debit' THEN p.Amount ELSE 0 END) as TotalDebit,
    SUM(CASE WHEN p.TransactionType = 'Credit' THEN p.Amount ELSE 0 END) as TotalCredit,
    (SUM(CASE WHEN p.TransactionType = 'Debit' THEN p.Amount ELSE 0 END) - 
     SUM(CASE WHEN p.TransactionType = 'Credit' THEN p.Amount ELSE 0 END)) as TotalOutstanding
FROM tblcustomers c
LEFT JOIN tblcustomerpayments p ON c.ID = p.CustomerID AND p.IsActive = 1" . 
    (!empty($dateFrom) || !empty($dateTo) ? " AND " . substr($paymentWhere, 6) : "") . "
WHERE c.IsActive = 1";

// Get count of customers with outstanding amounts
$outstandingCustomersQuery = "SELECT COUNT(*) as OutstandingCustomers FROM (
    SELECT c.ID,
        (COALESCE(SUM(CASE WHEN p.TransactionType = 'Debit' THEN p.Amount ELSE 0 END), 0) - 
         COALESCE(SUM(CASE WHEN p.TransactionType = 'Credit' THEN p.Amount ELSE 0 END), 0)) as OutstandingAmount
    FROM tblcustomers c
    LEFT JOIN tblcustomerpayments p ON c.ID = p.CustomerID AND p.IsActive = 1" . 
        (!empty($dateFrom) || !empty($dateTo) ? " AND " . substr($paymentWhere, 6) : "") . "
    WHERE c.IsActive = 1
    GROUP BY c.ID
    HAVING OutstandingAmount > 0
) x";

$summaryResult = mysqli_query($con, $summaryQuery);
$summary = mysqli_fetch_assoc($summaryResult);

$outstandingCustomersResult = mysqli_query($con, $outstandingCustomersQuery);
$outstandingCustomersData = mysqli_fetch_assoc($outstandingCustomersResult);
$summary['OutstandingCustomers'] = $outstandingCustomersData['OutstandingCustomers'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Customer Outstanding Report</title>
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <style>
        * { 
            box-sizing: border-box; 
            -webkit-tap-highlight-color: transparent; 
        }
        
        body { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: #1a1a1a; 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; 
            margin: 0; 
            padding: 0; 
            min-height: 100vh;
            line-height: 1.5;
        }
        
        .header { 
            background: rgba(255, 255, 255, 0.95); 
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            color: #1a1a1a; 
            padding: 16px 20px; 
            display: flex; 
            align-items: center; 
            gap: 16px; 
            box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        .back-btn { 
            background: rgba(103, 126, 234, 0.1); 
            border: none; 
            color: #667eea; 
            font-size: 20px; 
            cursor: pointer; 
            width: 40px; 
            height: 40px; 
            border-radius: 12px; 
            display: flex; 
            align-items: center; 
            justify-content: center;
            transition: all 0.2s ease;
            text-decoration: none;
        }
        
        .back-btn:hover {
            background: rgba(103, 126, 234, 0.2);
            transform: scale(1.05);
            color: #667eea;
            text-decoration: none;
        }
        
        .dashboard-btn { 
            background: rgba(103, 126, 234, 0.1); 
            border: none; 
            color: #667eea; 
            font-size: 18px; 
            cursor: pointer; 
            width: 40px; 
            height: 40px; 
            border-radius: 12px; 
            display: flex; 
            align-items: center; 
            justify-content: center;
            transition: all 0.2s ease;
            margin-left: 8px;
            text-decoration: none;
        }
        
        .dashboard-btn:hover {
            background: rgba(103, 126, 234, 0.2);
            transform: scale(1.05);
            color: #667eea;
            text-decoration: none;
        }
        
        .title { 
            font-size: 22px; 
            margin: 0; 
            font-weight: 700; 
            color: #1a1a1a;
        }
        
        .export-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: #fff; 
            border: none; 
            padding: 10px 16px; 
            border-radius: 8px; 
            font-size: 13px; 
            font-weight: 600; 
            cursor: pointer; 
            transition: all 0.2s ease;
            box-shadow: 0 4px 12px rgba(103, 126, 234, 0.3);
            margin-left: auto;
            flex-shrink: 0;
        }
        
        .export-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(103, 126, 234, 0.4);
        }
        
        .container { 
            max-width: 1200px; 
            margin: 0 auto; 
            padding: 20px 16px; 
        }
        
        .card { 
            background: rgba(255, 255, 255, 0.95); 
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.2); 
            border-radius: 16px; 
            overflow: hidden; 
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); 
            margin-bottom: 20px;
            transition: transform 0.2s ease;
        }
        
        .card:hover {
            transform: translateY(-2px);
        }
        
        .card h3 { 
            font-size: 16px; 
            margin: 0; 
            padding: 16px 20px; 
            border-bottom: 1px solid rgba(0, 0, 0, 0.06); 
            font-weight: 700;
            color: #1a1a1a;
        }
        
        .summary { 
            padding: 16px 20px; 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); 
            gap: 12px; 
        }
        
        .pill { 
            background: linear-gradient(135deg, rgba(103, 126, 234, 0.08) 0%, rgba(118, 75, 162, 0.08) 100%); 
            padding: 12px; 
            border-radius: 10px; 
            font-size: 12px; 
            font-weight: 600; 
            border: 1px solid rgba(103, 126, 234, 0.1);
            text-align: center;
            transition: all 0.2s ease;
        }
        
        .pill:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(103, 126, 234, 0.15);
        }
        
        .pill .label { 
            color: #667eea; 
            font-weight: 600; 
            display: block; 
            font-size: 12px; 
            text-transform: uppercase; 
            letter-spacing: 0.5px; 
            margin-bottom: 4px; 
        }
        
        .pill .value {
            color: #1a1a1a;
            font-size: 14px;
            font-weight: 700;
        }
        
        .pill.danger .value {
            color: #ef4444;
        }
        
        .pill.success .value {
            color: #10b981;
        }
        
        .filters { 
            padding: 16px 20px; 
            background: rgba(103, 126, 234, 0.05); 
            border-bottom: 1px solid rgba(0, 0, 0, 0.06); 
            display: flex; 
            flex-wrap: wrap;
            gap: 12px; 
            align-items: end; 
        }
        
        .filter-group { 
            display: flex; 
            flex-direction: column; 
            gap: 6px; 
            transition: all 0.3s ease;
            min-width: 100px;
            max-width: 160px;
        }
        
        .filter-label { 
            font-size: 11px; 
            color: #667eea; 
            font-weight: 600; 
            text-transform: uppercase; 
            letter-spacing: 0.5px; 
        }
        
        .filter-select, .filter-input { 
            padding: 8px 10px; 
            border: 2px solid rgba(103, 126, 234, 0.1); 
            border-radius: 8px; 
            font-size: 13px; 
            background: rgba(255, 255, 255, 0.8); 
            transition: all 0.2s ease;
            font-weight: 500;
            width: 100%;
            min-width: 0;
        }
        
        .filter-select:focus, .filter-input:focus { 
            outline: none; 
            border-color: #667eea; 
            background: rgba(255, 255, 255, 0.95);
            box-shadow: 0 0 0 3px rgba(103, 126, 234, 0.1);
        }
        
        .filter-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: #fff; 
            border: none; 
            padding: 8px 16px; 
            border-radius: 8px; 
            font-size: 12px; 
            font-weight: 600; 
            cursor: pointer; 
            transition: all 0.2s ease;
            margin-right: 8px;
            margin-bottom: 2px;
        }
        
        .filter-btn:hover {
            transform: translateY(-1px);
        }
        
        .filter-btn.secondary {
            background: rgba(108, 117, 125, 0.8);
        }
        
        .filter-btn.warning {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        }
        
        .customer-list { 
            list-style: none; 
            padding: 0; 
            margin: 0; 
        }
        
        .customer-item { 
            display: flex; 
            align-items: center; 
            gap: 16px; 
            padding: 16px 20px; 
            border-bottom: 1px solid rgba(0, 0, 0, 0.04); 
            transition: all 0.2s ease;
        }
        
        .customer-item:hover {
            background: rgba(103, 126, 234, 0.02);
        }
        
        .customer-item:last-child { 
            border-bottom: none; 
        }
        
        .customer-avatar { 
            width: 44px; 
            height: 44px; 
            border-radius: 12px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            color: #fff; 
            font-size: 18px; 
            flex-shrink: 0;
            font-weight: 600;
        }
        
        .customer-avatar.retail { 
            background: linear-gradient(135deg, #10b981 0%, #059669 100%); 
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
        }
        
        .customer-avatar.shop { 
            background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); 
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        }
        
        .customer-main { 
            flex: 1; 
            min-width: 0;
        }
        
        .customer-name { 
            font-weight: 600; 
            font-size: 15px; 
            color: #1a1a1a; 
            margin-bottom: 2px;
        }
        
        .customer-details { 
            font-size: 12px; 
            color: #6b7280; 
            line-height: 1.3;
        }
        
        .customer-area {
            background: rgba(103, 126, 234, 0.1);
            color: #667eea;
            padding: 2px 8px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 600;
            display: inline-block;
            margin-top: 4px;
        }
        
        .customer-amounts { 
            text-align: right;
            flex-shrink: 0;
            min-width: 120px;
        }
        
        .amount-row {
            font-size: 11px;
            color: #6b7280;
            margin-bottom: 2px;
        }
        
        .outstanding-amount { 
            font-weight: 700; 
            font-size: 16px; 
        }
        
        .outstanding-positive { 
            color: #ef4444; 
        }
        
        .outstanding-negative { 
            color: #10b981; 
        }
        
        .outstanding-zero {
            color: #6b7280;
        }
        
        .empty { 
            text-align: center; 
            color: #6b7280; 
            padding: 48px 24px; 
            font-size: 16px;
        }
        
        .empty i {
            font-size: 48px;
            margin-bottom: 16px;
            display: block;
            opacity: 0.5;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            margin-top: 20px;
            flex-wrap: wrap;
        }
        
        .page-btn {
            background: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(103, 126, 234, 0.2);
            color: #667eea;
            padding: 8px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 13px;
            font-weight: 600;
            transition: all 0.2s ease;
        }
        
        .page-btn:hover {
            background: rgba(103, 126, 234, 0.1);
            transform: translateY(-1px);
            color: #667eea;
            text-decoration: none;
        }
        
        .page-btn.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: transparent;
        }
        
        .page-info {
            font-size: 13px;
            color: #6b7280;
            margin-top: 12px;
            text-align: center;
        }
        
        /* Mobile optimizations */
        @media (max-width: 768px) {
            .header {
                padding: 12px 16px;
            }
            
            .title {
                font-size: 18px;
            }
            
            .container {
                padding: 16px 12px;
            }
            
            .card h3 {
                padding: 14px 16px;
                font-size: 15px;
            }
            
            .summary {
                padding: 14px 16px;
                grid-template-columns: 1fr 1fr;
                gap: 10px;
            }
            
            .pill {
                padding: 10px;
                font-size: 11px;
            }
            
            .pill .value {
                font-size: 13px;
            }
            
            .filters {
                padding: 14px 16px;
                gap: 10px;
            }
            
            .filter-group {
                min-width: 90px;
                max-width: 120px;
            }
            
            .filter-select, .filter-input {
                padding: 7px 8px;
                font-size: 14px; /* Prevent zoom on iOS */
            }
            
            .export-btn {
                padding: 8px 12px;
                font-size: 12px;
            }
            
            .customer-item {
                padding: 14px 16px;
                gap: 12px;
            }
            
            .customer-avatar {
                width: 40px;
                height: 40px;
                font-size: 16px;
            }
            
            .customer-name {
                font-size: 14px;
            }
            
            .customer-details {
                font-size: 11px;
            }
            
            .outstanding-amount {
                font-size: 15px;
            }
            
            .customer-amounts {
                min-width: 100px;
            }
        }
        
        @media (max-width: 480px) {
            .summary {
                grid-template-columns: 1fr;
            }
            
            .pill {
                text-align: left;
                padding: 8px;
            }
            
            .filters {
                flex-direction: column;
                align-items: stretch;
            }
            
            .filter-group {
                max-width: none;
            }
            
            .customer-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;
                padding: 12px 16px;
            }
            
            .customer-amounts {
                align-self: flex-end;
                text-align: right;
                min-width: auto;
            }
            
            .outstanding-amount {
                font-size: 16px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <a href="javascript:history.back()" class="back-btn" title="Back">
            <i class="fas fa-arrow-left"></i>
        </a>
        <h1 class="title">Outstanding Report</h1>
        <a href="dashboard.php" class="dashboard-btn" title="Dashboard">
            <i class="fas fa-tachometer-alt"></i>
        </a>
        <?php if ($outstandingOnly): ?>
        <div style="background: rgba(239, 68, 68, 0.1); color: #ef4444; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 600;">
            <i class="fas fa-exclamation-triangle mr-1"></i>Outstanding Only
        </div>
        <?php endif; ?>
        <button class="export-btn" onclick="exportOutstanding()">
            <i class="fas fa-download mr-1"></i>Export Excel
        </button>
    </div>

    <div class="container">
        <!-- Summary Statistics -->
        <div class="card">
            <h3>Business Overview</h3>
            <div class="summary">
                <div class="pill">
                    <span class="label">Outstanding Customers</span>
                    <span class="value"><?php echo number_format($summary['OutstandingCustomers']); ?></span>
                </div>
                <div class="pill success">
                    <span class="label">Total Credits</span>
                    <span class="value">₹<?php echo number_format($summary['TotalCredit'], 0); ?></span>
                </div>
                <div class="pill">
                    <span class="label">Total Debits</span>
                    <span class="value">₹<?php echo number_format($summary['TotalDebit'], 0); ?></span>
                </div>
                <div class="pill <?php echo $summary['TotalOutstanding'] > 0 ? 'danger' : 'success'; ?>">
                    <span class="label">Net Outstanding</span>
                    <span class="value">₹<?php echo number_format(abs($summary['TotalOutstanding']), 0); ?><?php if ($summary['TotalOutstanding'] < 0) echo ' (Advance)'; ?></span>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card">
            <h3>Filter & Search</h3>
            <div class="filters">
                <form method="GET" style="display: contents;">
                    <div class="filter-group">
                        <label class="filter-label">Search Customer</label>
                        <input type="text" class="filter-input" name="search" 
                               placeholder="Name or area..." 
                               value="<?php echo htmlspecialchars($searchTerm); ?>">
                    </div>
                    
                    <div class="filter-group">
                        <label class="filter-label">Customer Type</label>
                        <select class="filter-select" name="type">
                            <option value="">All Types</option>
                            <option value="Retail" <?php echo $filterType == 'Retail' ? 'selected' : ''; ?>>Retail</option>
                            <option value="Shop" <?php echo $filterType == 'Shop' ? 'selected' : ''; ?>>Shop</option>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label class="filter-label">From Date</label>
                        <input type="date" class="filter-input" name="date_from" 
                               value="<?php echo $dateFrom; ?>">
                    </div>
                    
                    <div class="filter-group">
                        <label class="filter-label">To Date</label>
                        <input type="date" class="filter-input" name="date_to" 
                               value="<?php echo $dateTo; ?>">
                    </div>
                    
                    <div class="filter-group" style="max-width: 200px;">
                        <label class="filter-label">Actions</label>
                        <div>
                            <button type="submit" class="filter-btn">
                                <i class="fas fa-search mr-1"></i>Search
                            </button>
                            <a href="customer-outstanding.php" class="filter-btn secondary">
                                <i class="fas fa-times mr-1"></i>Clear
                            </a>
                            <a href="customer-outstanding.php?outstanding_only=1" class="filter-btn warning">
                                <i class="fas fa-exclamation-triangle mr-1"></i>Outstanding Only
                            </a>
                        </div>
                    </div>
                    
                    <?php if ($outstandingOnly): ?>
                        <input type="hidden" name="outstanding_only" value="1" />
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <!-- Customer List -->
        <div class="card">
            <h3>
                Customer Outstanding Details 
                <span style="color: #6b7280; font-weight: normal; font-size: 14px;">
                    (<?php echo $totalRecords; ?> customers)
                </span>
            </h3>
            
            <ul class="customer-list">
                <?php 
                $counter = $offset + 1;
                $totalOutstandingSum = 0;
                while($customer = mysqli_fetch_assoc($customersResult)): 
                    $outstandingAmount = $customer['OutstandingAmount'];
                    $totalOutstandingSum += $outstandingAmount;
                    
                    // Determine outstanding class
                    $outstandingClass = 'outstanding-zero';
                    if ($outstandingAmount > 0) {
                        $outstandingClass = 'outstanding-positive';
                    } elseif ($outstandingAmount < 0) {
                        $outstandingClass = 'outstanding-negative';
                    }
                    
                    // Get customer initials for avatar
                    $nameParts = explode(' ', $customer['CustomerName']);
                    $initials = '';
                    if (count($nameParts) >= 2) {
                        $initials = strtoupper(substr($nameParts[0], 0, 1) . substr($nameParts[1], 0, 1));
                    } else {
                        $initials = strtoupper(substr($customer['CustomerName'], 0, 2));
                    }
                ?>
                <li class="customer-item">
                    <div class="customer-avatar <?php echo strtolower($customer['CustomerType']); ?>">
                        <?php echo $initials; ?>
                    </div>
                    
                    <div class="customer-main">
                        <div class="customer-name">
                            <?php echo htmlspecialchars($customer['CustomerName']); ?>
                        </div>
                        <div class="customer-details">
                            <i class="fas fa-phone mr-1"></i>
                            <a href="tel:<?php echo $customer['Mobile']; ?>" style="color: #667eea; text-decoration: none;">
                                <?php echo $customer['Mobile']; ?>
                            </a>
                            <?php if (!empty($customer['AlternativePhone'])): ?>
                            | <a href="tel:<?php echo $customer['AlternativePhone']; ?>" style="color: #6b7280; text-decoration: none;">
                                <?php echo $customer['AlternativePhone']; ?>
                            </a>
                            <?php endif; ?>
                        </div>
                        <div class="customer-area">
                            <i class="fas <?php echo $customer['CustomerType'] == 'Retail' ? 'fa-user' : 'fa-store'; ?> mr-1"></i>
                            <?php echo htmlspecialchars($customer['Area']); ?> • <?php echo $customer['CustomerType']; ?>
                        </div>
                    </div>
                    
                    <div class="customer-amounts">
                        <div class="amount-row">
                            Debit: <span style="color: #ef4444;">₹<?php echo number_format($customer['TotalDebit'], 0); ?></span>
                        </div>
                        <div class="amount-row">
                            Credit: <span style="color: #10b981;">₹<?php echo number_format($customer['TotalCredit'], 0); ?></span>
                        </div>
                        <div class="outstanding-amount <?php echo $outstandingClass; ?>">
                            ₹<?php echo number_format(abs($outstandingAmount), 0); ?>
                            <?php if ($outstandingAmount < 0): ?>
                                <div style="font-size: 10px; color: #10b981;">(Advance)</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </li>
                <?php endwhile; ?>
                
                <?php if (mysqli_num_rows($customersResult) == 0): ?>
                <li class="empty">
                    <i class="fas fa-search"></i>
                    <div>No customers found matching your criteria.</div>
                    <?php if ($outstandingOnly): ?>
                    <div style="font-size: 14px; margin-top: 8px;">
                        <a href="customer-outstanding.php" style="color: #667eea; text-decoration: none;">
                            <i class="fas fa-arrow-left mr-1"></i>Show all customers
                        </a>
                    </div>
                    <?php endif; ?>
                </li>
                <?php endif; ?>
            </ul>
            
            <?php if (mysqli_num_rows($customersResult) > 0): ?>
            <div style="background: rgba(103, 126, 234, 0.05); padding: 16px 20px; border-top: 1px solid rgba(0, 0, 0, 0.06); text-align: center;">
                <strong>Page Total Outstanding: 
                    <span class="<?php echo $totalOutstandingSum > 0 ? 'outstanding-positive' : ($totalOutstandingSum < 0 ? 'outstanding-negative' : 'outstanding-zero'); ?>">
                        ₹<?php echo number_format(abs($totalOutstandingSum), 0); ?>
                        <?php if ($totalOutstandingSum < 0): ?>
                            (Net Advance)
                        <?php endif; ?>
                    </span>
                </strong>
            </div>
            <?php endif; ?>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($searchTerm); ?>&type=<?php echo urlencode($filterType); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?><?php echo $outstandingOnly ? '&outstanding_only=1' : ''; ?>" class="page-btn">
                <i class="fas fa-chevron-left mr-1"></i>Previous
            </a>
            <?php endif; ?>
            
            <?php for ($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
            <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($searchTerm); ?>&type=<?php echo urlencode($filterType); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?><?php echo $outstandingOnly ? '&outstanding_only=1' : ''; ?>" 
               class="page-btn <?php echo $i == $page ? 'active' : ''; ?>">
                <?php echo $i; ?>
            </a>
            <?php endfor; ?>
            
            <?php if ($page < $totalPages): ?>
            <a href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($searchTerm); ?>&type=<?php echo urlencode($filterType); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?><?php echo $outstandingOnly ? '&outstanding_only=1' : ''; ?>" class="page-btn">
                Next<i class="fas fa-chevron-right ml-1"></i>
            </a>
            <?php endif; ?>
        </div>
        
        <div class="page-info">
            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $recordsPerPage, $totalRecords); ?> of <?php echo $totalRecords; ?> customers
        </div>
        <?php endif; ?>
    </div>

    <!-- Include required scripts for Excel export -->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

    <script>
        function exportOutstanding() {
            // Create a virtual table for export with all customer data
            const exportData = [];
            
            // Header row
            exportData.push([
                'Customer Name',
                'Mobile',
                'Alternative Phone',
                'Area',
                'Customer Type',
                'Total Debit',
                'Total Credit',
                'Outstanding Amount'
            ]);
            
            // Get customer data from the list
            const customerItems = document.querySelectorAll('.customer-item');
            customerItems.forEach(item => {
                const customerName = item.querySelector('.customer-name').textContent.trim();
                const phoneLinks = item.querySelectorAll('.customer-details a');
                const mobile = phoneLinks[0] ? phoneLinks[0].textContent.trim() : '';
                const altPhone = phoneLinks[1] ? phoneLinks[1].textContent.trim() : '';
                const areaText = item.querySelector('.customer-area').textContent.trim();
                const areaParts = areaText.split(' • ');
                const area = areaParts[0].replace(/^[^a-zA-Z]*/, '').trim(); // Remove icon
                const customerType = areaParts[1] || '';
                
                const amountRows = item.querySelectorAll('.amount-row');
                const debitText = amountRows[0] ? amountRows[0].textContent : '';
                const creditText = amountRows[1] ? amountRows[1].textContent : '';
                const outstandingText = item.querySelector('.outstanding-amount').textContent.trim();
                
                // Extract amounts (remove currency symbols and format)
                const debit = debitText.match(/₹([\d,]+)/)?.[1].replace(/,/g, '') || '0';
                const credit = creditText.match(/₹([\d,]+)/)?.[1].replace(/,/g, '') || '0';
                let outstanding = outstandingText.match(/₹([\d,]+)/)?.[1].replace(/,/g, '') || '0';
                
                // Handle negative outstanding (advance)
                if (outstandingText.includes('(Advance)')) {
                    outstanding = '-' + outstanding;
                }
                
                exportData.push([
                    customerName,
                    mobile,
                    altPhone,
                    area,
                    customerType,
                    parseInt(debit),
                    parseInt(credit),
                    parseInt(outstanding)
                ]);
            });
            
            // Create workbook and worksheet
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.aoa_to_sheet(exportData);
            
            // Set column widths
            ws['!cols'] = [
                { width: 25 },  // Customer Name
                { width: 15 },  // Mobile
                { width: 15 },  // Alternative Phone
                { width: 20 },  // Area
                { width: 12 },  // Customer Type
                { width: 15 },  // Total Debit
                { width: 15 },  // Total Credit
                { width: 18 }   // Outstanding Amount
            ];
            
            // Add some basic formatting
            const range = XLSX.utils.decode_range(ws['!ref']);
            for (let row = 0; row <= range.e.r; row++) {
                for (let col = 0; col <= range.e.c; col++) {
                    const cellAddress = XLSX.utils.encode_cell({ r: row, c: col });
                    if (!ws[cellAddress]) continue;
                    
                    // Header row formatting
                    if (row === 0) {
                        ws[cellAddress].s = {
                            font: { bold: true },
                            fill: { fgColor: { rgb: "EEEEEE" } }
                        };
                    }
                    
                    // Number formatting for amount columns
                    if ((col >= 5 && col <= 7) && row > 0) {
                        ws[cellAddress].t = 'n';
                        ws[cellAddress].z = '#,##0';
                    }
                }
            }
            
            XLSX.utils.book_append_sheet(wb, ws, 'Customer Outstanding');
            
            // Generate filename with current date and filter info
            let filename = 'Customer_Outstanding_Report_' + new Date().toISOString().slice(0, 10);
            
            <?php if ($outstandingOnly): ?>
            filename += '_Outstanding_Only';
            <?php endif; ?>
            
            <?php if (!empty($filterType)): ?>
            filename += '_<?php echo $filterType; ?>';
            <?php endif; ?>
            
            filename += '.xlsx';
            
            // Save file
            XLSX.writeFile(wb, filename);
        }
        
        // Auto-refresh data every 5 minutes
        setInterval(function() {
            if (!document.hidden) {
                location.reload();
            }
        }, 300000);
        
        // Add smooth scrolling for pagination
        document.querySelectorAll('.page-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                // Add a subtle loading state
                document.body.style.opacity = '0.8';
                document.body.style.pointerEvents = 'none';
            });
        });
        
        // Initialize any tooltips or interactive elements
        document.addEventListener('DOMContentLoaded', function() {
            // Add click animation to filter buttons
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    this.style.transform = 'scale(0.95)';
                    setTimeout(() => {
                        this.style.transform = '';
                    }, 150);
                });
            });
            
            // Add hover effects for customer items
            document.querySelectorAll('.customer-item').forEach(item => {
                item.addEventListener('mouseenter', function() {
                    this.style.transform = 'translateX(4px)';
                });
                
                item.addEventListener('mouseleave', function() {
                    this.style.transform = '';
                });
            });
        });
    </script>
</body>
</html>
