<?php
require_once 'config/database.php';
secureSessionStart();
requireLogin();

$conn = getConnection();
$message = '';
$message_type = '';

// Get filter parameters
$date_range = isset($_GET['date_range']) ? $_GET['date_range'] : 'this_month';
$custom_from = isset($_GET['from_date']) ? $_GET['from_date'] : '';
$custom_to = isset($_GET['to_date']) ? $_GET['to_date'] : '';
$package_filter = isset($_GET['package']) ? intval($_GET['package']) : 0;
$user_id_filter = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$payment_status = isset($_GET['payment_status']) ? intval($_GET['payment_status']) : -1;

// Set date range based on selection
$from_date = '';
$to_date = date('Y-m-d');

switch ($date_range) {
    case 'today':
        $from_date = date('Y-m-d');
        break;
    case 'yesterday':
        $from_date = date('Y-m-d', strtotime('-1 day'));
        $to_date = $from_date;
        break;
    case 'this_week':
        $from_date = date('Y-m-d', strtotime('monday this week'));
        break;
    case 'last_week':
        $from_date = date('Y-m-d', strtotime('monday last week'));
        $to_date = date('Y-m-d', strtotime('sunday last week'));
        break;
    case 'this_month':
        $from_date = date('Y-m-01');
        break;
    case 'last_month':
        $from_date = date('Y-m-01', strtotime('first day of last month'));
        $to_date = date('Y-m-t', strtotime('last day of last month'));
        break;
    case 'this_quarter':
        $quarter = ceil(date('n') / 3);
        $from_date = date('Y-' . (($quarter - 1) * 3 + 1) . '-01');
        break;
    case 'last_quarter':
        $quarter = ceil(date('n') / 3) - 1;
        if ($quarter < 1) $quarter = 4;
        $year = $quarter == 4 ? date('Y') - 1 : date('Y');
        $from_date = date($year . '-' . (($quarter - 1) * 3 + 1) . '-01');
        $to_date = date($year . '-' . ($quarter * 3) . '-30');
        break;
    case 'this_year':
        $from_date = date('Y-01-01');
        break;
    case 'last_year':
        $from_date = date('Y-01-01', strtotime('-1 year'));
        $to_date = date('Y-12-31', strtotime('-1 year'));
        break;
    case 'custom':
        if ($custom_from) $from_date = $custom_from;
        if ($custom_to) $to_date = $custom_to;
        break;
}

// Build WHERE clause for sales data
$where = [];

// PIN Requests (sales)
$pr_where = ["1=1"]; // Start with true condition

if ($from_date && $to_date) {
    $pr_where[] = "DATE(pr.created_at) BETWEEN '$from_date' AND '$to_date'";
}

if ($package_filter > 0) {
    $pr_where[] = "pr.package_id = $package_filter";
}

if ($user_id_filter > 0) {
    $pr_where[] = "pr.user_id = $user_id_filter";
}

if ($payment_status >= 0) {
    $pr_where[] = "pr.payment_status = $payment_status";
}

$pr_where_clause = "WHERE " . implode(" AND ", $pr_where);

// PINs (used for registrations) - FIXED: Using correct column names from your schema
$pin_where = ["p.used_by IS NOT NULL"]; // Used pins are those with used_by not null

if ($from_date && $to_date) {
    $pin_where[] = "DATE(p.used_at) BETWEEN '$from_date' AND '$to_date'";
}

if ($package_filter > 0) {
    $pin_where[] = "p.package_id = $package_filter";
}

$pin_where_clause = "WHERE " . implode(" AND ", $pin_where);

// Users (registrations)
$user_where = ["1=1"];

if ($from_date && $to_date) {
    $user_where[] = "DATE(created_at) BETWEEN '$from_date' AND '$to_date'";
}

if ($package_filter > 0) {
    $user_where[] = "package_id = $package_filter";
}

$user_where_clause = "WHERE " . implode(" AND ", $user_where);

// Get sales summary with error handling
$summary = [];

// Total sales amount (from PIN requests with payment_status = 1)
$query = "SELECT COALESCE(SUM(total_amount), 0) as total_sales, COUNT(*) as total_requests 
          FROM pin_request pr 
          $pr_where_clause AND pr.payment_status = 1";
$result = mysqli_query($conn, $query);
if (!$result) {
    die("Query failed: " . mysqli_error($conn) . " in query: " . $query);
}
$row = mysqli_fetch_assoc($result);
$summary['total_sales'] = $row['total_sales'] ?? 0;
$summary['total_requests'] = $row['total_requests'] ?? 0;

// Paid sales amount (for conversion rate)
$query = "SELECT COALESCE(SUM(total_amount), 0) as paid_sales 
          FROM pin_request pr 
          $pr_where_clause AND pr.payment_status = 1";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$summary['paid_sales'] = $row['paid_sales'] ?? 0;

// Pending payments
$query = "SELECT COALESCE(SUM(total_amount), 0) as pending_amount, COUNT(*) as pending_count 
          FROM pin_request pr 
          $pr_where_clause AND pr.payment_status = 0";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$summary['pending_amount'] = $row['pending_amount'] ?? 0;
$summary['pending_count'] = $row['pending_count'] ?? 0;

// Completed registrations (users joined)
$query = "SELECT COUNT(*) as new_users FROM users u $user_where_clause";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$summary['new_users'] = $row['new_users'] ?? 0;

// Pins sold - FIXED: Using correct column names
$query = "SELECT COUNT(*) as pins_sold, COALESCE(SUM(package_id), 0) as pins_value 
          FROM pin p 
          $pin_where_clause";
$result = mysqli_query($conn, $query);
if (!$result) {
    die("Query failed: " . mysqli_error($conn) . " in query: " . $query);
}
$row = mysqli_fetch_assoc($result);
$summary['pins_sold'] = $row['pins_sold'] ?? 0;
$summary['pins_value'] = $row['pins_value'] ?? 0;

// Average order value
$summary['avg_order'] = $summary['total_requests'] > 0 ? $summary['total_sales'] / $summary['total_requests'] : 0;

// Get daily sales data for chart
$daily_sales = [];
$daily_query = "SELECT DATE(created_at) as date, 
                       COUNT(*) as request_count,
                       COALESCE(SUM(CASE WHEN payment_status = 1 THEN total_amount ELSE 0 END), 0) as paid_amount,
                       COALESCE(SUM(CASE WHEN payment_status = 0 THEN total_amount ELSE 0 END), 0) as pending_amount
                FROM pin_request pr
                WHERE DATE(created_at) BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE()
                GROUP BY DATE(created_at)
                ORDER BY date ASC";
$daily_result = mysqli_query($conn, $daily_query);
if ($daily_result) {
    while ($row = mysqli_fetch_assoc($daily_result)) {
        $daily_sales[] = $row;
    }
}

// Get package-wise sales
$package_sales = [];
$package_query = "SELECT 
                    package_id,
                    package_name,
                    COUNT(*) as request_count,
                    COALESCE(SUM(total_amount), 0) as total_amount,
                    COALESCE(SUM(CASE WHEN payment_status = 1 THEN total_amount ELSE 0 END), 0) as paid_amount
                  FROM pin_request pr
                  $pr_where_clause
                  GROUP BY package_id, package_name
                  ORDER BY total_amount DESC";
$package_result = mysqli_query($conn, $package_query);
if ($package_result) {
    while ($row = mysqli_fetch_assoc($package_result)) {
        $package_sales[] = $row;
    }
}

// Get top sellers (users with most PIN requests)
$top_sellers = [];
$seller_query = "SELECT 
                    pr.user_id,
                    u.name,
                    u.mobile,
                    COUNT(*) as request_count,
                    COALESCE(SUM(pr.total_amount), 0) as total_sales,
                    COALESCE(SUM(CASE WHEN pr.payment_status = 1 THEN pr.total_amount ELSE 0 END), 0) as paid_sales
                  FROM pin_request pr
                  LEFT JOIN users u ON pr.user_id = u.user_id
                  $pr_where_clause
                  GROUP BY pr.user_id
                  ORDER BY total_sales DESC
                  LIMIT 10";
$seller_result = mysqli_query($conn, $seller_query);
if ($seller_result) {
    while ($row = mysqli_fetch_assoc($seller_result)) {
        $top_sellers[] = $row;
    }
}

// Get payment status breakdown
$payment_stats = [];
$payment_query = "SELECT 
                    payment_status,
                    COUNT(*) as count,
                    COALESCE(SUM(total_amount), 0) as total
                  FROM pin_request pr
                  $pr_where_clause
                  GROUP BY payment_status";
$payment_result = mysqli_query($conn, $payment_query);
if ($payment_result) {
    while ($row = mysqli_fetch_assoc($payment_result)) {
        $payment_stats[$row['payment_status']] = $row;
    }
}

// Get all users for filter dropdown
$users = mysqli_query($conn, "SELECT user_id, name FROM users ORDER BY name LIMIT 1000");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Sales Report - MLM System</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">
    
    <!-- Select2 -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <style>
        * {
            font-family: 'Inter', sans-serif;
        }
        
        .report-header {
            background: linear-gradient(135deg, #4154f1 0%, #6f42c1 100%);
            color: white;
            padding: 30px;
            border-radius: 20px;
            margin-bottom: 30px;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
        }
        
        .stat-card.sales::before { background: linear-gradient(180deg, #28a745, #20c997); }
        .stat-card.orders::before { background: linear-gradient(180deg, #4154f1, #6f42c1); }
        .stat-card.users::before { background: linear-gradient(180deg, #17a2b8, #0dcaf0); }
        .stat-card.pins::before { background: linear-gradient(180deg, #ffc107, #fd7e14); }
        .stat-card.pending::before { background: linear-gradient(180deg, #dc3545, #fd7e14); }
        .stat-card.avg::before { background: linear-gradient(180deg, #6f42c1, #d63384); }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.05);
        }
        
        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        .stat-icon.sales { background: rgba(40, 167, 69, 0.1); color: #28a745; }
        .stat-icon.orders { background: rgba(65, 84, 241, 0.1); color: #4154f1; }
        .stat-icon.users { background: rgba(23, 162, 184, 0.1); color: #17a2b8; }
        .stat-icon.pins { background: rgba(255, 193, 7, 0.1); color: #ffc107; }
        .stat-icon.pending { background: rgba(220, 53, 69, 0.1); color: #dc3545; }
        .stat-icon.avg { background: rgba(111, 66, 193, 0.1); color: #6f42c1; }
        
        .stat-value {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 5px;
            color: #1a1a1a;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 14px;
            font-weight: 500;
        }
        
        .filter-card {
            background: white;
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
        }
        
        .chart-container {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
        }
        
        .chart-box {
            position: relative;
            height: 300px;
            width: 100%;
        }
        
        .table-container {
            background: white;
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
        }
        
        .badge-status {
            padding: 6px 12px;
            border-radius: 30px;
            font-weight: 500;
            font-size: 12px;
        }
        
        .badge-status.paid {
            background: rgba(40, 167, 69, 0.15);
            color: #28a745;
        }
        
        .badge-status.pending {
            background: rgba(255, 193, 7, 0.15);
            color: #856404;
        }
        
        .badge-status.rejected {
            background: rgba(220, 53, 69, 0.15);
            color: #dc3545;
        }
        
        .badge-package {
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 500;
        }
        
        .badge-package.basic { background: rgba(255, 193, 7, 0.15); color: #856404; }
        .badge-package.premium { background: rgba(111, 66, 193, 0.15); color: #563d7c; }
        
        .export-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            z-index: 1000;
            width: 60px;
            height: 60px;
            border-radius: 30px;
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            box-shadow: 0 4px 20px rgba(40, 167, 69, 0.3);
            cursor: pointer;
            transition: all 0.3s;
            border: none;
        }
        
        .export-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 25px rgba(40, 167, 69, 0.4);
        }
        
        .export-menu {
            position: fixed;
            bottom: 100px;
            right: 30px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            padding: 10px 0;
            display: none;
            z-index: 999;
        }
        
        .export-menu.show {
            display: block;
        }
        
        .export-menu a {
            display: block;
            padding: 10px 20px;
            color: #333;
            text-decoration: none;
            transition: all 0.2s;
        }
        
        .export-menu a:hover {
            background: #f8f9fa;
            color: #28a745;
        }
        
        .kpi-card {
            text-align: center;
            padding: 20px;
        }
        
        .kpi-value {
            font-size: 36px;
            font-weight: 700;
            color: #4154f1;
        }
        
        .kpi-label {
            color: #6c757d;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    <?php include 'includes/sidebar.php'; ?>

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>Sales Report</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                    <li class="breadcrumb-item active">Sales Report</li>
                </ol>
            </nav>
        </div>

        <section class="section">
            <!-- Report Header -->
            <div class="report-header">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h2><i class="fas fa-chart-line me-3"></i>Sales Performance Dashboard</h2>
                        <p class="mb-0 opacity-75">Comprehensive sales analytics and reporting for period: 
                            <strong><?php echo $from_date ? date('d M Y', strtotime($from_date)) : 'Start'; ?> - <?php echo $to_date ? date('d M Y', strtotime($to_date)) : 'Now'; ?></strong>
                        </p>
                    </div>
                    <div class="col-md-4 text-end">
                        <div class="btn-group">
                            <button class="btn btn-light btn-sm" onclick="window.location.href='?date_range=today'">Today</button>
                            <button class="btn btn-light btn-sm" onclick="window.location.href='?date_range=yesterday'">Yesterday</button>
                            <button class="btn btn-light btn-sm" onclick="window.location.href='?date_range=this_week'">This Week</button>
                            <button class="btn btn-light btn-sm" onclick="window.location.href='?date_range=this_month'">This Month</button>
                            <button class="btn btn-light btn-sm" onclick="window.location.href='?date_range=this_year'">This Year</button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Statistics Cards -->
            <div class="stats-grid">
                <div class="stat-card sales">
                    <div class="stat-icon sales">
                        <i class="fas fa-rupee-sign"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($summary['total_sales'], 2); ?></div>
                    <div class="stat-label">Total Sales</div>
                    <small class="text-muted"><?php echo $summary['total_requests']; ?> transactions</small>
                </div>
                
                <div class="stat-card orders">
                    <div class="stat-icon orders">
                        <i class="fas fa-shopping-cart"></i>
                    </div>
                    <div class="stat-value"><?php echo $summary['total_requests']; ?></div>
                    <div class="stat-label">Total Orders</div>
                    <small class="text-muted">PIN requests</small>
                </div>
                
                <div class="stat-card users">
                    <div class="stat-icon users">
                        <i class="fas fa-user-plus"></i>
                    </div>
                    <div class="stat-value"><?php echo $summary['new_users']; ?></div>
                    <div class="stat-label">New Registrations</div>
                    <small class="text-muted">using purchased PINs</small>
                </div>
                
                <div class="stat-card pins">
                    <div class="stat-icon pins">
                        <i class="fas fa-key"></i>
                    </div>
                    <div class="stat-value"><?php echo $summary['pins_sold']; ?></div>
                    <div class="stat-label">PINs Sold</div>
                    <small class="text-muted">₹<?php echo number_format($summary['pins_value'], 2); ?> value</small>
                </div>
                
                <div class="stat-card pending">
                    <div class="stat-icon pending">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($summary['pending_amount'], 2); ?></div>
                    <div class="stat-label">Pending Payments</div>
                    <small class="text-muted"><?php echo $summary['pending_count']; ?> orders</small>
                </div>
                
                <div class="stat-card avg">
                    <div class="stat-icon avg">
                        <i class="fas fa-calculator"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($summary['avg_order'], 2); ?></div>
                    <div class="stat-label">Average Order</div>
                    <small class="text-muted">per transaction</small>
                </div>
            </div>
            
            <!-- Filter Card -->
            <div class="filter-card">
                <h5 class="mb-4"><i class="fas fa-filter me-2"></i>Filter Sales Data</h5>
                
                <form method="GET" class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label">Date Range</label>
                        <select name="date_range" class="form-select" onchange="toggleCustomDates(this.value)">
                            <option value="today" <?php echo $date_range == 'today' ? 'selected' : ''; ?>>Today</option>
                            <option value="yesterday" <?php echo $date_range == 'yesterday' ? 'selected' : ''; ?>>Yesterday</option>
                            <option value="this_week" <?php echo $date_range == 'this_week' ? 'selected' : ''; ?>>This Week</option>
                            <option value="last_week" <?php echo $date_range == 'last_week' ? 'selected' : ''; ?>>Last Week</option>
                            <option value="this_month" <?php echo $date_range == 'this_month' ? 'selected' : ''; ?>>This Month</option>
                            <option value="last_month" <?php echo $date_range == 'last_month' ? 'selected' : ''; ?>>Last Month</option>
                            <option value="this_quarter" <?php echo $date_range == 'this_quarter' ? 'selected' : ''; ?>>This Quarter</option>
                            <option value="last_quarter" <?php echo $date_range == 'last_quarter' ? 'selected' : ''; ?>>Last Quarter</option>
                            <option value="this_year" <?php echo $date_range == 'this_year' ? 'selected' : ''; ?>>This Year</option>
                            <option value="last_year" <?php echo $date_range == 'last_year' ? 'selected' : ''; ?>>Last Year</option>
                            <option value="custom" <?php echo $date_range == 'custom' ? 'selected' : ''; ?>>Custom Range</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2 custom-date" style="display: <?php echo $date_range == 'custom' ? 'block' : 'none'; ?>;">
                        <label class="form-label">From Date</label>
                        <input type="date" class="form-control" name="from_date" value="<?php echo $custom_from; ?>">
                    </div>
                    
                    <div class="col-md-2 custom-date" style="display: <?php echo $date_range == 'custom' ? 'block' : 'none'; ?>;">
                        <label class="form-label">To Date</label>
                        <input type="date" class="form-control" name="to_date" value="<?php echo $custom_to; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">Package</label>
                        <select name="package" class="form-select">
                            <option value="0">All Packages</option>
                            <option value="2500" <?php echo $package_filter == 2500 ? 'selected' : ''; ?>>₹2500 - Basic</option>
                            <option value="3500" <?php echo $package_filter == 3500 ? 'selected' : ''; ?>>₹3500 - Premium</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">User</label>
                        <select name="user_id" class="form-select user-select">
                            <option value="0">All Users</option>
                            <?php 
                            if ($users && mysqli_num_rows($users) > 0) {
                                mysqli_data_seek($users, 0);
                                while ($user = mysqli_fetch_assoc($users)): 
                                ?>
                                    <option value="<?php echo $user['user_id']; ?>" <?php echo $user_id_filter == $user['user_id'] ? 'selected' : ''; ?>>
                                        <?php echo $user['user_id']; ?> - <?php echo htmlspecialchars($user['name']); ?>
                                    </option>
                                <?php 
                                endwhile;
                            } 
                            ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">Payment Status</label>
                        <select name="payment_status" class="form-select">
                            <option value="-1">All Status</option>
                            <option value="1" <?php echo $payment_status == 1 ? 'selected' : ''; ?>>Paid</option>
                            <option value="0" <?php echo $payment_status == 0 ? 'selected' : ''; ?>>Pending</option>
                        </select>
                    </div>
                    
                    <div class="col-md-1 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- Charts Row -->
            <div class="row">
                <div class="col-md-8">
                    <div class="chart-container">
                        <h5 class="mb-3"><i class="fas fa-chart-line me-2"></i>Daily Sales Trend (Last 30 Days)</h5>
                        <div class="chart-box">
                            <canvas id="dailySalesChart"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="chart-container">
                        <h5 class="mb-3"><i class="fas fa-chart-pie me-2"></i>Package Distribution</h5>
                        <div class="chart-box">
                            <canvas id="packageChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- KPI Cards -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body kpi-card">
                            <div class="kpi-value"><?php echo $summary['total_requests']; ?></div>
                            <div class="kpi-label">Total Orders</div>
                            <div class="progress mt-2" style="height: 5px;">
                                <div class="progress-bar bg-primary" style="width: 100%"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body kpi-card">
                            <div class="kpi-value"><?php echo $summary['total_requests'] > 0 ? round(($summary['paid_sales'] / $summary['total_sales']) * 100, 1) : 0; ?>%</div>
                            <div class="kpi-label">Conversion Rate</div>
                            <div class="progress mt-2" style="height: 5px;">
                                <div class="progress-bar bg-success" style="width: <?php echo $summary['total_requests'] > 0 ? ($summary['paid_sales'] / $summary['total_sales']) * 100 : 0; ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body kpi-card">
                            <div class="kpi-value"><?php echo $summary['pins_sold']; ?></div>
                            <div class="kpi-label">PINs Sold</div>
                            <div class="progress mt-2" style="height: 5px;">
                                <div class="progress-bar bg-warning" style="width: <?php echo $summary['total_requests'] > 0 ? ($summary['pins_sold'] / $summary['total_requests']) * 100 : 0; ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="card">
                        <div class="card-body kpi-card">
                            <div class="kpi-value"><?php echo $summary['new_users']; ?></div>
                            <div class="kpi-label">New Registrations</div>
                            <div class="progress mt-2" style="height: 5px;">
                                <div class="progress-bar bg-info" style="width: <?php echo $summary['pins_sold'] > 0 ? ($summary['new_users'] / $summary['pins_sold']) * 100 : 0; ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Package Sales Table -->
            <div class="table-container">
                <h5 class="mb-4"><i class="fas fa-cubes me-2"></i>Package-wise Sales</h5>
                
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Package</th>
                                <th>Requests</th>
                                <th>Total Amount</th>
                                <th>Paid Amount</th>
                                <th>Pending Amount</th>
                                <th>Conversion</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($package_sales)): ?>
                                <?php foreach ($package_sales as $package): ?>
                                    <tr>
                                        <td>
                                            <span class="badge-package <?php echo $package['package_id'] == 2500 ? 'basic' : 'premium'; ?>">
                                                <?php echo htmlspecialchars($package['package_name'] ?: ($package['package_id'] == 2500 ? 'Basic Package' : 'Premium Package')); ?>
                                            </span>
                                        </td>
                                        <td><?php echo $package['request_count']; ?></td>
                                        <td class="fw-bold">₹<?php echo number_format($package['total_amount'], 2); ?></td>
                                        <td class="text-success">₹<?php echo number_format($package['paid_amount'], 2); ?></td>
                                        <td class="text-warning">₹<?php echo number_format($package['total_amount'] - $package['paid_amount'], 2); ?></td>
                                        <td>
                                            <?php $conv = $package['total_amount'] > 0 ? ($package['paid_amount'] / $package['total_amount']) * 100 : 0; ?>
                                            <div class="d-flex align-items-center">
                                                <div class="progress flex-grow-1 me-2" style="height: 5px;">
                                                    <div class="progress-bar bg-success" style="width: <?php echo $conv; ?>%"></div>
                                                </div>
                                                <small><?php echo round($conv, 1); ?>%</small>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-center py-4">No package sales data available for the selected period.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Top Sellers Table -->
            <div class="table-container">
                <h5 class="mb-4"><i class="fas fa-crown me-2"></i>Top Sellers</h5>
                
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Rank</th>
                                <th>User</th>
                                <th>Contact</th>
                                <th>Requests</th>
                                <th>Total Sales</th>
                                <th>Paid Sales</th>
                                <th>Performance</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            if (!empty($top_sellers)):
                                $rank = 1;
                                foreach ($top_sellers as $seller): 
                            ?>
                                <tr>
                                    <td>
                                        <?php if ($rank == 1): ?>
                                            <span class="badge bg-warning text-dark"><i class="fas fa-crown me-1"></i>#1</span>
                                        <?php elseif ($rank == 2): ?>
                                            <span class="badge bg-secondary">#2</span>
                                        <?php elseif ($rank == 3): ?>
                                            <span class="badge bg-danger">#3</span>
                                        <?php else: ?>
                                            #<?php echo $rank; ?>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="fw-bold"><?php echo htmlspecialchars($seller['name'] ?: 'N/A'); ?></div>
                                        <small class="text-muted">ID: <?php echo $seller['user_id']; ?></small>
                                    </td>
                                    <td><?php echo $seller['mobile'] ?: 'N/A'; ?></td>
                                    <td><?php echo $seller['request_count']; ?></td>
                                    <td class="fw-bold">₹<?php echo number_format($seller['total_sales'], 2); ?></td>
                                    <td class="text-success">₹<?php echo number_format($seller['paid_sales'], 2); ?></td>
                                    <td>
                                        <?php $perf = $seller['total_sales'] > 0 ? ($seller['paid_sales'] / $seller['total_sales']) * 100 : 0; ?>
                                        <div class="progress" style="height: 5px;">
                                            <div class="progress-bar bg-success" style="width: <?php echo $perf; ?>%"></div>
                                        </div>
                                        <small class="text-muted"><?php echo round($perf, 1); ?>% paid</small>
                                    </td>
                                </tr>
                            <?php 
                                    $rank++;
                                endforeach; 
                            else:
                            ?>
                                <tr>
                                    <td colspan="7" class="text-center py-4">No seller data available for the selected period.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>
    </main>
    
    <!-- Floating Export Button -->
    <button class="export-btn" onclick="toggleExportMenu()">
        <i class="fas fa-download"></i>
    </button>
    
    <div class="export-menu" id="exportMenu">
        <a href="#" onclick="exportReport('pdf'); return false;">
            <i class="fas fa-file-pdf me-2 text-danger"></i>Export as PDF
        </a>
        <a href="#" onclick="exportReport('excel'); return false;">
            <i class="fas fa-file-excel me-2 text-success"></i>Export as Excel
        </a>
        <a href="#" onclick="exportReport('csv'); return false;">
            <i class="fas fa-file-csv me-2 text-primary"></i>Export as CSV
        </a>
        <a href="#" onclick="window.print(); return false;">
            <i class="fas fa-print me-2 text-secondary"></i>Print Report
        </a>
    </div>

    <?php include 'includes/footer.php'; ?>

    <!-- Vendor JS Files -->
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/vendor/simple-datatables/simple-datatables.js"></script>
    <script src="assets/js/main.js"></script>
    
    <!-- jQuery and Plugins -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
    // Initialize Select2
    $(document).ready(function() {
        $('.user-select').select2({
            theme: 'bootstrap-5',
            placeholder: 'Search for a user...',
            allowClear: true,
            width: '100%'
        });
    });
    
    // Toggle custom date inputs
    function toggleCustomDates(value) {
        var customDates = document.querySelectorAll('.custom-date');
        if (value === 'custom') {
            customDates.forEach(el => el.style.display = 'block');
        } else {
            customDates.forEach(el => el.style.display = 'none');
        }
    }
    
    // Toggle export menu
    function toggleExportMenu() {
        document.getElementById('exportMenu').classList.toggle('show');
    }
    
    // Close export menu when clicking outside
    document.addEventListener('click', function(event) {
        var exportBtn = document.querySelector('.export-btn');
        var exportMenu = document.getElementById('exportMenu');
        if (!exportBtn.contains(event.target) && !exportMenu.contains(event.target)) {
            exportMenu.classList.remove('show');
        }
    });
    
    // Export function
    function exportReport(format) {
        var url = 'export-report.php?type=sales&format=' + format + '&<?php echo $_SERVER['QUERY_STRING']; ?>';
        window.open(url, '_blank');
        document.getElementById('exportMenu').classList.remove('show');
    }
    
    // Daily Sales Chart
    <?php if (!empty($daily_sales)): ?>
    const dailyCtx = document.getElementById('dailySalesChart').getContext('2d');
    const dailyData = <?php echo json_encode($daily_sales); ?>;
    
    new Chart(dailyCtx, {
        type: 'line',
        data: {
            labels: dailyData.map(item => {
                const date = new Date(item.date);
                return date.toLocaleDateString('en-IN', { day: 'numeric', month: 'short' });
            }),
            datasets: [
                {
                    label: 'Paid Sales',
                    data: dailyData.map(item => item.paid_amount),
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    tension: 0.4,
                    fill: true,
                    yAxisID: 'y'
                },
                {
                    label: 'Pending Sales',
                    data: dailyData.map(item => item.pending_amount),
                    borderColor: '#ffc107',
                    backgroundColor: 'rgba(255, 193, 7, 0.1)',
                    tension: 0.4,
                    fill: true,
                    yAxisID: 'y'
                },
                {
                    label: 'Order Count',
                    data: dailyData.map(item => item.request_count),
                    borderColor: '#4154f1',
                    backgroundColor: 'rgba(65, 84, 241, 0.1)',
                    type: 'bar',
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                }
            },
            scales: {
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    title: {
                        display: true,
                        text: 'Amount (₹)'
                    },
                    ticks: {
                        callback: function(value) {
                            return '₹' + value.toLocaleString();
                        }
                    }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: 'Order Count'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                }
            }
        }
    });
    <?php endif; ?>
    
    // Package Chart
    <?php if (!empty($package_sales)): ?>
    const packageCtx = document.getElementById('packageChart').getContext('2d');
    const packageData = <?php echo json_encode($package_sales); ?>;
    
    new Chart(packageCtx, {
        type: 'doughnut',
        data: {
            labels: packageData.map(item => item.package_name || (item.package_id == 2500 ? 'Basic Package' : 'Premium Package')),
            datasets: [{
                data: packageData.map(item => item.total_amount),
                backgroundColor: ['#ffc107', '#6f42c1'],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.label || '';
                            let value = context.raw || 0;
                            let total = context.dataset.data.reduce((a, b) => a + b, 0);
                            let percentage = ((value / total) * 100).toFixed(1);
                            return label + ': ₹' + value.toLocaleString() + ' (' + percentage + '%)';
                        }
                    }
                }
            }
        }
    });
    <?php endif; ?>
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>