<?php
declare(strict_types=1);
session_start();

require_once '../assets/db_connect.php';

// Start output buffering
ob_start();

require_once '../includes/header.php';
require_once '../includes/sidebar.php';

// Authentication check
if (!isset($_SESSION['user'])) { 
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'><div class='alert alert-danger'>Access denied.</div></div>";
    require_once '../includes/footer.php';
    exit; 
}

$user_role = $_SESSION['user']['role'] ?? 'cashier';
$user_shop_id = (int)($_SESSION['user']['shop_id'] ?? 0);
$current_user_id = (int)($_SESSION['user']['id'] ?? 0);

// Get filter parameters with validation
$from = $_GET['from'] ?? date('Y-m-01');
$to = $_GET['to'] ?? date('Y-m-d');

// Validate dates
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
    $from = date('Y-m-01');
    $to = date('Y-m-d');
}

// Ensure from <= to
if (strtotime($from) > strtotime($to)) {
    $temp = $from;
    $from = $to;
    $to = $temp;
}

// Shop selection logic
if ($user_role === 'admin') {
    $shop_id = (int)($_GET['shop_id'] ?? 0);
} else {
    $shop_id = $user_shop_id;
}

/* ---- FETCH SHOPS FOR ADMIN ---- */
$shops = [];
if ($user_role === 'admin') {
    $shop_stmt = $pdo->prepare("SELECT id, name FROM shops ORDER BY name");
    $shop_stmt->execute();
    $shops = $shop_stmt->fetchAll(PDO::FETCH_ASSOC);
}

/* ---- MAIN SALES BY USER QUERY WITH ANALYTICS ---- */
$sql = "
WITH sales_summary AS (
    SELECT 
        s.created_by as user_id,
        u.fullname as cashier_name,
        u.username,
        u.role,
        sh.id as shop_id,
        sh.name as shop_name,
        COUNT(DISTINCT s.id) as total_sales_count,
        COUNT(DISTINCT s.customer_id) as unique_customers,
        SUM(s.total) as gross_revenue,
        SUM(p.total_paid) as total_collected,
        SUM(s.total - COALESCE(p.total_paid, 0)) as outstanding_balance,
        AVG(s.total) as avg_sale_amount,
        MIN(s.sale_date) as first_sale_date,
        MAX(s.sale_date) as last_sale_date
    FROM sales s
    INNER JOIN users u ON s.created_by = u.id
    LEFT JOIN shops sh ON s.shop_id = sh.id
    LEFT JOIN (
        SELECT sale_id, SUM(amount) as total_paid
        FROM payments
        GROUP BY sale_id
    ) p ON s.id = p.sale_id
    WHERE DATE(s.sale_date) BETWEEN :from_date AND :to_date
        AND s.status != 'cancelled'
";

$params = [
    ':from_date' => $from,
    ':to_date' => $to
];

if ($shop_id > 0) {
    $sql .= " AND s.shop_id = :shop_id";
    $params[':shop_id'] = $shop_id;
} elseif ($user_role !== 'admin' && $user_shop_id > 0) {
    $sql .= " AND s.shop_id = :shop_id";
    $params[':shop_id'] = $user_shop_id;
}

$sql .= "
    GROUP BY s.created_by, u.id, u.fullname, u.username, u.role, sh.id, sh.name
),
payment_status_summary AS (
    SELECT 
        user_id,
        SUM(CASE WHEN s.status = 'paid' THEN 1 ELSE 0 END) as fully_paid_sales,
        SUM(CASE WHEN s.status = 'partially_paid' THEN 1 ELSE 0 END) as partially_paid_sales,
        SUM(CASE WHEN s.status = 'open' THEN 1 ELSE 0 END) as open_sales
    FROM sales s
    WHERE DATE(s.sale_date) BETWEEN :from_date2 AND :to_date2
        AND s.status != 'cancelled'
    GROUP BY s.created_by
)
SELECT 
    ss.*,
    COALESCE(pss.fully_paid_sales, 0) as fully_paid_sales,
    COALESCE(pss.partially_paid_sales, 0) as partially_paid_sales,
    COALESCE(pss.open_sales, 0) as open_sales,
    CASE 
        WHEN ss.total_sales_count > 0 
        THEN ROUND((ss.total_collected / NULLIF(ss.gross_revenue, 0)) * 100, 2)
        ELSE 0 
    END as collection_rate_percent,
    CASE 
        WHEN ss.total_sales_count > 0 
        THEN ROUND(ss.outstanding_balance / NULLIF(ss.total_sales_count, 0), 2)
        ELSE 0 
    END as avg_outstanding_per_sale
FROM sales_summary ss
LEFT JOIN payment_status_summary pss ON ss.user_id = pss.user_id
ORDER BY ss.gross_revenue DESC, ss.total_sales_count DESC
";

try {
    $stmt = $pdo->prepare($sql);
    
    // Bind parameters (need to bind twice for CTE subqueries)
    $stmt->bindValue(':from_date', $from);
    $stmt->bindValue(':to_date', $to);
    $stmt->bindValue(':from_date2', $from);
    $stmt->bindValue(':to_date2', $to);
    
    if (isset($params[':shop_id'])) {
        $stmt->bindValue(':shop_id', $params[':shop_id']);
    }
    
    $stmt->execute();
    $user_sales = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Convert numeric strings to floats
    foreach ($user_sales as &$user) {
        $user['gross_revenue'] = (float)($user['gross_revenue'] ?? 0);
        $user['total_collected'] = (float)($user['total_collected'] ?? 0);
        $user['outstanding_balance'] = (float)($user['outstanding_balance'] ?? 0);
        $user['avg_sale_amount'] = (float)($user['avg_sale_amount'] ?? 0);
        $user['collection_rate_percent'] = (float)($user['collection_rate_percent'] ?? 0);
        $user['avg_outstanding_per_sale'] = (float)($user['avg_outstanding_per_sale'] ?? 0);
        $user['total_sales_count'] = (int)($user['total_sales_count'] ?? 0);
        $user['unique_customers'] = (int)($user['unique_customers'] ?? 0);
        $user['fully_paid_sales'] = (int)($user['fully_paid_sales'] ?? 0);
        $user['partially_paid_sales'] = (int)($user['partially_paid_sales'] ?? 0);
        $user['open_sales'] = (int)($user['open_sales'] ?? 0);
    }
    unset($user); // Break the reference
    
} catch (PDOException $e) {
    error_log("User sales query failed: " . $e->getMessage());
    $user_sales = [];
}

/* ---- CALCULATE GRAND TOTALS AND SUMMARIES ---- */
$summary = [
    'total_cashiers' => 0,
    'total_sales' => 0,
    'total_gross_revenue' => 0.0,
    'total_collected' => 0.0,
    'total_outstanding' => 0.0,
    'total_customers' => 0,
    'top_performer' => null,
    'best_collection_rate' => null,
    'sales_by_role' => []
];

if (!empty($user_sales)) {
    $summary['total_cashiers'] = count($user_sales);
    $summary['total_sales'] = array_sum(array_column($user_sales, 'total_sales_count'));
    $summary['total_gross_revenue'] = array_sum(array_column($user_sales, 'gross_revenue'));
    $summary['total_collected'] = array_sum(array_column($user_sales, 'total_collected'));
    $summary['total_outstanding'] = array_sum(array_column($user_sales, 'outstanding_balance'));
    
    // Sum unique customers (may have duplicates across users)
    $summary['total_customers'] = array_sum(array_column($user_sales, 'unique_customers'));
    
    // Get top performer by revenue
    $summary['top_performer'] = $user_sales[0] ?? null;
    
    // Get best collection rate
    usort($user_sales, function($a, $b) {
        return $b['collection_rate_percent'] <=> $a['collection_rate_percent'];
    });
    $summary['best_collection_rate'] = $user_sales[0] ?? null;
    
    // Group by role
    foreach ($user_sales as $user) {
        $role = $user['role'] ?? 'unknown';
        if (!isset($summary['sales_by_role'][$role])) {
            $summary['sales_by_role'][$role] = [
                'count' => 0,
                'total_sales' => 0,
                'total_revenue' => 0.0,
                'total_collected' => 0.0
            ];
        }
        $summary['sales_by_role'][$role]['count']++;
        $summary['sales_by_role'][$role]['total_sales'] += $user['total_sales_count'];
        $summary['sales_by_role'][$role]['total_revenue'] += $user['gross_revenue'];
        $summary['sales_by_role'][$role]['total_collected'] += $user['total_collected'];
    }
}

/* ---- CSV EXPORT ---- */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    // Clean output buffer
    ob_clean();
    
    // Set headers
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=user_sales_performance_' . $from . '_to_' . $to . '.csv');
    
    // Output BOM for UTF-8 compatibility
    echo "\xEF\xBB\xBF";
    
    $output = fopen('php://output', 'w');
    
    // Add report header
    fputcsv($output, ['User Sales Performance Report']);
    fputcsv($output, ['Period:', $from . ' to ' . $to]);
    
    // Get shop name for CSV
    $shop_name = 'All Shops';
    if ($shop_id > 0) {
        foreach ($shops as $shop) {
            if ($shop['id'] == $shop_id) {
                $shop_name = $shop['name'];
                break;
            }
        }
    }
    fputcsv($output, ['Shop:', $shop_name]);
    fputcsv($output, ['Generated:', date('Y-m-d H:i:s')]);
    fputcsv($output, []); // Empty line
    
    // Column headers
    fputcsv($output, [
        'Cashier Name',
        'Username',
        'Role',
        'Shop',
        'Total Sales',
        'Unique Customers',
        'Gross Revenue',
        'Amount Collected',
        'Outstanding Balance',
        'Avg Sale Amount',
        'Collection Rate %',
        'Avg Outstanding/Sale',
        'Fully Paid',
        'Partially Paid',
        'Open Sales',
        'First Sale',
        'Last Sale'
    ]);
    
    // Data rows
    foreach ($user_sales as $user) {
        fputcsv($output, [
            $user['cashier_name'] ?? '',
            $user['username'] ?? '',
            $user['role'] ?? '',
            $user['shop_name'] ?? '',
            $user['total_sales_count'],
            $user['unique_customers'],
            $user['gross_revenue'],
            $user['total_collected'],
            $user['outstanding_balance'],
            $user['avg_sale_amount'],
            $user['collection_rate_percent'],
            $user['avg_outstanding_per_sale'],
            $user['fully_paid_sales'],
            $user['partially_paid_sales'],
            $user['open_sales'],
            $user['first_sale_date'] ?? '',
            $user['last_sale_date'] ?? ''
        ]);
    }
    
    // Summary rows
    fputcsv($output, []); // Empty line
    fputcsv($output, ['SUMMARY', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']);
    fputcsv($output, [
        'Total Cashiers: ' . $summary['total_cashiers'],
        '',
        '',
        '',
        'Total Sales: ' . $summary['total_sales'],
        'Total Customers: ' . $summary['total_customers'],
        'Total Revenue: ' . $summary['total_gross_revenue'],
        'Total Collected: ' . $summary['total_collected'],
        'Total Outstanding: ' . $summary['total_outstanding'],
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        ''
    ]);
    
    fclose($output);
    exit;
}
?>

<!-- PRINT CSS -->
<style>
@media print {
    body * { 
        visibility: hidden; 
        margin: 0;
        padding: 0;
    }
    #print-area, #print-area * { 
        visibility: visible; 
    }
    #print-area { 
        position: absolute; 
        left: 0; 
        top: 0; 
        width: 100%; 
        font-size: 11px;
    }
    .no-print { 
        display: none !important; 
    }
    .summary-cards {
        display: none;
    }
}

/* Back button styling */
.back-btn {
    display: inline-flex;
    align-items: center;
    padding: 8px 16px;
    background-color: #6c757d;
    color: white;
    text-decoration: none;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    font-size: 14px;
    margin-bottom: 15px;
    transition: background-color 0.2s;
    gap: 5px;
}

.back-btn:hover {
    background-color: #5a6268;
    color: white;
    text-decoration: none;
}

/* Summary cards */
.summary-card {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    background: #f8f9fa;
    transition: transform 0.2s;
    height: 100%;
}

.summary-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

/* Status indicators */
.status-indicator {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 5px;
}

.status-paid { background-color: #28a745; }
.status-partial { background-color: #17a2b8; }
.status-open { background-color: #ffc107; }

/* Progress bars */
.progress-thin {
    height: 6px;
    margin-top: 5px;
}

/* Badges */
.role-badge {
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
}

.role-admin { background-color: #dc3545; color: white; }
.role-pharmacist { background-color: #17a2b8; color: white; }
.role-cashier { background-color: #6c757d; color: white; }

/* Table styling */
.table-hover tbody tr:hover {
    background-color: rgba(0,0,0,0.025);
}

.text-end {
    text-align: right !important;
}
</style>

<div class="col-md-10 ml-sm-auto px-4 py-4">

<!-- BACK BUTTON 1: Top of the page -->
<div class="no-print mb-3">
    <a href="daily_sales.php" class="back-btn">
        <i class="fas fa-arrow-left"></i> Back to Reports
    </a>
</div>

<!-- FILTER FORM -->
<div class="no-print">
    <h3 class="text-success mb-4">User Sales Performance</h3>
    
    <form method="GET" class="row g-3 mb-4">
        <div class="col-md-3">
            <label for="from" class="form-label">From Date</label>
            <input type="date" id="from" name="from" value="<?= htmlspecialchars($from) ?>" 
                   class="form-control form-control-sm" required>
        </div>
        
        <div class="col-md-3">
            <label for="to" class="form-label">To Date</label>
            <input type="date" id="to" name="to" value="<?= htmlspecialchars($to) ?>" 
                   class="form-control form-control-sm" required>
        </div>
        
        <?php if ($user_role === 'admin'): ?>
        <div class="col-md-3">
            <label for="shop_id" class="form-label">Shop</label>
            <select id="shop_id" name="shop_id" class="form-select form-select-sm">
                <option value="0">All Shops</option>
                <?php foreach($shops as $shop): ?>
                    <option value="<?= (int)$shop['id'] ?>" 
                        <?= ($shop_id === (int)$shop['id']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($shop['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php else: ?>
            <input type="hidden" name="shop_id" value="<?= $shop_id ?>">
        <?php endif; ?>
        
        <div class="col-md-3 d-flex align-items-end">
            <div class="btn-group w-100" role="group">
                <button type="submit" class="btn btn-primary btn-sm">
                    <i class="fas fa-filter"></i> Filter
                </button>
                <a href="sales_by_user.php" class="btn btn-secondary btn-sm">
                    <i class="fas fa-sync"></i> Reset
                </a>
                <a href="?from=<?= $from ?>&to=<?= $to ?>&shop_id=<?= $shop_id ?>&export=csv" 
                   class="btn btn-success btn-sm">
                    <i class="fas fa-download"></i> CSV
                </a>
                <button type="button" onclick="window.print();" class="btn btn-dark btn-sm">
                    <i class="fas fa-print"></i> Print
                </button>
            </div>
        </div>
    </form>
</div>

<!-- PERFORMANCE SUMMARY CARDS -->
<?php if (!empty($user_sales)): ?>
<div class="row mb-4 no-print">
    <div class="col-md-3">
        <div class="summary-card text-center">
            <h6 class="text-muted mb-2">Active Users</h6>
            <h3 class="text-primary mb-0"><?= number_format($summary['total_cashiers']) ?></h3>
            <small class="text-muted">
                <?php foreach($summary['sales_by_role'] as $role => $data): ?>
                    <?= ucfirst($role) ?>: <?= $data['count'] ?> 
                <?php endforeach; ?>
            </small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="summary-card text-center">
            <h6 class="text-muted mb-2">Total Sales</h6>
            <h3 class="text-info mb-0"><?= number_format($summary['total_sales']) ?></h3>
            <small class="text-muted">
                Avg/User: <?= number_format($summary['total_sales'] / max($summary['total_cashiers'], 1), 1) ?>
            </small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="summary-card text-center">
            <h6 class="text-muted mb-2">Revenue Generated</h6>
            <h3 class="text-success mb-0"><?= number_format($summary['total_gross_revenue'], 2) ?></h3>
            <small class="text-muted">
                Collected: <?= number_format($summary['total_collected'], 2) ?>
            </small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="summary-card text-center">
            <h6 class="text-muted mb-2">Collection Rate</h6>
            <h3 class="<?= ($summary['total_gross_revenue'] > 0) ? (($summary['total_collected'] / $summary['total_gross_revenue'] * 100) >= 90 ? 'text-success' : 'text-warning') : 'text-secondary' ?> mb-0">
                <?= $summary['total_gross_revenue'] > 0 ? number_format(($summary['total_collected'] / $summary['total_gross_revenue']) * 100, 1) : '0' ?>%
            </h3>
            <small class="text-muted">
                Outstanding: <?= number_format($summary['total_outstanding'], 2) ?>
            </small>
        </div>
    </div>
</div>

<!-- TOP PERFORMER HIGHLIGHT -->
<?php if ($summary['top_performer']): ?>
<div class="row mb-4 no-print">
    <div class="col-12">
        <div class="card border-success">
            <div class="card-header bg-success text-white">
                <h6 class="mb-0"><i class="fas fa-trophy mr-2"></i> Top Performer</h6>
            </div>
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-3">
                        <h5 class="mb-1"><?= htmlspecialchars($summary['top_performer']['cashier_name']) ?></h5>
                        <div class="d-flex align-items-center">
                            <span class="role-badge role-<?= $summary['top_performer']['role'] ?> mr-2">
                                <?= ucfirst($summary['top_performer']['role']) ?>
                            </span>
                            <small class="text-muted">@<?= htmlspecialchars($summary['top_performer']['username']) ?></small>
                        </div>
                    </div>
                    <div class="col-md-9">
                        <div class="row text-center">
                            <div class="col">
                                <h6 class="text-muted mb-1">Sales</h6>
                                <h4 class="mb-0"><?= number_format($summary['top_performer']['total_sales_count']) ?></h4>
                            </div>
                            <div class="col">
                                <h6 class="text-muted mb-1">Revenue</h6>
                                <h4 class="mb-0 text-success"><?= number_format($summary['top_performer']['gross_revenue'], 2) ?></h4>
                            </div>
                            <div class="col">
                                <h6 class="text-muted mb-1">Collection</h6>
                                <h4 class="mb-0 text-info"><?= number_format($summary['top_performer']['collection_rate_percent'], 1) ?>%</h4>
                            </div>
                            <div class="col">
                                <h6 class="text-muted mb-1">Avg Sale</h6>
                                <h4 class="mb-0"><?= number_format($summary['top_performer']['avg_sale_amount'], 2) ?></h4>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>
<?php endif; ?>

<!-- PRINT AREA START -->
<div id="print-area">
    <div class="text-center mb-4">
        <h4 class="mb-1"><strong>User Sales Performance Report</strong></h4>
        <p class="mb-1"><?= date('d M Y', strtotime($from)) ?> — <?= date('d M Y', strtotime($to)) ?></p>
        <p class="text-muted mb-0">
            <?php if ($shop_id == 0): ?>
                <em>All Shops</em>
            <?php else: 
                $shop_name = '';
                if (!empty($user_sales)) {
                    $shop_name = $user_sales[0]['shop_name'] ?? '';
                } elseif (!empty($shops)) {
                    foreach ($shops as $shop) {
                        if ($shop['id'] == $shop_id) {
                            $shop_name = $shop['name'];
                            break;
                        }
                    }
                }
            ?>
                <em>Shop: <?= htmlspecialchars($shop_name) ?></em>
            <?php endif; ?>
        </p>
        <p class="text-muted"><small>Generated: <?= date('d-M-Y H:i') ?></small></p>
        <?php if (!empty($user_sales)): ?>
        <p class="text-muted mb-0">
            <small>
                Showing <?= number_format($summary['total_cashiers']) ?> users, 
                <?= number_format($summary['total_sales']) ?> sales, 
                <?= number_format($summary['total_gross_revenue'], 2) ?> revenue
            </small>
        </p>
        <?php endif; ?>
    </div>

    <div class="table-responsive">
        <table class="table table-bordered table-sm table-hover">
            <thead class="table-light">
                <tr>
                    <th>#</th>
                    <th>User Details</th>
                    <th class="text-end">Sales</th>
                    <th class="text-end">Customers</th>
                    <th class="text-end">Gross Revenue</th>
                    <th class="text-end">Collected</th>
                    <th class="text-end">Outstanding</th>
                    <th class="text-end">Collection %</th>
                    <th>Payment Status</th>
                    <?php if ($shop_id == 0): ?>
                    <th>Shop</th>
                    <?php endif; ?>
                </tr>
            </thead>

            <tbody>
                <?php if (empty($user_sales)): ?>
                    <tr>
                        <td colspan="<?= $shop_id == 0 ? 10 : 9 ?>" class="text-center py-4">
                            <div class="text-muted">
                                <i class="fas fa-users fa-2x mb-2"></i><br>
                                No user sales found for the selected period
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach($user_sales as $index => $user): 
                        $revenue_percentage = ($user['gross_revenue'] / max($summary['total_gross_revenue'], 1)) * 100;
                    ?>
                        <tr>
                            <td><?= $index + 1 ?></td>
                            <td>
                                <div class="fw-bold"><?= htmlspecialchars($user['cashier_name']) ?></div>
                                <div class="small text-muted">
                                    <span class="role-badge role-<?= $user['role'] ?>">
                                        <?= ucfirst($user['role']) ?>
                                    </span>
                                    @<?= htmlspecialchars($user['username']) ?>
                                </div>
                                <div class="small text-muted">
                                    First: <?= !empty($user['first_sale_date']) ? date('d-M-y', strtotime($user['first_sale_date'])) : 'N/A' ?> | 
                                    Last: <?= !empty($user['last_sale_date']) ? date('d-M-y', strtotime($user['last_sale_date'])) : 'N/A' ?>
                                </div>
                                <div class="progress progress-thin mt-1">
                                    <div class="progress-bar bg-primary" role="progressbar" 
                                         style="width: <?= min($revenue_percentage, 100) ?>%" 
                                         aria-valuenow="<?= $revenue_percentage ?>" 
                                         aria-valuemin="0" 
                                         aria-valuemax="100"></div>
                                </div>
                                <small class="text-muted"><?= number_format($revenue_percentage, 1) ?>% of total revenue</small>
                            </td>
                            <td class="text-end fw-bold"><?= number_format($user['total_sales_count']) ?></td>
                            <td class="text-end"><?= number_format($user['unique_customers']) ?></td>
                            <td class="text-end"><?= number_format((float)$user['gross_revenue'], 2) ?></td>
                            <td class="text-end text-success"><?= number_format((float)$user['total_collected'], 2) ?></td>
                            <td class="text-end <?= $user['outstanding_balance'] > 0 ? 'text-warning fw-bold' : 'text-success' ?>">
                                <?= number_format((float)$user['outstanding_balance'], 2) ?>
                            </td>
                            <td class="text-end fw-bold <?= $user['collection_rate_percent'] >= 90 ? 'text-success' : ($user['collection_rate_percent'] >= 70 ? 'text-warning' : 'text-danger') ?>">
                                <?= number_format((float)$user['collection_rate_percent'], 1) ?>%
                            </td>
                            <td>
                                <div class="d-flex flex-column small">
                                    <div>
                                        <span class="status-indicator status-paid"></span>
                                        Paid: <?= $user['fully_paid_sales'] ?>
                                    </div>
                                    <div>
                                        <span class="status-indicator status-partial"></span>
                                        Partial: <?= $user['partially_paid_sales'] ?>
                                    </div>
                                    <div>
                                        <span class="status-indicator status-open"></span>
                                        Open: <?= $user['open_sales'] ?>
                                    </div>
                                </div>
                            </td>
                            <?php if ($shop_id == 0): ?>
                            <td><?= htmlspecialchars($user['shop_name'] ?? '') ?></td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>

            <?php if (!empty($user_sales)): ?>
            <tfoot class="table-active">
                <tr>
                    <th colspan="2" class="text-end">GRAND TOTALS:</th>
                    <th class="text-end"><?= number_format($summary['total_sales']) ?></th>
                    <th class="text-end"><?= number_format($summary['total_customers']) ?></th>
                    <th class="text-end"><?= number_format($summary['total_gross_revenue'], 2) ?></th>
                    <th class="text-end text-success"><?= number_format($summary['total_collected'], 2) ?></th>
                    <th class="text-end <?= $summary['total_outstanding'] > 0 ? 'text-warning fw-bold' : 'text-success' ?>">
                        <?= number_format($summary['total_outstanding'], 2) ?>
                    </th>
                    <th class="text-end">
                        <?= $summary['total_gross_revenue'] > 0 ? number_format(($summary['total_collected'] / $summary['total_gross_revenue']) * 100, 1) : '0' ?>%
                    </th>
                    <th>
                        <small>
                            <?= array_sum(array_column($user_sales, 'fully_paid_sales')) ?> paid,
                            <?= array_sum(array_column($user_sales, 'partially_paid_sales')) ?> partial
                        </small>
                    </th>
                    <?php if ($shop_id == 0): ?>
                    <th></th>
                    <?php endif; ?>
                </tr>
            </tfoot>
            <?php endif; ?>
        </table>
    </div>
</div>
<!-- PRINT AREA END -->

<!-- BACK BUTTON 2: Bottom of the page -->
<div class="no-print mt-4">
    <a href="daily_sales.php" class="back-btn">
        <i class="fas fa-arrow-left"></i> Back to Reports
    </a>
</div>

</div>

<?php 
require_once '../includes/footer.php'; 
ob_end_flush();
?>