<?php
/**
 * Buyer Analysis Report
 * LandSales Pro - Top buyers and purchase patterns
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];

// Get top buyers by purchase value
$topBuyers = db_fetch_all("SELECT b.*,
    COUNT(s.id) as purchase_count,
    COALESCE(SUM(s.total_price), 0) as total_value,
    COALESCE(SUM((SELECT SUM(amount) FROM payments WHERE sale_id = s.id AND status = 'confirmed')), 0) as total_paid
    FROM buyers b
    LEFT JOIN sales s ON b.id = s.buyer_id AND s.status IN ('active', 'completed')
    WHERE b.user_id = ?
    GROUP BY b.id
    ORDER BY total_value DESC
    LIMIT 20", 'i', [$userId]);

// Get stats
$buyerStats = db_fetch_one("SELECT
    COUNT(DISTINCT b.id) as total_buyers,
    COUNT(DISTINCT CASE WHEN s.id IS NOT NULL THEN b.id END) as buyers_with_purchases,
    AVG(purchase_value) as avg_purchase
    FROM buyers b
    LEFT JOIN (
        SELECT buyer_id, COUNT(*) as purchase_count, SUM(total_price) as purchase_value
        FROM sales WHERE status IN ('active', 'completed')
        GROUP BY buyer_id
    ) s ON b.id = s.buyer_id
    WHERE b.user_id = ?", 'i', [$userId]);

// Buyers by purchase count distribution
$purchaseDistribution = db_fetch_all("SELECT
    CASE
        WHEN purchase_count = 0 THEN '0 purchases'
        WHEN purchase_count = 1 THEN '1 purchase'
        WHEN purchase_count BETWEEN 2 AND 3 THEN '2-3 purchases'
        ELSE '4+ purchases'
    END as category,
    COUNT(*) as buyer_count
    FROM (
        SELECT b.id, COUNT(s.id) as purchase_count
        FROM buyers b
        LEFT JOIN sales s ON b.id = s.buyer_id AND s.status IN ('active', 'completed')
        WHERE b.user_id = ?
        GROUP BY b.id
    ) t
    GROUP BY category
    ORDER BY FIELD(category, '0 purchases', '1 purchase', '2-3 purchases', '4+ purchases')", 'i', [$userId]);

// Recent buyers
$recentBuyers = db_fetch_all("SELECT b.*, COUNT(s.id) as purchase_count
    FROM buyers b
    LEFT JOIN sales s ON b.id = s.buyer_id AND s.status IN ('active', 'completed')
    WHERE b.user_id = ?
    GROUP BY b.id
    ORDER BY b.created_at DESC
    LIMIT 10", 'i', [$userId]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Buyer Analysis - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Buyer Analysis</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <button onclick="window.print()" class="btn btn-outline">
                    <i class="fas fa-print"></i> Print
                </button>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Summary Stats -->
            <div class="stats-row">
                <div class="stat-mini">
                    <i class="fas fa-users"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($buyerStats['total_buyers']); ?></div>
                        <div class="stat-label">Total Buyers</div>
                    </div>
                </div>
                <div class="stat-mini success">
                    <i class="fas fa-shopping-cart"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($buyerStats['buyers_with_purchases']); ?></div>
                        <div class="stat-label">With Purchases</div>
                    </div>
                </div>
                <div class="stat-mini info">
                    <i class="fas fa-chart-bar"></i>
                    <div>
                        <div class="stat-value">TZS <?php echo formatMoney($buyerStats['avg_purchase'] ?? 0); ?></div>
                        <div class="stat-label">Avg Purchase Value</div>
                    </div>
                </div>
            </div>

            <div class="report-grid">
                <!-- Top Buyers -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-trophy"></i> Top Buyers by Value</h3>
                    </div>
                    <div class="table-responsive">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Buyer</th>
                                    <th>Purchases</th>
                                    <th>Total Value</th>
                                    <th>Paid</th>
                                    <th>Balance</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($topBuyers)): ?>
                                <tr>
                                    <td colspan="6" class="empty-row">
                                        <div class="empty-state">
                                            <i class="fas fa-users"></i>
                                            <p>No buyers found</p>
                                        </div>
                                    </td>
                                </tr>
                                <?php else: ?>
                                <?php $rank = 1; foreach ($topBuyers as $buyer):
                                    $balance = $buyer['total_value'] - $buyer['total_paid'];
                                ?>
                                <tr>
                                    <td>
                                        <span class="rank-badge <?php echo $rank <= 3 ? 'top' : ''; ?>"><?php echo $rank++; ?></span>
                                    </td>
                                    <td>
                                        <div class="buyer-info">
                                            <div class="buyer-name"><?php echo htmlspecialchars($buyer['full_name']); ?></div>
                                            <div class="buyer-phone"><?php echo $buyer['phone']; ?></div>
                                        </div>
                                    </td>
                                    <td><?php echo $buyer['purchase_count']; ?></td>
                                    <td>TZS <?php echo number_format($buyer['total_value']); ?></td>
                                    <td class="text-success">TZS <?php echo number_format($buyer['total_paid']); ?></td>
                                    <td class="<?php echo $balance > 0 ? 'text-warning' : 'text-success'; ?>">
                                        TZS <?php echo number_format($balance); ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="side-cards">
                    <!-- Purchase Distribution -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-chart-pie"></i> Purchase Distribution</h3>
                        </div>
                        <div class="card-body">
                            <?php foreach ($purchaseDistribution as $dist): ?>
                            <div class="distribution-item">
                                <div class="dist-label">
                                    <span><?php echo $dist['category']; ?></span>
                                    <span><?php echo $dist['buyer_count']; ?> buyers</span>
                                </div>
                                <div class="dist-bar">
                                    <div class="dist-fill" style="width: <?php echo $buyerStats['total_buyers'] > 0 ? ($dist['buyer_count'] / $buyerStats['total_buyers']) * 100 : 0; ?>%"></div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Recent Buyers -->
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-clock"></i> Recently Added</h3>
                        </div>
                        <div class="card-body">
                            <div class="recent-list">
                                <?php foreach ($recentBuyers as $buyer): ?>
                                <a href="../buyers/view.php?id=<?php echo $buyer['id']; ?>" class="recent-item">
                                    <div class="recent-avatar">
                                        <?php echo strtoupper(substr($buyer['full_name'], 0, 2)); ?>
                                    </div>
                                    <div class="recent-info">
                                        <div class="recent-name"><?php echo htmlspecialchars($buyer['full_name']); ?></div>
                                        <div class="recent-meta">
                                            <?php echo $buyer['purchase_count']; ?> purchases
                                            • Added <?php echo date('M j', strtotime($buyer['created_at'])); ?>
                                        </div>
                                    </div>
                                </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .stats-row { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
        .stat-mini { flex: 1; min-width: 180px; padding: 1rem; background: white; border-radius: 10px; display: flex; align-items: center; gap: 0.75rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .stat-mini i { width: 40px; height: 40px; background: #f1f5f9; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #64748b; }
        .stat-mini.success { border-left: 3px solid #22c55e; }
        .stat-mini.success i { background: #dcfce7; color: #16a34a; }
        .stat-mini.info { border-left: 3px solid #3b82f6; }
        .stat-mini.info i { background: #dbeafe; color: #2563eb; }
        .stat-mini .stat-value { font-size: 1.1rem; font-weight: 700; color: #1e293b; }
        .stat-mini .stat-label { font-size: 0.75rem; color: #64748b; }

        .report-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 1.5rem; }

        .card { background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; margin-bottom: 1.5rem; }
        .card-header { padding: 1rem 1.25rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; }
        .card-header h3 { margin: 0; font-size: 0.95rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }
        .card-body { padding: 1.25rem; }

        .side-cards .card { margin-bottom: 1rem; }
        .side-cards .card:last-child { margin-bottom: 0; }

        .table-responsive { overflow-x: auto; }
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 0.75rem 1rem; text-align: left; border-bottom: 1px solid #f1f5f9; font-size: 0.85rem; }
        .data-table th { background: #f8fafc; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; }
        .data-table tbody tr:hover { background: #f8fafc; }

        .rank-badge { width: 24px; height: 24px; border-radius: 50%; background: #f1f5f9; display: flex; align-items: center; justify-content: center; font-size: 0.75rem; font-weight: 600; color: #64748b; }
        .rank-badge.top { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; }

        .buyer-name { font-weight: 500; color: #1e293b; }
        .buyer-phone { font-size: 0.8rem; color: #64748b; }
        .text-success { color: #16a34a; }
        .text-warning { color: #d97706; }

        .distribution-item { margin-bottom: 0.75rem; }
        .dist-label { display: flex; justify-content: space-between; font-size: 0.8rem; margin-bottom: 0.25rem; }
        .dist-bar { height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; }
        .dist-fill { height: 100%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 4px; }

        .recent-list { }
        .recent-item { display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0; border-bottom: 1px solid #f1f5f9; text-decoration: none; }
        .recent-item:last-child { border-bottom: none; }
        .recent-avatar { width: 36px; height: 36px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 0.75rem; font-weight: 600; }
        .recent-name { font-weight: 500; color: #1e293b; font-size: 0.85rem; }
        .recent-meta { font-size: 0.75rem; color: #64748b; }

        .empty-row td { padding: 2rem; }
        .empty-state { text-align: center; color: #94a3b8; }
        .empty-state i { font-size: 2rem; margin-bottom: 0.5rem; }

        @media print {
            body { background: white; }
            .header-actions { display: none; }
            .sidebar, .top-header { display: none; }
            .main-content { margin-left: 0; padding: 0; }
            .card { box-shadow: none; border: 1px solid #e2e8f0; }
        }

        @media (max-width: 992px) {
            .report-grid { grid-template-columns: 1fr; }
        }

        @media (max-width: 768px) {
            .stats-row { flex-direction: column; }
        }
    </style>
</body>
</html>
