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

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

// Get customer statistics
$statsQuery = "SELECT 
    COUNT(*) as TotalCustomers,
    COUNT(CASE WHEN CustomerType = 'Retail' THEN 1 END) as RetailCustomers,
    COUNT(CASE WHEN CustomerType = 'Shop' THEN 1 END) as ShopCustomers,
    COUNT(CASE WHEN CreatedDate >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as NewCustomersThisMonth,
    COUNT(CASE WHEN CreatedDate >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as NewCustomersThisWeek
    FROM tblcustomers WHERE IsActive = 1";
$statsResult = mysqli_query($con, $statsQuery);
$stats = mysqli_fetch_assoc($statsResult);

// Get area-wise customer distribution
$areaStatsQuery = "SELECT Area, COUNT(*) as CustomerCount, CustomerType
                   FROM tblcustomers 
                   WHERE IsActive = 1 
                   GROUP BY Area, CustomerType 
                   ORDER BY CustomerCount DESC";
$areaStatsResult = mysqli_query($con, $areaStatsQuery);

// Get monthly customer registration trend (last 12 months)
$monthlyTrendQuery = "SELECT 
    DATE_FORMAT(CreatedDate, '%Y-%m') as Month,
    COUNT(*) as CustomerCount,
    CustomerType
    FROM tblcustomers 
    WHERE IsActive = 1 AND CreatedDate >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT(CreatedDate, '%Y-%m'), CustomerType
    ORDER BY Month DESC";
$monthlyTrendResult = mysqli_query($con, $monthlyTrendQuery);

// Get recent customers
$recentCustomersQuery = "SELECT c.*, u.FullName as CreatedByName 
                        FROM tblcustomers c 
                        LEFT JOIN tblusers u ON c.CreatedBy = u.ID 
                        WHERE c.IsActive = 1 
                        ORDER BY c.CreatedDate DESC 
                        LIMIT 10";
$recentCustomersResult = mysqli_query($con, $recentCustomersQuery);

// Prepare data for charts
$areaData = [];
$monthlyData = [];

while ($row = mysqli_fetch_assoc($areaStatsResult)) {
    $areaData[] = $row;
}

mysqli_data_seek($monthlyTrendResult, 0);
while ($row = mysqli_fetch_assoc($monthlyTrendResult)) {
    $monthlyData[] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Customer Reports | Mariyappa Nadar Ricemill</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .chart-container {
            position: relative;
            height: 250px;
        }
        .stats-card {
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .stats-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        .card-body { padding: 1rem; }
        .card-header { padding: 0.75rem 1rem; }
        .table td, .table th { padding: 0.5rem; }
        .icon-circle { 
            width: 35px; 
            height: 35px; 
            border-radius: 50%; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
        }
        .small { font-size: 0.85rem; }
        
        @media (max-width: 768px) {
            .chart-container { height: 200px; }
            .card-body, .card-header { padding: 0.75rem; }
            .icon-circle { width: 30px; height: 30px; }
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Page Heading -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">
                            <i class="fas fa-chart-line text-primary mr-2"></i>
                            Customer Analytics & Reports
                        </h1>
                        <div class="d-none d-lg-inline-block">
                            <a href="customer-management.php" class="btn btn-primary">
                                <i class="fas fa-users mr-2"></i>Manage Customers
                            </a>
                        </div>
                    </div>

                    <!-- Overview Statistics -->
                    <div class="row mb-3">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card stats-card border-left-primary shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                                Total Customers</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['TotalCustomers']); ?>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-users fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card stats-card border-left-success shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                Retail Customers</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['RetailCustomers']); ?>
                                            </div>
                                            <div class="text-xs text-muted">
                                                <?php echo $stats['TotalCustomers'] > 0 ? round(($stats['RetailCustomers'] / $stats['TotalCustomers']) * 100, 1) : 0; ?>% of total
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-user fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card stats-card border-left-info shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                                Shop Customers</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['ShopCustomers']); ?>
                                            </div>
                                            <div class="text-xs text-muted">
                                                <?php echo $stats['TotalCustomers'] > 0 ? round(($stats['ShopCustomers'] / $stats['TotalCustomers']) * 100, 1) : 0; ?>% of total
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-store fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card stats-card border-left-warning shadow h-100 py-2">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                                New This Month</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                                <?php echo number_format($stats['NewCustomersThisMonth']); ?>
                                            </div>
                                            <div class="text-xs text-muted">
                                                <?php echo number_format($stats['NewCustomersThisWeek']); ?> this week
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-user-plus fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Charts Row -->
                    <div class="row">
                        <!-- Customer Type Distribution -->
                        <div class="col-xl-4 col-lg-5">
                            <div class="card shadow mb-3">
                                <div class="card-header">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-chart-pie mr-2"></i>Customer Type Distribution
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container">
                                        <canvas id="customerTypeChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Monthly Registration Trend -->
                        <div class="col-xl-8 col-lg-7">
                            <div class="card shadow mb-3">
                                <div class="card-header">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-chart-line mr-2"></i>Monthly Registration Trend (Last 12 Months)
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container">
                                        <canvas id="monthlyTrendChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Area Distribution and Recent Customers -->
                    <div class="row">
                        <!-- Area-wise Distribution -->
                        <div class="col-xl-8 col-lg-7">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-map-marker-alt mr-2"></i>Area-wise Customer Distribution
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead class="thead-light">
                                                <tr>
                                                    <th>Area</th>
                                                    <th>Retail Customers</th>
                                                    <th>Shop Customers</th>
                                                    <th>Total</th>
                                                    <th>Percentage</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                // Group area data by area
                                                $areaGroups = [];
                                                foreach ($areaData as $row) {
                                                    if (!isset($areaGroups[$row['Area']])) {
                                                        $areaGroups[$row['Area']] = ['Retail' => 0, 'Shop' => 0];
                                                    }
                                                    $areaGroups[$row['Area']][$row['CustomerType']] = $row['CustomerCount'];
                                                }
                                                
                                                // Sort by total customers
                                                uasort($areaGroups, function($a, $b) {
                                                    return ($b['Retail'] + $b['Shop']) - ($a['Retail'] + $a['Shop']);
                                                });
                                                
                                                foreach ($areaGroups as $area => $counts):
                                                    $total = $counts['Retail'] + $counts['Shop'];
                                                    $percentage = $stats['TotalCustomers'] > 0 ? round(($total / $stats['TotalCustomers']) * 100, 1) : 0;
                                                ?>
                                                <tr>
                                                    <td><strong><?php echo htmlspecialchars($area); ?></strong></td>
                                                    <td>
                                                        <span class="badge badge-success"><?php echo $counts['Retail']; ?></span>
                                                    </td>
                                                    <td>
                                                        <span class="badge badge-info"><?php echo $counts['Shop']; ?></span>
                                                    </td>
                                                    <td><strong><?php echo $total; ?></strong></td>
                                                    <td>
                                                        <div class="progress" style="height: 20px;">
                                                            <div class="progress-bar bg-primary" role="progressbar" 
                                                                 style="width: <?php echo $percentage; ?>%">
                                                                <?php echo $percentage; ?>%
                                                            </div>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Recent Customers -->
                        <div class="col-xl-4 col-lg-5">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-clock mr-2"></i>Recent Customers
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <?php while($customer = mysqli_fetch_assoc($recentCustomersResult)): ?>
                                    <div class="d-flex align-items-center mb-3">
                                        <div class="mr-3">
                                            <div class="icon-circle bg-<?php echo $customer['CustomerType'] == 'Retail' ? 'success' : 'info'; ?>">
                                                <i class="fas <?php echo $customer['CustomerType'] == 'Retail' ? 'fa-user' : 'fa-store'; ?> text-white"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1">
                                            <div class="small font-weight-bold">
                                                <?php echo htmlspecialchars($customer['CustomerName']); ?>
                                            </div>
                                            <div class="small text-gray-500">
                                                <?php echo $customer['Mobile']; ?> • <?php echo htmlspecialchars($customer['Area']); ?>
                                            </div>
                                            <div class="small text-gray-400">
                                                <?php echo date('M j, Y', strtotime($customer['CreatedDate'])); ?>
                                            </div>
                                        </div>
                                        <div>
                                            <span class="badge badge-<?php echo $customer['CustomerType'] == 'Retail' ? 'success' : 'info'; ?> badge-sm">
                                                <?php echo $customer['CustomerType']; ?>
                                            </span>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                    <div class="text-center">
                                        <a href="customer-management.php" class="btn btn-sm btn-primary">
                                            <i class="fas fa-eye mr-1"></i>View All Customers
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
                <!-- /.container-fluid -->
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>

    <?php include_once('includes/footer2.php');?>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="js/quick-filters.js"></script>

    <script>
        // Customer Type Distribution Chart
        const customerTypeCtx = document.getElementById('customerTypeChart').getContext('2d');
        new Chart(customerTypeCtx, {
            type: 'doughnut',
            data: {
                labels: ['Retail Customers', 'Shop Customers'],
                datasets: [{
                    data: [<?php echo $stats['RetailCustomers']; ?>, <?php echo $stats['ShopCustomers']; ?>],
                    backgroundColor: ['#1cc88a', '#36b9cc'],
                    hoverBackgroundColor: ['#17a673', '#2c9faf'],
                    borderWidth: 2,
                    borderColor: '#ffffff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            usePointStyle: true
                        }
                    }
                },
                cutout: '60%'
            }
        });

        // Monthly Trend Chart
        const monthlyTrendCtx = document.getElementById('monthlyTrendChart').getContext('2d');
        
        // Process monthly data
        const monthlyData = <?php echo json_encode($monthlyData); ?>;
        const months = [];
        const retailData = [];
        const shopData = [];
        
        // Get unique months and initialize data
        const monthSet = new Set();
        monthlyData.forEach(item => monthSet.add(item.Month));
        const sortedMonths = Array.from(monthSet).sort().slice(-12);
        
        sortedMonths.forEach(month => {
            months.push(new Date(month + '-01').toLocaleDateString('en-US', { year: 'numeric', month: 'short' }));
            
            const retailCount = monthlyData.find(item => item.Month === month && item.CustomerType === 'Retail')?.CustomerCount || 0;
            const shopCount = monthlyData.find(item => item.Month === month && item.CustomerType === 'Shop')?.CustomerCount || 0;
            
            retailData.push(retailCount);
            shopData.push(shopCount);
        });

        new Chart(monthlyTrendCtx, {
            type: 'line',
            data: {
                labels: months,
                datasets: [{
                    label: 'Retail Customers',
                    data: retailData,
                    borderColor: '#1cc88a',
                    backgroundColor: 'rgba(28, 200, 138, 0.1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.3
                }, {
                    label: 'Shop Customers',
                    data: shopData,
                    borderColor: '#36b9cc',
                    backgroundColor: 'rgba(54, 185, 204, 0.1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0
                        }
                    }
                },
                interaction: {
                    intersect: false,
                    mode: 'index'
                }
            }
        });
    </script>
</body>
</html>
