<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

if (!isLoggedIn() || getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$buyerSystem = new BuyerSystem($database, $currentUserId);

if (!$buyerSystem->hasPermission('view_analytics')) {
    $_SESSION['flash_message'] = 'Analytics is only available for verified premium buyers';
    $_SESSION['flash_type'] = 'warning';
    header('Location: ' . APP_URL . '/buyer/dashboard.php');
    exit();
}

// Get date range
$fromDate = $_GET['from'] ?? date('Y-m-01');
$toDate = $_GET['to'] ?? date('Y-m-d');

// Spending by category
$sql = "SELECT p.category, SUM(o.total_amount) as total, COUNT(o.id) as count
        FROM orders o
        INNER JOIN products p ON o.product_id = p.id
        WHERE o.buyer_id = ? AND o.created_at BETWEEN ? AND ?
        GROUP BY p.category
        ORDER BY total DESC";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId, $fromDate, $toDate]);
$spendingByCategory = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Monthly spending trend
$sql = "SELECT DATE_FORMAT(created_at, '%Y-%m') as month, 
               SUM(total_amount) as total,
               COUNT(*) as orders
        FROM orders
        WHERE buyer_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
        ORDER BY month ASC";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$monthlyTrend = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Top suppliers
$topSuppliers = $buyerSystem->getSuppliers();
$topSuppliers = array_slice($topSuppliers, 0, 5);

// Order status breakdown
$sql = "SELECT status, COUNT(*) as count, SUM(total_amount) as total
        FROM orders
        WHERE buyer_id = ? AND created_at BETWEEN ? AND ?
        GROUP BY status";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId, $fromDate, $toDate]);
$ordersByStatus = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Analytics Dashboard';
$breadcrumbs = [['title' => 'Analytics', 'url' => '']];

require_once __DIR__ . '/includes/base.php';
renderBuyerHeader($pageTitle, $breadcrumbs);
?>

<style>
    .analytics-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        margin-bottom: 1.5rem;
    }
    .metric-card {
        text-align: center;
        padding: 1.5rem;
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
        border-radius: 12px;
    }
    .metric-value {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 0.5rem;
    }
</style>

<!-- Date Filter -->
<div class="card shadow-sm mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-4">
                <label class="form-label">From Date</label>
                <input type="date" name="from" class="form-control" value="<?php echo $fromDate; ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label">To Date</label>
                <input type="date" name="to" class="form-control" value="<?php echo $toDate; ?>">
            </div>
            <div class="col-md-4">
                <label class="form-label">&nbsp;</label>
                <button type="submit" class="btn btn-primary w-100">
                    <i class="bi bi-funnel me-2"></i>Apply Filter
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Key Metrics -->
<div class="row mb-4">
    <?php
    $stats = $buyerSystem->getStatistics();
    $metrics = [
        ['label' => 'Total Orders', 'value' => number_format($stats['total_orders']), 'icon' => 'cart-check'],
        ['label' => 'Total Spent', 'value' => formatCurrency($stats['total_spent']), 'icon' => 'cash-coin'],
        ['label' => 'Avg Order', 'value' => formatCurrency($stats['avg_order_value']), 'icon' => 'graph-up'],
        ['label' => 'Suppliers', 'value' => number_format($stats['active_suppliers']), 'icon' => 'people']
    ];
    foreach ($metrics as $metric):
    ?>
    <div class="col-md-3 col-sm-6">
        <div class="metric-card">
            <i class="bi bi-<?php echo $metric['icon']; ?>" style="font-size: 2rem;"></i>
            <div class="metric-value"><?php echo $metric['value']; ?></div>
            <div><?php echo $metric['label']; ?></div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<div class="row">
    <!-- Monthly Trend Chart -->
    <div class="col-lg-8">
        <div class="analytics-card">
            <h5 class="mb-4"><i class="bi bi-graph-up me-2"></i>Spending Trend (Last 12 Months)</h5>
            <canvas id="monthlyTrendChart" height="80"></canvas>
        </div>
        
        <!-- Spending by Category -->
        <div class="analytics-card">
            <h5 class="mb-4"><i class="bi bi-pie-chart me-2"></i>Spending by Category</h5>
            <?php if (empty($spendingByCategory)): ?>
                <p class="text-muted text-center py-4">No data available for selected period</p>
            <?php else: ?>
                <div class="row">
                    <div class="col-md-6">
                        <canvas id="categoryChart"></canvas>
                    </div>
                    <div class="col-md-6">
                        <div class="list-group">
                            <?php foreach ($spendingByCategory as $cat): ?>
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                <div>
                                    <strong><?php echo ucfirst(str_replace('_', ' ', $cat['category'])); ?></strong>
                                    <br><small class="text-muted"><?php echo $cat['count']; ?> orders</small>
                                </div>
                                <span class="badge bg-primary rounded-pill">
                                    <?php echo formatCurrency($cat['total']); ?>
                                </span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Sidebar -->
    <div class="col-lg-4">
        <!-- Order Status -->
        <div class="analytics-card">
            <h5 class="mb-3"><i class="bi bi-clipboard-data me-2"></i>Order Status</h5>
            <canvas id="statusChart"></canvas>
        </div>
        
        <!-- Top Suppliers -->
        <div class="analytics-card">
            <h5 class="mb-3"><i class="bi bi-star me-2"></i>Top Suppliers</h5>
            <?php if (empty($topSuppliers)): ?>
                <p class="text-muted text-center py-3">No suppliers yet</p>
            <?php else: ?>
                <?php foreach ($topSuppliers as $i => $supplier): ?>
                <div class="d-flex align-items-center mb-3">
                    <div class="me-3">
                        <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" 
                             style="width: 40px; height: 40px;">
                            <strong><?php echo $i + 1; ?></strong>
                        </div>
                    </div>
                    <div class="flex-grow-1">
                        <strong class="d-block"><?php echo htmlspecialchars($supplier['full_name']); ?></strong>
                        <small class="text-muted"><?php echo formatCurrency($supplier['total_spent']); ?></small>
                    </div>
                    <div>
                        <?php echo getRatingStars($supplier['avg_rating']); ?>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Monthly Trend Chart
const trendCtx = document.getElementById('monthlyTrendChart').getContext('2d');
new Chart(trendCtx, {
    type: 'line',
    data: {
        labels: <?php echo json_encode(array_column($monthlyTrend, 'month')); ?>,
        datasets: [{
            label: 'Spending',
            data: <?php echo json_encode(array_column($monthlyTrend, 'total')); ?>,
            borderColor: '#3b82f6',
            backgroundColor: 'rgba(59, 130, 246, 0.1)',
            tension: 0.4,
            fill: true
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: value => 'UGX ' + value.toLocaleString()
                }
            }
        }
    }
});

// Category Chart
<?php if (!empty($spendingByCategory)): ?>
const categoryCtx = document.getElementById('categoryChart').getContext('2d');
new Chart(categoryCtx, {
    type: 'doughnut',
    data: {
        labels: <?php echo json_encode(array_map(fn($c) => ucfirst(str_replace('_', ' ', $c['category'])), $spendingByCategory)); ?>,
        datasets: [{
            data: <?php echo json_encode(array_column($spendingByCategory, 'total')); ?>,
            backgroundColor: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899']
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { position: 'bottom' }
        }
    }
});
<?php endif; ?>

// Status Chart
const statusCtx = document.getElementById('statusChart').getContext('2d');
new Chart(statusCtx, {
    type: 'pie',
    data: {
        labels: <?php echo json_encode(array_column($ordersByStatus, 'status')); ?>,
        datasets: [{
            data: <?php echo json_encode(array_column($ordersByStatus, 'count')); ?>,
            backgroundColor: ['#f59e0b', '#3b82f6', '#10b981', '#6b7280', '#ef4444']
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { position: 'bottom' }
        }
    }
});
</script>

<?php renderBuyerFooter(); ?>