<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Business Data Analytics Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --accent: #4895ef;
            --success: #4cc9f0;
            --danger: #f72585;
            --warning: #f8961e;
            --light: #f8f9fa;
            --dark: #212529;
            --gray: #adb5bd;
            --border-radius: 8px;
            --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f5f7ff;
            color: var(--dark);
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 0;
            margin-bottom: 30px;
            border-bottom: 1px solid #e9ecef;
        }

        .logo {
            font-size: 28px;
            font-weight: 700;
            color: var(--primary);
            display: flex;
            align-items: center;
        }

        .logo svg {
            margin-right: 10px;
        }

        .upload-section {
            background-color: white;
            border-radius: var(--border-radius);
            padding: 30px;
            box-shadow: var(--box-shadow);
            margin-bottom: 30px;
            text-align: center;
            transition: var(--transition);
        }

        .upload-section:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

        .upload-icon {
            width: 80px;
            height: 80px;
            margin: 0 auto 20px;
            background-color: var(--light);
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        h1, h2, h3 {
            margin-bottom: 15px;
            color: var(--dark);
        }

        p {
            margin-bottom: 20px;
            color: #6c757d;
        }

        .file-input {
            display: none;
        }

        .file-label {
            display: inline-block;
            background-color: var(--primary);
            color: white;
            padding: 12px 30px;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-weight: 500;
            transition: var(--transition);
        }

        .file-label:hover {
            background-color: var(--secondary);
        }

        .status {
            margin-top: 20px;
            font-weight: 500;
        }

        .dashboard {
            display: none;
            opacity: 0;
            transition: opacity 0.5s ease;
        }

        .dashboard.active {
            display: block;
            opacity: 1;
        }

        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            overflow-x: auto;
            padding-bottom: 10px;
        }

        .tab {
            padding: 12px 24px;
            background-color: white;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: var(--transition);
            font-weight: 500;
            white-space: nowrap;
        }

        .tab:hover {
            background-color: var(--light);
        }

        .tab.active {
            background-color: var(--primary);
            color: white;
        }

        .panel {
            display: none;
            background-color: white;
            border-radius: var(--border-radius);
            padding: 30px;
            box-shadow: var(--box-shadow);
            margin-bottom: 30px;
        }

        .panel.active {
            display: block;
            animation: fadeIn 0.5s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .card {
            background-color: white;
            border-radius: var(--border-radius);
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: var(--box-shadow);
            transition: var(--transition);
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background-color: white;
            border-radius: var(--border-radius);
            padding: 20px;
            box-shadow: var(--box-shadow);
            transition: var(--transition);
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-title {
            font-size: 14px;
            color: var(--gray);
            margin-bottom: 10px;
        }

        .stat-value {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .stat-change {
            font-size: 14px;
            font-weight: 500;
        }

        .positive {
            color: #4ade80;
        }

        .negative {
            color: var(--danger);
        }

        .chart-container {
            height: 300px;
            margin-bottom: 30px;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        .data-table th {
            background-color: var(--light);
            padding: 12px 15px;
            text-align: left;
            font-weight: 500;
            position: sticky;
            top: 0;
        }

        .data-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #e9ecef;
        }

        .data-table tbody tr:hover {
            background-color: #f8f9fa;
        }

        .table-container {
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 30px;
        }

        .export-btn {
            background-color: var(--accent);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-weight: 500;
            transition: var(--transition);
            margin-top: 20px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .export-btn:hover {
            background-color: var(--secondary);
        }

        .search-container {
            margin-bottom: 20px;
            position: relative;
        }

        .search-input {
            width: 100%;
            padding: 12px 15px 12px 40px;
            border: 1px solid #e9ecef;
            border-radius: var(--border-radius);
            font-size: 16px;
            transition: var(--transition);
        }

        .search-input:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
        }

        .search-icon {
            position: absolute;
            top: 50%;
            left: 15px;
            transform: translateY(-50%);
            color: var(--gray);
        }

        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
        }

        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-left-color: var(--primary);
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .filter-container {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .filter-select {
            padding: 10px 15px;
            border: 1px solid #e9ecef;
            border-radius: var(--border-radius);
            font-size: 14px;
            min-width: 180px;
        }

        .filter-select:focus {
            border-color: var(--primary);
            outline: none;
        }

        .date-range {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .date-input {
            padding: 10px 15px;
            border: 1px solid #e9ecef;
            border-radius: var(--border-radius);
            font-size: 14px;
        }

        .date-input:focus {
            border-color: var(--primary);
            outline: none;
        }

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

            .tabs {
                flex-wrap: wrap;
            }

            .tab {
                flex-grow: 1;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="logo">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M21 6H3C2.44772 6 2 6.44772 2 7V17C2 17.5523 2.44772 18 3 18H21C21.5523 18 22 17.5523 22 17V7C22 6.44772 21.5523 6 21 6Z" stroke="#4361ee" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M16 14C17.1046 14 18 13.1046 18 12C18 10.8954 17.1046 10 16 10C14.8954 10 14 10.8954 14 12C14 13.1046 14.8954 14 16 14Z" stroke="#4361ee" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M6 12H10" stroke="#4361ee" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                DataInsight
            </div>
        </header>

        <section class="upload-section" id="uploadSection">
            <div class="upload-icon">
                <svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15" stroke="#4361ee" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M17 8L12 3L7 8" stroke="#4361ee" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M12 3V15" stroke="#4361ee" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <h2>Upload Your Excel Data</h2>
            <p>Upload your Excel file to generate comprehensive reports and analytics</p>
            <input type="file" id="fileInput" class="file-input" accept=".xlsx, .xls">
            <label for="fileInput" class="file-label">Choose File</label>
            <p class="status" id="uploadStatus">No file selected</p>
        </section>

        <section class="dashboard" id="dashboard">
            <div class="tabs" id="reportTabs">
                <div class="tab active" data-tab="overview">Overview</div>
                <div class="tab" data-tab="sales">Sales Report</div>
                <div class="tab" data-tab="tax">Tax Report</div>
                <div class="tab" data-tab="stock">Stock Report</div>
                <div class="tab" data-tab="accounts">Accounts Report</div>
                <div class="tab" data-tab="consignee">Consignee Analysis</div>
                <div class="tab" data-tab="raw-data">Raw Data</div>
            </div>

            <div class="panel active" id="overview">
                <h2>Dashboard Overview</h2>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-title">Total Sales</div>
                        <div class="stat-value" id="totalSales">₹0</div>
                        <div class="stat-change positive">+0% vs last period</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Total Tax</div>
                        <div class="stat-value" id="totalTax">₹0</div>
                        <div class="stat-change positive">+0% vs last period</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Total Transactions</div>
                        <div class="stat-value" id="totalTransactions">0</div>
                        <div class="stat-change positive">+0% vs last period</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Unique Consignees</div>
                        <div class="stat-value" id="uniqueConsignees">0</div>
                        <div class="stat-change positive">+0% vs last period</div>
                    </div>
                </div>

                <div class="card">
                    <h3>Sales Trend</h3>
                    <div class="chart-container">
                        <canvas id="salesTrendChart"></canvas>
                    </div>
                </div>

                <div class="card">
                    <h3>Tax Distribution</h3>
                    <div class="chart-container">
                        <canvas id="taxDistributionChart"></canvas>
                    </div>
                </div>
            </div>

            <div class="panel" id="sales">
                <h2>Sales Report</h2>
                <div class="filter-container">
                    <div class="date-range">
                        <input type="date" class="date-input" id="salesStartDate">
                        <span>to</span>
                        <input type="date" class="date-input" id="salesEndDate">
                    </div>
                    <select class="filter-select" id="salesConsigneeFilter">
                        <option value="">All Consignees</option>
                    </select>
                    <select class="filter-select" id="salesTypeFilter">
                        <option value="">All Types</option>
                    </select>
                </div>
                <div class="search-container">
                    <span class="search-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M11 19C15.4183 19 19 15.4183 19 11C19 6.58172 15.4183 3 11 3C6.58172 3 3 6.58172 3 11C3 15.4183 6.58172 19 11 19Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M21 21L16.65 16.65" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </span>
                    <input type="text" class="search-input" id="salesSearch" placeholder="Search sales data...">
                </div>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-title">Total Sales Value</div>
                        <div class="stat-value" id="salesTotal">₹0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Average Order Value</div>
                        <div class="stat-value" id="salesAverage">₹0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Highest Sale</div>
                        <div class="stat-value" id="salesHighest">₹0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Sales Count</div>
                        <div class="stat-value" id="salesCount">0</div>
                    </div>
                </div>
                <div class="card">
                    <h3>Sales by Consignee</h3>
                    <div class="chart-container">
                        <canvas id="salesByConsigneeChart"></canvas>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table" id="salesTable">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Voucher No</th>
                                <th>Consignee/Buyer</th>
                                <th>Particulars</th>
                                <th>Quantity</th>
                                <th>Rate</th>
                                <th>Value</th>
                                <th>GST</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
                <button class="export-btn" id="exportSalesBtn">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M7 10L12 15L17 10" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M12 15V3" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    Export Sales Report
                </button>
            </div>

            <div class="panel" id="tax">
                <h2>Tax Report</h2>
                <div class="filter-container">
                    <div class="date-range">
                        <input type="date" class="date-input" id="taxStartDate">
                        <span>to</span>
                        <input type="date" class="date-input" id="taxEndDate">
                    </div>
                    <select class="filter-select" id="taxTypeFilter">
                        <option value="">All Tax Types</option>
                        <option value="CGST">CGST</option>
                        <option value="SGST">SGST</option>
                        <option value="IGST">IGST</option>
                    </select>
                </div>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-title">Total CGST</div>
                        <div class="stat-value" id="totalCGST">₹0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Total SGST</div>
                        <div class="stat-value" id="totalSGST">₹0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Total IGST</div>
                        <div class="stat-value" id="totalIGST">₹0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Total Tax</div>
                        <div class="stat-value" id="taxTotal">₹0</div>
                    </div>
                </div>
                <div class="card">
                    <h3>Tax Distribution</h3>
                    <div class="chart-container">
                        <canvas id="taxDistributionDetailChart"></canvas>
                    </div>
                </div>
                <div class="card">
                    <h3>Monthly Tax Summary</h3>
                    <div class="chart-container">
                        <canvas id="monthlyTaxChart"></canvas>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table" id="taxTable">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Voucher No</th>
                                <th>GSTIN/UIN</th>
                                <th>Consignee/Buyer</th>
                                <th>Taxable Value</th>
                                <th>CGST</th>
                                <th>SGST</th>
                                <th>IGST</th>
                                <th>Total Tax</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
                <button class="export-btn" id="exportTaxBtn">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M7 10L12 15L17 10" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M12 15V3" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    Export Tax Report
                </button>
            </div>

            <div class="panel" id="stock">
                <h2>Stock Report</h2>
                <div class="filter-container">
                    <select class="filter-select" id="stockItemFilter">
                        <option value="">All Items</option>
                    </select>
                </div>
                <div class="search-container">
                    <span class="search-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M11 19C15.4183 19 19 15.4183 19 11C19 6.58172 15.4183 3 11 3C6.58172 3 3 6.58172 3 11C3 15.4183 6.58172 19 11 19Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M21 21L16.65 16.65" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </span>
                    <input type="text" class="search-input" id="stockSearch" placeholder="Search items...">
                </div>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-title">Total Stock Items</div>
                        <div class="stat-value" id="totalStockItems">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Total Stock Value</div>
                        <div class="stat-value" id="totalStockValue">₹0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Total Quantity</div>
                        <div class="stat-value" id="totalQuantity">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Avg. Item Value</div>
                        <div class="stat-value" id="avgItemValue">₹0</div>
                    </div>
                </div>
                <div class="card">
                    <h3>Top Items by Value</h3>
                    <div class="chart-container">
                        <canvas id="topItemsChart"></canvas>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table" id="stockTable">
                        <thead>
                            <tr>
                                <th>Particulars</th>
                                <th>Total Quantity</th>
                                <th>Avg. Rate</th>
                                <th>Total Value</th>
                                <th>Last Updated</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
                <button class="export-btn" id="exportStockBtn">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M7 10L12 15L17 10" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M12 15V3" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    Export Stock Report
                </button>
            </div>

            <div class="panel" id="accounts">
                <h2>Accounts Report</h2>
                <div class="filter-container">
                    <div class="date-range">
                        <input type="date" class="date-input" id="accountsStartDate">
                        <span>to</span>
                        <input type="date" class="date-input" id="accountsEndDate">
                    </div>
                    <select class="filter-select" id="accountsTypeFilter">
                        <option value="">All Account Types</option>
                    </select>
                </div>
<div class="stat-card">
    <div class="stat-title">Total Revenue</div>
    <div class="stat-value" id="totalRevenue">₹0</div>
</div>
<div class="stat-card">
    <div class="stat-title">Total Expenses</div>
    <div class="stat-value" id="totalExpenses">₹0</div>
</div>
<div class="stat-card">
    <div class="stat-title">Net Profit</div>
    <div class="stat-value" id="netProfit">₹0</div>
</div>
<div class="stat-card">
    <div class="stat-title">Profit Margin</div>
    <div class="stat-value" id="profitMargin">0%</div>
</div>
</div>
<div class="card">
    <h3>Revenue vs Expenses</h3>
    <div class="chart-container">
        <canvas id="revenueExpensesChart"></canvas>
    </div>
</div>
<div class="card">
    <h3>Income Breakdown</h3>
    <div class="chart-container">
        <canvas id="incomeBreakdownChart"></canvas>
    </div>
</div>
<div class="table-container">
    <table class="data-table" id="accountsTable">
        <thead>
            <tr>
                <th>Date</th>
                <th>Particulars</th>
                <th>Voucher No</th>
                <th>Account Type</th>
                <th>Debit</th>
                <th>Credit</th>
                <th>Balance</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<button class="export-btn" id="exportAccountsBtn">
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M7 10L12 15L17 10" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M12 15V3" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>
    Export Accounts Report
</button>
</div>

<div class="panel" id="consignee">
<h2>Consignee Analysis</h2>
<div class="filter-container">
    <div class="date-range">
        <input type="date" class="date-input" id="consigneeStartDate">
        <span>to</span>
        <input type="date" class="date-input" id="consigneeEndDate">
    </div>
    <select class="filter-select" id="consigneeFilter">
        <option value="">All Consignees</option>
    </select>
</div>
<div class="search-container">
    <span class="search-icon">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M11 19C15.4183 19 19 15.4183 19 11C19 6.58172 15.4183 3 11 3C6.58172 3 3 6.58172 3 11C3 15.4183 6.58172 19 11 19Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M21 21L16.65 16.65" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
    </span>
    <input type="text" class="search-input" id="consigneeSearch" placeholder="Search consignees...">
</div>
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-title">Total Consignees</div>
        <div class="stat-value" id="totalConsignees">0</div>
    </div>
    <div class="stat-card">
        <div class="stat-title">Top Consignee Value</div>
        <div class="stat-value" id="topConsigneeValue">₹0</div>
    </div>
    <div class="stat-card">
        <div class="stat-title">Avg. Value per Consignee</div>
        <div class="stat-value" id="avgConsigneeValue">₹0</div>
    </div>
    <div class="stat-card">
        <div class="stat-title">Active Consignees</div>
        <div class="stat-value" id="activeConsignees">0</div>
    </div>
</div>
<div class="card">
    <h3>Top Consignees by Value</h3>
    <div class="chart-container">
        <canvas id="topConsigneesChart"></canvas>
    </div>
</div>
<div class="card">
    <h3>Consignee Transaction Frequency</h3>
    <div class="chart-container">
        <canvas id="consigneeFrequencyChart"></canvas>
    </div>
</div>
<div class="table-container">
    <table class="data-table" id="consigneeTable">
        <thead>
            <tr>
                <th>Consignee/Buyer</th>
                <th>GSTIN/UIN</th>
                <th>Address</th>
                <th>Total Transactions</th>
                <th>Total Value</th>
                <th>Last Transaction</th>
                <th>Avg. Order Value</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<button class="export-btn" id="exportConsigneeBtn">
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M7 10L12 15L17 10" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M12 15V3" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>
    Export Consignee Report
</button>
</div>

<div class="panel" id="raw-data">
<h2>Raw Data</h2>
<div class="search-container">
    <span class="search-icon">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M11 19C15.4183 19 19 15.4183 19 11C19 6.58172 15.4183 3 11 3C6.58172 3 3 6.58172 3 11C3 15.4183 6.58172 19 11 19Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M21 21L16.65 16.65" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
    </span>
    <input type="text" class="search-input" id="rawDataSearch" placeholder="Search raw data...">
</div>
<div class="table-container">
    <table class="data-table" id="rawDataTable">
        <thead>
            <tr>
                <th>Date</th>
                <th>Particulars</th>
                <th>Consignee/Buyer</th>
                <th>Voucher No.</th>
                <th>GSTIN/UIN</th>
                <th>Quantity</th>
                <th>Rate</th>
                <th>Value</th>
                <th>Gross Total</th>
                <th>CGST</th>
                <th>SGST</th>
                <th>IGST</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<button class="export-btn" id="exportRawDataBtn">
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M7 10L12 15L17 10" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M12 15V3" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>
    Export Raw Data
</button>
</div>
</section>

</div>

<script>
    // Global variables to store data
    let rawData = [];
    let salesData = [];
    let taxData = [];
    let stockData = [];
    let accountsData = [];
    let consigneeData = [];
    let charts = {};

    // DOM elements
    const fileInput = document.getElementById('fileInput');
    const uploadStatus = document.getElementById('uploadStatus');
    const uploadSection = document.getElementById('uploadSection');
    const dashboard = document.getElementById('dashboard');
    const tabs = document.querySelectorAll('.tab');
    const panels = document.querySelectorAll('.panel');

    // Event listeners
    fileInput.addEventListener('change', handleFileUpload);
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            // Remove active class from all tabs and panels
            tabs.forEach(t => t.classList.remove('active'));
            panels.forEach(p => p.classList.remove('active'));
            
            // Add active class to clicked tab and corresponding panel
            tab.classList.add('active');
            document.getElementById(tab.dataset.tab).classList.add('active');
            
            // Refresh charts if they exist
            if (charts[tab.dataset.tab]) {
                charts[tab.dataset.tab].forEach(chart => chart.update());
            }
        });
    });

    // Add event listeners for date filters to update data on change
    ['salesStartDate', 'salesEndDate', 'taxStartDate', 'taxEndDate', 'accountsStartDate', 'accountsEndDate', 'consigneeStartDate', 'consigneeEndDate'].forEach(id => {
        const input = document.getElementById(id);
        if (input) {
            input.addEventListener('change', () => {
                filterAndUpdateReports();
            });
        }
    });

    // Add event listeners for other filters to update data on change
    document.getElementById('salesConsigneeFilter').addEventListener('change', filterAndUpdateReports);
    document.getElementById('salesTypeFilter').addEventListener('change', filterAndUpdateReports);
    document.getElementById('taxTypeFilter').addEventListener('change', filterAndUpdateReports);
    document.getElementById('stockItemFilter').addEventListener('change', filterAndUpdateReports);
    document.getElementById('accountsTypeFilter').addEventListener('change', filterAndUpdateReports);
    document.getElementById('consigneeFilter').addEventListener('change', filterAndUpdateReports);

    // Function to filter data based on selected filters and update tables and charts
    function filterAndUpdateReports() {
        filterSalesData();
        filterTaxData();
        filterStockData();
        filterAccountsData();
        filterConsigneeData();

        updateTables();
        updateDashboardStats();
        updateCharts();
    }

    // Filter sales data based on filters
    function filterSalesData() {
        const startDate = parseDate(document.getElementById('salesStartDate').value);
        const endDate = parseDate(document.getElementById('salesEndDate').value);
        const consigneeFilter = document.getElementById('salesConsigneeFilter').value;
        const typeFilter = document.getElementById('salesTypeFilter').value;

        salesData = rawData.map(row => {
            const date = parseDate(row['Date']);
            return {
                date: date,
                dateStr: formatDate(date),
                voucherNo: row['Voucher No.'] || '',
                voucherType: row['Voucher Type'] || '',
                consignee: row['Consignee/Buyer'] || '',
                particulars: row['Particulars'] || '',
                quantity: parseFloat(row['Quantity'] || 0),
                rate: parseFloat(row['Rate'] || 0),
                value: parseFloat(row['Value'] || 0),
                grossTotal: parseFloat(row['Gross Total'] || 0),
                cgst: getCGSTValue(row),
                sgst: getSGSTValue(row),
                igst: getIGSTValue(row),
                totalTax: getTotalTaxValue(row),
                totalAmount: parseFloat(row['Gross Total'] || 0) + getTotalTaxValue(row)
            };
        }).filter(item => {
            if (!item.date) return false;
            if (startDate && item.date < startDate) return false;
            if (endDate && item.date > endDate) return false;
            if (consigneeFilter && item.consignee !== consigneeFilter) return false;
            if (typeFilter && item.voucherType !== typeFilter) return false;
            return true;
        });
    }

    // Filter tax data based on salesData filtered
    function filterTaxData() {
        taxData = salesData.map(item => ({
            ...item,
            taxableValue: item.value,
            cgst: item.cgst,
            sgst: item.sgst,
            igst: item.igst,
            totalTax: item.totalTax,
            gstin: rawData.find(row => row['Voucher No.'] === item.voucherNo)?.['GSTIN/UIN'] || ''
        }));

        const taxTypeFilter = document.getElementById('taxTypeFilter').value;
        if (taxTypeFilter) {
            taxData = taxData.filter(item => {
                if (taxTypeFilter === 'CGST') return item.cgst > 0;
                if (taxTypeFilter === 'SGST') return item.sgst > 0;
                if (taxTypeFilter === 'IGST') return item.igst > 0;
                return true;
            });
        }
    }

    // Filter stock data based on stockItemFilter
    function filterStockData() {
        const stockItemFilter = document.getElementById('stockItemFilter').value;
        // Recalculate stockData from salesData filtered
        const stockMap = {};
        salesData.forEach(item => {
            if (item.particulars && item.quantity) {
                if (!stockMap[item.particulars]) {
                    stockMap[item.particulars] = {
                        particulars: item.particulars,
                        totalQuantity: 0,
                        totalValue: 0,
                        transactions: 0,
                        lastUpdated: null
                    };
                }
                stockMap[item.particulars].totalQuantity += item.quantity;
                stockMap[item.particulars].totalValue += item.value;
                stockMap[item.particulars].transactions += 1;
                if (!stockMap[item.particulars].lastUpdated || (item.date && item.date > stockMap[item.particulars].lastUpdated)) {
                    stockMap[item.particulars].lastUpdated = item.date;
                }
            }
        });
        stockData = Object.values(stockMap).map(item => ({
            ...item,
            avgRate: item.totalQuantity > 0 ? item.totalValue / item.totalQuantity : 0,
            lastUpdatedStr: item.lastUpdated ? formatDate(item.lastUpdated) : 'N/A'
        }));
        if (stockItemFilter) {
            stockData = stockData.filter(item => item.particulars === stockItemFilter);
        }
    }

    // Filter accounts data based on accountsTypeFilter and date range
    function filterAccountsData() {
        const startDate = parseDate(document.getElementById('accountsStartDate').value);
        const endDate = parseDate(document.getElementById('accountsEndDate').value);
        const accountsTypeFilter = document.getElementById('accountsTypeFilter').value;

        // Recalculate accountsData from salesData filtered
        const accounts = [];
        salesData.forEach(item => {
            accounts.push({
                date: item.date,
                dateStr: item.dateStr,
                particulars: item.particulars,
                voucherNo: item.voucherNo,
                accountType: 'Sales',
                debit: 0,
                credit: item.totalAmount,
                balance: item.totalAmount
            });
        });
        accountsData = accounts.sort((a, b) => a.date - b.date);
        let runningBalance = 0;
        accountsData.forEach(item => {
            runningBalance += item.credit - item.debit;
            item.balance = runningBalance;
        });
        accountsData = accountsData.filter(item => {
            if (!item.date) return false;
            if (startDate && item.date < startDate) return false;
            if (endDate && item.date > endDate) return false;
            if (accountsTypeFilter && item.accountType !== accountsTypeFilter) return false;
            return true;
        });
    }

    // Filter consignee data based on consigneeFilter and date range
    function filterConsigneeData() {
        const startDate = parseDate(document.getElementById('consigneeStartDate').value);
        const endDate = parseDate(document.getElementById('consigneeEndDate').value);
        const consigneeFilter = document.getElementById('consigneeFilter').value;

        // Recalculate consigneeData from salesData filtered
        const consigneeMap = {};
        salesData.forEach(item => {
            if (item.consignee) {
                if (!consigneeMap[item.consignee]) {
                    const consigneeDataRow = rawData.find(row => row['Consignee/Buyer'] === item.consignee);
                    consigneeMap[item.consignee] = {
                        consignee: item.consignee,
                        gstin: consigneeDataRow?.['GSTIN/UIN'] || '',
                        address: consigneeDataRow?.['Address'] || '',
                        transactions: 0,
                        totalValue: 0,
                        lastTransaction: null,
                        orders: []
                    };
                }
                consigneeMap[item.consignee].transactions += 1;
                consigneeMap[item.consignee].totalValue += item.totalAmount;
                consigneeMap[item.consignee].orders.push({
                    date: item.date,
                    amount: item.totalAmount
                });
                if (!consigneeMap[item.consignee].lastTransaction || (item.date && item.date > consigneeMap[item.consignee].lastTransaction)) {
                    consigneeMap[item.consignee].lastTransaction = item.date;
                }
            }
        });
        consigneeData = Object.values(consigneeMap).map(item => ({
            ...item,
            avgOrderValue: item.transactions > 0 ? item.totalValue / item.transactions : 0,
            lastTransactionStr: item.lastTransaction ? formatDate(item.lastTransaction) : 'N/A'
        }));
        if (consigneeFilter) {
            consigneeData = consigneeData.filter(item => item.consignee === consigneeFilter);
        }
        consigneeData.sort((a, b) => b.totalValue - a.totalValue);
    }

    // Update charts after filtering
    function updateCharts() {
        Object.keys(charts).forEach(key => {
            charts[key].forEach(chart => chart.destroy());
        });
        createCharts();
    }

    // Add event listeners for export buttons
    document.getElementById('exportSalesBtn').addEventListener('click', () => exportData('sales'));
    document.getElementById('exportTaxBtn').addEventListener('click', () => exportData('tax'));
    document.getElementById('exportStockBtn').addEventListener('click', () => exportData('stock'));
    document.getElementById('exportAccountsBtn').addEventListener('click', () => exportData('accounts'));
    document.getElementById('exportConsigneeBtn').addEventListener('click', () => exportData('consignee'));
    document.getElementById('exportRawDataBtn').addEventListener('click', () => exportData('rawData'));

    // Search functionality for tables
    document.getElementById('salesSearch').addEventListener('input', e => filterTable('salesTable', e.target.value));
    document.getElementById('stockSearch').addEventListener('input', e => filterTable('stockTable', e.target.value));
    document.getElementById('consigneeSearch').addEventListener('input', e => filterTable('consigneeTable', e.target.value));
    document.getElementById('rawDataSearch').addEventListener('input', e => filterTable('rawDataTable', e.target.value));

    // Handle file upload
    function handleFileUpload(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        uploadStatus.textContent = `Reading ${file.name}...`;
        
        const reader = new FileReader();
        reader.onload = function(e) {
            try {
                const data = new Uint8Array(e.target.result);
                
                const workbook = XLSX.read(data, {type: 'array'});
                
                // Get first sheet
                const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                
                // Convert to JSON starting from row 9 (index 8)
                const jsonData = XLSX.utils.sheet_to_json(firstSheet, {
                    range: 8, // Start from row 9 (0-indexed)
                    header: 1
                });
                
                // Get headers from row 8 (index 7)
                const headers = XLSX.utils.sheet_to_json(firstSheet, {
                    range: 7, // Row 8
                    header: 1
                })[0];
                
                // Show mapping UI for user to map file headers to expected headings
                showMappingUI(headers, file.name, jsonData);
            } catch (error) {
                console.error('Error processing file:', error);
                uploadStatus.textContent = `Error: ${error.message}`;
                uploadStatus.style.color = 'var(--danger)';
            }
        };
        
        reader.onerror = function() {
            uploadStatus.textContent = 'Error reading file';
            uploadStatus.style.color = 'var(--danger)';
        };
        
        reader.readAsArrayBuffer(file);
    }

    // Show mapping UI function
    function showMappingUI(fileHeaders, fileName, jsonData) {
        // Updated expected headings to match actual file headers
        const expectedHeadings = [
            'Date',
            'Particulars',
            'ConsigneeBuyer',
            'Address',
            'Voucher Type',
            'Voucher No.',
            'Voucher Ref No.',
            'GSTIN/UIN',
            'Sales Tax',
            'Service Tax',
            'PAN No.',
            'CST No.',
            'Narration',
            'Order No.',
            'Terms of Payment',
            'Other Deductions',
            'Delivery Note No.',
            'Despatch Doc No.',
            'Destination',
            'Place of Receipt by Consignee',
            'Vessel/Flight No.',
            'Port of Loading',
            'Port of Discharge',
            'Country of Origin',
            'Shipping Bill No.',
            'Shipping Date',
            'Port Code',
            'Quantity',
            'Alt. Units',
            'Rate',
            'Value',
            'Gross Total',
            'GST Sale @ 28%',
            'Output CGST @ 14%',
            'Output SGST @ 14%',
            'Roundoff',
            'Output CGST @ 9%',
            'Output SGST @ 9%',
            'Commission Recivable A/c',
            'Output IGST @ 18%',
            'Cash Sales',
            'GST Interstate Sale @ 18%',
            'Fright Charge Recived',
            'Transport Charge',
            'Fuel,Petrol and Diesel Charges'
        ];

        // Create mapping container
        const mappingContainer = document.createElement('div');
        mappingContainer.id = 'mappingContainer';
        mappingContainer.style.backgroundColor = 'white';
        mappingContainer.style.borderRadius = 'var(--border-radius)';
        mappingContainer.style.padding = '20px';
        mappingContainer.style.boxShadow = 'var(--box-shadow)';
        mappingContainer.style.marginTop = '20px';

        // Title
        const title = document.createElement('h3');
        title.textContent = `Map Columns for ${fileName}`;
        mappingContainer.appendChild(title);

        // Instructions
        const instructions = document.createElement('p');
        instructions.textContent = 'Please map the columns from your file to the expected headings below. Select "Ignore" to skip a heading.';
        mappingContainer.appendChild(instructions);

        // Create form
        const form = document.createElement('form');
        form.id = 'mappingForm';

        // For each expected heading, create a dropdown to select file header or ignore
        expectedHeadings.forEach(expected => {
            const label = document.createElement('label');
            label.textContent = expected;
            label.style.display = 'block';
            label.style.marginTop = '10px';

            const select = document.createElement('select');
            select.name = expected;
            select.style.width = '100%';
            select.style.padding = '8px';
            select.style.marginTop = '5px';
            select.style.borderRadius = '4px';
            select.style.border = '1px solid #ccc';

            // Add option to ignore
            const ignoreOption = document.createElement('option');
            ignoreOption.value = '';
            ignoreOption.textContent = 'Ignore';
            select.appendChild(ignoreOption);

            // Add options for each file header
            fileHeaders.forEach(header => {
                const option = document.createElement('option');
                option.value = header;
                option.textContent = header;
                select.appendChild(option);
            });

            label.appendChild(select);
            form.appendChild(label);
        });

        // Submit button
        const submitBtn = document.createElement('button');
        submitBtn.type = 'submit';
        submitBtn.textContent = 'Apply Mapping';
        submitBtn.style.marginTop = '20px';
        submitBtn.style.padding = '10px 20px';
        submitBtn.style.backgroundColor = 'var(--primary)';
        submitBtn.style.color = 'white';
        submitBtn.style.border = 'none';
        submitBtn.style.borderRadius = 'var(--border-radius)';
        submitBtn.style.cursor = 'pointer';

        form.appendChild(submitBtn);
        mappingContainer.appendChild(form);

        // Insert mapping UI after upload section
        uploadSection.style.display = 'none';
        if (document.getElementById('mappingContainer')) {
            document.getElementById('mappingContainer').remove();
        }
        document.querySelector('.container').appendChild(mappingContainer);

        // Handle form submission
        form.addEventListener('submit', function(event) {
            event.preventDefault();

            // Get mapping from form
            const formData = new FormData(form);
            const mapping = {};
            for (const [key, value] of formData.entries()) {
                if (value) {
                    mapping[key] = value;
                }
            }

            // Transform rawData keys using mapping
            const transformedData = jsonData.map(row => {
                const rowData = {};
                Object.keys(mapping).forEach(expectedKey => {
                    const fileHeader = mapping[expectedKey];
                    const index = fileHeaders.indexOf(fileHeader);
                    if (index !== -1 && index < row.length) {
                        rowData[expectedKey] = row[index];
                    } else {
                        rowData[expectedKey] = null;
                    }
                });
                return rowData;
            });

            // Filter out empty rows
            rawData = transformedData.filter(row => Object.values(row).some(val => val !== null && val !== ''));

            // Remove mapping UI
            mappingContainer.remove();

            // Update UI
            uploadStatus.textContent = `${fileName} loaded successfully with mapping!`;
            uploadSection.style.backgroundColor = '#e6f7ee';
            uploadSection.style.display = 'block';
            uploadSection.style.opacity = 0;
            setTimeout(() => {
                uploadSection.style.opacity = 1;
            }, 100);

            // Show dashboard
            setTimeout(() => {
                uploadSection.style.opacity = 0;
                setTimeout(() => {
                    uploadSection.style.display = 'none';
                    dashboard.classList.add('active');
                }, 300);
            }, 1000);

            // Process data for different reports
            processData();
        });
    }
                
            } catch (error) {
                console.error('Error processing file:', error);
                uploadStatus.textContent = `Error: ${error.message}`;
                uploadStatus.style.color = 'var(--danger)';
            }
        };
        
        reader.onerror = function() {
            uploadStatus.textContent = 'Error reading file';
            uploadStatus.style.color = 'var(--danger)';
        };
        
        reader.readAsArrayBuffer(file);
    }

    // Process data for different reports
    function processData() {
        // Process sales data
        processSalesData();
        
        // Process tax data
        processTaxData();
        
        // Process stock data
        processStockData();
        
        // Process accounts data
        processAccountsData();
        
        // Process consignee data
        processConsigneeData();
        
        // Update tables
        updateTables();
        
        // Create charts
        createCharts();
        
        // Update dashboard stats
        updateDashboardStats();
    }

    // Process sales data
    function processSalesData() {
        salesData = rawData.map(row => {
            // Convert string dates to Date objects
            const date = parseDate(row['Date']);
            
            return {
                date: date,
                dateStr: formatDate(date),
                voucherNo: row['Voucher No.'] || '',
                voucherType: row['Voucher Type'] || '',
                consignee: row['Consignee/Buyer'] || '',
                particulars: row['Particulars'] || '',
                quantity: parseFloat(row['Quantity'] || 0),
                rate: parseFloat(row['Rate'] || 0),
                value: parseFloat(row['Value'] || 0),
                grossTotal: parseFloat(row['Gross Total'] || 0),
                cgst: getCGSTValue(row),
                sgst: getSGSTValue(row),
                igst: getIGSTValue(row),
                totalTax: getTotalTaxValue(row),
                totalAmount: parseFloat(row['Gross Total'] || 0) + getTotalTaxValue(row)
            };
        });
        
        // Populate consignee filter
        const consignees = [...new Set(salesData.map(item => item.consignee))].filter(Boolean);
        const salesConsigneeFilter = document.getElementById('salesConsigneeFilter');
        salesConsigneeFilter.innerHTML = '<option value="">All Consignees</option>';
        consignees.forEach(consignee => {
            salesConsigneeFilter.innerHTML += `<option value="${consignee}">${consignee}</option>`;
        });
        
        // Populate voucher type filter
        const voucherTypes = [...new Set(salesData.map(item => item.voucherType))].filter(Boolean);
        const salesTypeFilter = document.getElementById('salesTypeFilter');
        salesTypeFilter.innerHTML = '<option value="">All Types</option>';
        voucherTypes.forEach(type => {
            salesTypeFilter.innerHTML += `<option value="${type}">${type}</option>`;
        });
        
        // Set date filters to min and max dates
        const dates = salesData.map(item => item.date).filter(date => date instanceof Date && !isNaN(date));
        if (dates.length > 0) {
            const minDate = new Date(Math.min(...dates));
            const maxDate = new Date(Math.max(...dates));
            
            document.getElementById('salesStartDate').value = formatDateForInput(minDate);
            document.getElementById('salesEndDate').value = formatDateForInput(maxDate);
            
            document.getElementById('taxStartDate').value = formatDateForInput(minDate);
            document.getElementById('taxEndDate').value = formatDateForInput(maxDate);
            
            document.getElementById('accountsStartDate').value = formatDateForInput(minDate);
            document.getElementById('accountsEndDate').value = formatDateForInput(maxDate);
            
            document.getElementById('consigneeStartDate').value = formatDateForInput(minDate);
            document.getElementById('consigneeEndDate').value = formatDateForInput(maxDate);
        }
    }

    // Process tax data
    function processTaxData() {
        taxData = salesData.map(item => ({
            ...item,
            taxableValue: item.value,
            cgst: item.cgst,
            sgst: item.sgst,
            igst: item.igst,
            totalTax: item.totalTax,
            gstin: rawData.find(row => row['Voucher No.'] === item.voucherNo)?.['GSTIN/UIN'] || ''
        }));
    }

    // Process stock data
    function processStockData() {
        // Group by particulars and calculate totals
        const stockMap = {};
        
        salesData.forEach(item => {
            if (item.particulars && item.quantity) {
                if (!stockMap[item.particulars]) {
                    stockMap[item.particulars] = {
                        particulars: item.particulars,
                        totalQuantity: 0,
                        totalValue: 0,
                        transactions: 0,
                        lastUpdated: null
                    };
                }
                
                stockMap[item.particulars].totalQuantity += item.quantity;
                stockMap[item.particulars].totalValue += item.value;
                stockMap[item.particulars].transactions += 1;
                
                // Track last updated date
                if (!stockMap[item.particulars].lastUpdated || 
                    (item.date && item.date > stockMap[item.particulars].lastUpdated)) {
                    stockMap[item.particulars].lastUpdated = item.date;
                }
            }
        });
        
        // Convert to array and calculate average rate
        stockData = Object.values(stockMap).map(item => ({
            ...item,
            avgRate: item.totalQuantity > 0 ? item.totalValue / item.totalQuantity : 0,
            lastUpdatedStr: item.lastUpdated ? formatDate(item.lastUpdated) : 'N/A'
        }));
        
        // Populate item filter
        const items = stockData.map(item => item.particulars);
        const stockItemFilter = document.getElementById('stockItemFilter');
        stockItemFilter.innerHTML = '<option value="">All Items</option>';
        items.forEach(item => {
            stockItemFilter.innerHTML += `<option value="${item}">${item}</option>`;
        });
    }

    // Process accounts data
    function processAccountsData() {
        // Create accounts data from sales and expenses
        const accounts = [];
        
        // Add sales to accounts
        salesData.forEach(item => {
            accounts.push({
                date: item.date,
                dateStr: item.dateStr,
                particulars: item.particulars,
                voucherNo: item.voucherNo,
                accountType: 'Sales',
                debit: 0,
                credit: item.totalAmount,
                balance: item.totalAmount
            });
        });
        
        // Sort by date
        accountsData = accounts.sort((a, b) => a.date - b.date);
        
        // Calculate running balance
        let runningBalance = 0;
        accountsData.forEach(item => {
            runningBalance += item.credit - item.debit;
            item.balance = runningBalance;
        });
        
        // Populate account type filter
        const accountTypes = [...new Set(accountsData.map(item => item.accountType))];
        const accountsTypeFilter = document.getElementById('accountsTypeFilter');
        accountsTypeFilter.innerHTML = '<option value="">All Account Types</option>';
        accountTypes.forEach(type => {
            accountsTypeFilter.innerHTML += `<option value="${type}">${type}</option>`;
        });
    }

    // Process consignee data
    function processConsigneeData() {
        // Group by consignee
        const consigneeMap = {};
        
        salesData.forEach(item => {
            if (item.consignee) {
                if (!consigneeMap[item.consignee]) {
                    const consigneeData = rawData.find(row => row['Consignee/Buyer'] === item.consignee);
                    
                    consigneeMap[item.consignee] = {
                        consignee: item.consignee,
                        gstin: consigneeData?.['GSTIN/UIN'] || '',
                        address: consigneeData?.['Address'] || '',
                        transactions: 0,
                        totalValue: 0,
                        lastTransaction: null,
                        orders: []
                    };
                }
                
                consigneeMap[item.consignee].transactions += 1;
                consigneeMap[item.consignee].totalValue += item.totalAmount;
                consigneeMap[item.consignee].orders.push({
                    date: item.date,
                    amount: item.totalAmount
                });
                
                // Track last transaction date
                if (!consigneeMap[item.consignee].lastTransaction || 
                    (item.date && item.date > consigneeMap[item.consignee].lastTransaction)) {
                    consigneeMap[item.consignee].lastTransaction = item.date;
                }
            }
        });
        
        // Convert to array and calculate average order value
        consigneeData = Object.values(consigneeMap).map(item => ({
            ...item,
            avgOrderValue: item.transactions > 0 ? item.totalValue / item.transactions : 0,
            lastTransactionStr: item.lastTransaction ? formatDate(item.lastTransaction) : 'N/A'
        }));
        
        // Sort by total value descending
        consigneeData.sort((a, b) => b.totalValue - a.totalValue);
        
        // Populate consignee filter
        const consigneeFilter = document.getElementById('consigneeFilter');
        consigneeFilter.innerHTML = '<option value="">All Consignees</option>';
        consigneeData.forEach(item => {
            consigneeFilter.innerHTML += `<option value="${item.consignee}">${item.consignee}</option>`;
        });
    }

    // Update tables with processed data
    function updateTables() {
        // Update sales table
        updateSalesTable();
        
        // Update tax table
        updateTaxTable();
        
        // Update stock table
        updateStockTable();
        
        // Update accounts table
        updateAccountsTable();
        
        // Update consignee table
        updateConsigneeTable();
        
        // Update raw data table
        updateRawDataTable();
    }

    // Update sales table
    function updateSalesTable() {
        const tableBody = document.querySelector('#salesTable tbody');
        tableBody.innerHTML = '';
        
        salesData.forEach(item => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${item.dateStr}</td>
                <td>${item.voucherNo}</td>
                <td>${item.consignee}</td>
                <td>${item.particulars}</td>
                <td>${formatNumber(item.quantity)}</td>
                <td>${formatCurrency(item.rate)}</td>
                <td>${formatCurrency(item.value)}</td>
                <td>${formatCurrency(item.totalTax)}</td>
                <td>${formatCurrency(item.totalAmount)}</td>
            `;
            tableBody.appendChild(row);
        });
    }

    // Update tax table
    function updateTaxTable() {
        const tableBody = document.querySelector('#taxTable tbody');
        tableBody.innerHTML = '';
        
        taxData.forEach(item => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${item.dateStr}</td>
                <td>${item.voucherNo}</td>
                <td>${item.gstin}</td>
                <td>${item.consignee}</td>
                <td>${formatCurrency(item.taxableValue)}</td>
                <td>${formatCurrency(item.cgst)}</td>
                <td>${formatCurrency(item.sgst)}</td>
                <td>${formatCurrency(item.igst)}</td>
                <td>${formatCurrency(item.totalTax)}</td>
            `;
            tableBody.appendChild(row);
        });
    }

    // Update stock table
    function updateStockTable() {
        const tableBody = document.querySelector('#stockTable tbody');
        tableBody.innerHTML = '';
        
        stockData.forEach(item => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${item.particulars}</td>
                <td>${formatNumber(item.totalQuantity)}</td>
                <td>${formatCurrency(item.avgRate)}</td>
                <td>${formatCurrency(item.totalValue)}</td>
                <td>${item.lastUpdatedStr}</td>
            `;
            tableBody.appendChild(row);
        });
    }

    // Update accounts table
    function updateAccountsTable() {
        const tableBody = document.querySelector('#accountsTable tbody');
        tableBody.innerHTML = '';
        
        accountsData.forEach(item => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${item.dateStr}</td>
                <td>${item.particulars}</td>
                <td>${item.voucherNo}</td>
                <td>${item.accountType}</td>
                <td>${formatCurrency(item.debit)}</td>
                <td>${formatCurrency(item.credit)}</td>
                <td>${formatCurrency(item.balance)}</td>
            `;
            tableBody.appendChild(row);
        });
    }

    // Update consignee table
    function updateConsigneeTable() {
        const tableBody = document.querySelector('#consigneeTable tbody');
        tableBody.innerHTML = '';
        
        consigneeData.forEach(item => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${item.consignee}</td>
                <td>${item.gstin}</td>
                <td>${item.address}</td>
                <td>${item.transactions}</td>
                <td>${formatCurrency(item.totalValue)}</td>
                <td>${item.lastTransactionStr}</td>
                <td>${formatCurrency(item.avgOrderValue)}</td>
            `;
            tableBody.appendChild(row);
        });
    }

    // Update raw data table
    function updateRawDataTable() {
        const tableBody = document.querySelector('#rawDataTable tbody');
        tableBody.innerHTML = '';
        
        rawData.forEach(row => {
            const tableRow = document.createElement('tr');
            
            // Parse date
            const date = parseDate(row['Date']);
            const dateStr = date ? formatDate(date) : '';
            
            tableRow.innerHTML = `
                <td>${dateStr}</td>
                <td>${row['Particulars'] || ''}</td>
                <td>${row['Consignee/Buyer'] || ''}</td>
                <td>${row['Voucher No.'] || ''}</td>
                <td>${row['GSTIN/UIN'] || ''}</td>
                <td>${formatNumber(row['Quantity'] || 0)}</td>
                <td>${formatCurrency(row['Value'] || 0)}</td>
                <td>${formatCurrency(row['Gross Total'] || 0)}</td>
                <td>${formatCurrency(getCGSTValue(row))}</td>
                <td>${formatCurrency(getSGSTValue(row))}</td>
                <td>${formatCurrency(getIGSTValue(row))}</td>
            `;
            tableBody.appendChild(tableRow);
        });
    }

    // Create charts for visualization
    function createCharts() {
        charts = {
            overview: [],
            sales: [],
            tax: [],
            stock: [],
            accounts: [],
            consignee: []
        };
        
        // Overview charts
        createSalesTrendChart();
        createTaxDistributionChart();
        
        // Sales charts
        createSalesByConsigneeChart();
        
        // Tax charts
        createTaxDistributionDetailChart();
        createMonthlyTaxChart();
        
        // Stock charts
        createTopItemsChart();
        
        // Accounts charts
        createRevenueExpensesChart();
        createIncomeBreakdownChart();
        
        // Consignee charts
        createTopConsigneesChart();
        createConsigneeFrequencyChart();
    }

    // Create sales trend chart
    function createSalesTrendChart() {
        const ctx = document.getElementById('salesTrendChart').getContext('2d');
        
        // Group sales data by month
        const monthlySales = {};
        
        salesData.forEach(item => {
            if (item.date) {
                const monthYear = item.date.toLocaleString('default', { month: 'short', year: 'numeric' });
                
                if (!monthlySales[monthYear]) {
                    monthlySales[monthYear] = 0;
                }
                
                monthlySales[monthYear] += item.totalAmount;
            }
        });
        
        // Sort months chronologically
        const months = Object.keys(monthlySales).sort((a, b) => {
            return new Date(a) - new Date(b);
        });
        
        const salesChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: months,
                datasets: [{
                    label: 'Monthly Sales',
                    data: months.map(month => monthlySales[month]),
                    backgroundColor: 'rgba(67, 97, 238, 0.2)',
                    borderColor: 'rgba(67, 97, 238, 1)',
                    borderWidth: 2,
                    pointBackgroundColor: 'rgba(67, 97, 238, 1)',
                    pointRadius: 4,
                    fill: true,
                    tension: 0.2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: value => '₹' + formatNumberShort(value)
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    },
                    tooltip: {
                        callbacks: {
                            label: context => '₹' + formatNumber(context.raw)
                        }
                    }
                }
            }
        });
        
        charts.overview.push(salesChart);
    }

    // Create tax distribution chart
    function createTaxDistributionChart() {
        const ctx = document.getElementById('taxDistributionChart').getContext('2d');
        
        // Calculate total tax amounts
        let totalCGST = 0;
        let totalSGST = 0;
        let totalIGST = 0;
        
        taxData.forEach(item => {
            totalCGST += item.cgst;
            totalSGST += item.sgst;
            totalIGST += item.igst;
        });
        
        const taxChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['CGST', 'SGST', 'IGST'],
                datasets: [{
                    data: [totalCGST, totalSGST, totalIGST],
                    backgroundColor: [
                        'rgba(72, 149, 239, 0.8)',
                        'rgba(76, 201, 240, 0.8)',
                        'rgba(67, 97, 238, 0.8)'
                    ],
                    borderColor: [
                        'rgba(72, 149, 239, 1)',
                        'rgba(76, 201, 240, 1)',
                        'rgba(67, 97, 238, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        callbacks: {
                            label: context => {
                                const label = context.label || '';
                                const value = context.raw || 0;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
                                return `${label}: ₹${formatNumber(value)} (${percentage}%)`;
                            }
                        }
                    }
                }
            }
        });
        
        charts.overview.push(taxChart);
    }

    // Create sales by consignee chart
    function createSalesByConsigneeChart() {
        const ctx = document.getElementById('salesByConsigneeChart').getContext('2d');
        
        // Get top 10 consignees by sales
        const topConsignees = [...consigneeData]
            .sort((a, b) => b.totalValue - a.totalValue)
            .slice(0, 10);
        
        const salesByConsigneeChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: topConsignees.map(item => truncateString(item.consignee, 15)),
                datasets: [{
                    label: 'Sales by Consignee',
                    data: topConsignees.map(item => item.totalValue),
                    backgroundColor: 'rgba(67, 97, 238, 0.7)',
                    borderColor: 'rgba(67, 97, 238, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: value => '₹' + formatNumberShort(value)
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            title: tooltipItems => {
                                const index = tooltipItems[0].dataIndex;
                                return topConsignees[index].consignee;
                            },
                            label: context => '₹' + formatNumber(context.raw)
                        }
                    }
                }
            }
        });
        
        charts.sales.push(salesByConsigneeChart);
    }

    // Create tax distribution detail chart
    function createTaxDistributionDetailChart() {
        const ctx = document.getElementById('taxDistributionDetailChart').getContext('2d');
        
        // Calculate tax amounts by rate
        const taxRates = {
            'GST 28%': { cgst: 0, sgst: 0, igst: 0 },
            'GST 18%': { cgst: 0, sgst: 0, igst: 0 },
            'GST 12%': { cgst: 0, sgst: 0, igst: 0 },
            'GST 5%': { cgst: 0, sgst: 0, igst: 0 }
        };
        
        rawData.forEach(row => {
            // GST 28%
            if (row['GST Sale @ 28%']) {
                taxRates['GST 28%'].cgst += parseFloat(row['Output CGST @ 14%'] || 0);
                taxRates['GST 28%'].sgst += parseFloat(row['Output SGST @ 14%'] || 0);
            }
            
            // GST 18%
            if (row['GST Sale @ 18%']) {
                taxRates['GST 18%'].cgst += parseFloat(row['Output CGST @ 9%'] || 0);
                taxRates['GST 18%'].sgst += parseFloat(row['Output SGST @ 9%'] || 0);
            }
            
            // IGST 18%
            if (row['GST Interstate Sale @ 18%']) {
                taxRates['GST 18%'].igst += parseFloat(row['Output IGST @ 18%'] || 0);
            }
        });
        
        const labels = Object.keys(taxRates);
        
        const taxDistributionChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'CGST',
                        data: labels.map(rate => taxRates[rate].cgst),
                        backgroundColor: 'rgba(72, 149, 239, 0.7)',
                        borderColor: 'rgba(72, 149, 239, 1)',
                        borderWidth: 1
                    },
                    {
                        label: 'SGST',
                        data: labels.map(rate => taxRates[rate].sgst),
                        backgroundColor: 'rgba(76, 201, 240, 0.7)',
                        borderColor: 'rgba(76, 201, 240, 1)',
                        borderWidth: 1
                    },
                    {
                        label: 'IGST',
                        data: labels.map(rate => taxRates[rate].igst),
                        backgroundColor: 'rgba(67, 97, 238, 0.7)',
                        borderColor: 'rgba(67, 97, 238, 1)',
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        stacked: false
                    },
                    y: {
                        stacked: false,
                        beginAtZero: true,
                        ticks: {
                            callback: value => '₹' + formatNumberShort(value)
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: context => {
                                const label = context.dataset.label || '';
                                return `${label}: ₹${formatNumber(context.raw)}`;
                            }
                        }
                    }
                }
            }
        });
        
        charts.tax.push(taxDistributionChart);
    }

    // Create monthly tax chart
    function createMonthlyTaxChart() {
        const ctx = document.getElementById('monthlyTaxChart').getContext('2d');
        
        // Group tax data by month
        const monthlyTax = {};
        
        taxData.forEach(item => {
            if (item.date) {
                const monthYear = item.date.toLocaleString('default', { month: 'short', year: 'numeric' });
                
                if (!monthlyTax[monthYear]) {
                    monthlyTax[monthYear] = {
                        cgst: 0,
                        sgst: 0,
                        igst: 0
                    };
                }
                
                monthlyTax[monthYear].cgst += item.cgst;
                monthlyTax[monthYear].sgst += item.sgst;
                monthlyTax[monthYear].igst += item.igst;
            }
        });
        
        // Sort months chronologically
        const months = Object.keys(monthlyTax).sort((a, b) => {
            return new Date(a) - new Date(b);
        });
        
        const monthlyTaxChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: months,
                datasets: [
                    {
                        label: 'CGST',
                        data: months.map(month => monthlyTax[month].cgst),
                        backgroundColor: 'rgba(72, 149, 239, 0.2)',
                        borderColor: 'rgba(72, 149, 239, 1)',
                        borderWidth: 2,
                        pointBackgroundColor: 'rgba(72, 149, 239, 1)',
                        tension: 0.2
                    },
                    {
                        label: 'SGST',
                        data: months.map(month => monthlyTax[month].sgst),
                        backgroundColor: 'rgba(76, 201, 240, 0.2)',
                        borderColor: 'rgba(76, 201, 240, 1)',
                        borderWidth: 2,
                        pointBackgroundColor: 'rgba(76, 201, 240, 1)',
                        tension: 0.2
                    },
                    {
                        label: 'IGST',
                        data: months.map(month => monthlyTax[month].igst),
                        backgroundColor: 'rgba(67, 97, 238, 0.2)',
                        borderColor: 'rgba(67, 97, 238, 1)',
                        borderWidth: 2,
                        pointBackgroundColor: 'rgba(67, 97, 238, 1)',
                        tension: 0.2
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: value => '₹' + formatNumberShort(value)
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: context => {
                                const label = context.dataset.label || '';
                                return `${label}: ₹${formatNumber(context.raw)}`;
                            }
                        }
                    }
                }
            }
        });
        
        charts.tax.push(monthlyTaxChart);
    }

    // Create top items chart
    function createTopItemsChart() {
        const ctx = document.getElementById('topItemsChart').getContext('2d');
        
        // Get top 10 items by value
        const topItems = [...stockData]
            .sort((a, b) => b.totalValue - a.totalValue)
            .slice(0, 10);
        
        const topItemsChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: topItems.map(item => truncateString(item.particulars, 15)),
                datasets: [{
                    label: 'Item Value',
                    data: topItems.map(item => item.totalValue),
                    backgroundColor: 'rgba(67, 97, 238, 0.7)',
                    borderColor: 'rgba(67, 97, 238, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        beginAtZero: true,
                        ticks: {
                            callback: value => '₹' + formatNumberShort(value)
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            title: tooltipItems => {
                                const index = tooltipItems[0].dataIndex;
                                return topItems[index].particulars;
                            },
                            label: context => '₹' + formatNumber(context.raw)
                        }
                    }
                }
            }
        });
        
        charts.stock.push(topItemsChart);
    }

    // Create revenue vs expenses chart
    function createRevenueExpensesChart() {
        const ctx = document.getElementById('revenueExpensesChart').getContext('2d');
        
        // Group by month
        const monthlyFinancials = {};
        
        accountsData.forEach(item => {
            if (item.date) {
                const monthYear = item.date.toLocaleString('default', { month: 'short', year: 'numeric' });
                
                if (!monthlyFinancials[monthYear]) {
                    monthlyFinancials[monthYear] = {
                        revenue: 0,
                        expenses: 0
                    };
                }
                
                monthlyFinancials[monthYear].revenue += item.credit;
                monthlyFinancials[monthYear].expenses += item.debit;
            }
        });
        
        // Sort months chronologically
        const months = Object.keys(monthlyFinancials).sort((a, b) => {
            return new Date(a) - new Date(b);
        });
        
        const revenueExpensesChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: months,
                datasets: [
                    {
                        label: 'Revenue',
                        data: months.map(month => monthlyFinancials[month].revenue),
                        backgroundColor: 'rgba(76, 201, 240, 0.7)',
                        borderColor: 'rgba(76, 201, 240, 1)',
                        borderWidth: 1
                    },
                    {
                        label: 'Expenses',
                        data: months.map(month => monthlyFinancials[month].expenses),
                        backgroundColor: 'rgba(247, 37, 133, 0.7)',
                        borderColor: 'rgba(247, 37, 133, 1)',
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: value => '₹' + formatNumberShort(value)
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: context => {
                                const label = context.dataset.label || '';
                                return `${label}: ₹${formatNumber(context.raw)}`;
                            }
                        }
                    }
                }
            }
        });
        
        charts.accounts.push(revenueExpensesChart);
    }

    // Create income breakdown chart
    function createIncomeBreakdownChart() {
        const ctx = document.getElementById('incomeBreakdownChart').getContext('2d');
        
        // Calculate income breakdown
        const incomeBreakdown = {
            'Sales': 0,
            'Commission': 0,
            'Freight Charges': 0,
            'Other Income': 0
        };
        
        // Extract income breakdowns from raw data
        rawData.forEach(row => {
            incomeBreakdown['Sales'] += 
                parseFloat(row['GST Sale @ 28%'] || 0) + 
                parseFloat(row['GST Sale @ 18%'] || 0) + 
                parseFloat(row['GST Interstate Sale @ 18%'] || 0) +
                parseFloat(row['Cash Sales'] || 0);
                
            incomeBreakdown['Commission'] += parseFloat(row['Commission Recivable A/c'] || 0);
            incomeBreakdown['Freight Charges'] += parseFloat(row['Fright Charge Recived'] || 0);
            incomeBreakdown['Other Income'] += 
                parseFloat(row['Transport Charge'] || 0) + 
                parseFloat(row['Fuel,Petrol and Diesel Charges'] || 0);
        });
        
        const labels = Object.keys(incomeBreakdown);
        
        const incomeBreakdownChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: labels,
                datasets: [{
                    data: labels.map(key => incomeBreakdown[key]),
                    backgroundColor: [
                        'rgba(67, 97, 238, 0.7)',
                        'rgba(76, 201, 240, 0.7)',
                        'rgba(72, 149, 239, 0.7)',
                        'rgba(63, 55, 201, 0.7)'
                    ],
                    borderColor: [
                        'rgba(67, 97, 238, 1)',
                        'rgba(76, 201, 240, 1)',
                        'rgba(72, 149, 239, 1)',
                        'rgba(63, 55, 201, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: context => {
                                const label = context.label || '';
                                const value = context.raw || 0;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
                                return `${label}: ₹${formatNumber(value)} (${percentage}%)`;
                            }
                        }
                    }
                }
            }
        });
        
        charts.accounts.push(incomeBreakdownChart);
    }

    // Create top consignees chart
    function createTopConsigneesChart() {
        const ctx = document.getElementById('topConsigneesChart').getContext('2d');
        
        // Get top 10 consignees by value
        const topConsignees = [...consigneeData]
            .sort((a, b) => b.totalValue - a.totalValue)
            .slice(0, 10);
        
        const topConsigneesChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: topConsignees.map(item => truncateString(item.consignee, 15)),
                datasets: [{
                    label: 'Total Value',
                    data: topConsignees.map(item => item.totalValue),
                    backgroundColor: 'rgba(67, 97, 238, 0.7)',
                    borderColor: 'rgba(67, 97, 238, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        beginAtZero: true,
                        ticks: {
                            callback: value => '₹' + formatNumberShort(value)
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            title: tooltipItems => {
                                const index = tooltipItems[0].dataIndex;
                                return topConsignees[index].consignee;
                            },
                            label: context => '₹' + formatNumber(context.raw)
                        }
                    }
                }
            }
        });
        
        charts.consignee.push(topConsigneesChart);
    }

    // Create consignee frequency chart
    function createConsigneeFrequencyChart() {
        const ctx = document.getElementById('consigneeFrequencyChart').getContext('2d');
        
        // Count consignees by transaction frequency
        const frequencyBuckets = {
            '1 transaction': 0,
            '2-5 transactions': 0,
            '6-10 transactions': 0,
            '11-20 transactions': 0,
            '21+ transactions': 0
        };
        
        consigneeData.forEach(item => {
            if (item.transactions === 1) {
                frequencyBuckets['1 transaction']++;
            } else if (item.transactions >= 2 && item.transactions <= 5) {
                frequencyBuckets['2-5 transactions']++;
            } else if (item.transactions >= 6 && item.transactions <= 10) {
                frequencyBuckets['6-10 transactions']++;
            } else if (item.transactions >= 11 && item.transactions <= 20) {
                frequencyBuckets['11-20 transactions']++;
            } else if (item.transactions > 20) {
                frequencyBuckets['21+ transactions']++;
            }
        });
        
        const labels = Object.keys(frequencyBuckets);
        
        const consigneeFrequencyChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: labels.map(key => frequencyBuckets[key]),
                    backgroundColor: [
                        'rgba(67, 97, 238, 0.7)',
                        'rgba(76, 201, 240, 0.7)',
                        'rgba(72, 149, 239, 0.7)',
                        'rgba(63, 55, 201, 0.7)',
                        'rgba(247, 37, 133, 0.7)'
                    ],
                    borderColor: [
                        'rgba(67, 97, 238, 1)',
                        'rgba(76, 201, 240, 1)',
                        'rgba(72, 149, 239, 1)',
                        'rgba(63, 55, 201, 1)',
                        'rgba(247, 37, 133, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: context => {
                                const label = context.label || '';
                                const value = context.raw || 0;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
                                return `${label}: ${value} consignees (${percentage}%)`;
                            }
                        }
                    }
                }
            }
        });
        
        charts.consignee.push(consigneeFrequencyChart);
    }

    // Update dashboard stats
    function updateDashboardStats() {
        // Calculate total sales
        const totalSales = salesData.reduce((sum, item) => sum + item.totalAmount, 0);
        document.getElementById('totalSales').textContent = formatCurrency(totalSales);
        
        // Calculate total tax
        const totalTax = taxData.reduce((sum, item) => sum + item.totalTax, 0);
        document.getElementById('totalTax').textContent = formatCurrency(totalTax);
        
        // Calculate total transactions
        const totalTransactions = salesData.length;
        document.getElementById('totalTransactions').textContent = totalTransactions;
        
        // Calculate unique consignees
        const uniqueConsignees = new Set(salesData.map(item => item.consignee)).size;
        document.getElementById('uniqueConsignees').textContent = uniqueConsignees;
        
        // Sales report stats
        document.getElementById('salesTotal').textContent = formatCurrency(totalSales);
        document.getElementById('salesAverage').textContent = formatCurrency(totalTransactions > 0 ? totalSales / totalTransactions : 0);
        document.getElementById('salesHighest').textContent = formatCurrency(Math.max(...salesData.map(item => item.totalAmount)));
        document.getElementById('salesCount').textContent = totalTransactions;
        
        // Tax report stats
        const totalCGST = taxData.reduce((sum, item) => sum + item.cgst, 0);
        const totalSGST = taxData.reduce((sum, item) => sum + item.sgst, 0);
        const totalIGST = taxData.reduce((sum, item) => sum + item.igst, 0);
        
        document.getElementById('totalCGST').textContent = formatCurrency(totalCGST);
        document.getElementById('totalSGST').textContent = formatCurrency(totalSGST);
        document.getElementById('totalIGST').textContent = formatCurrency(totalIGST);
        document.getElementById('taxTotal').textContent = formatCurrency(totalTax);
        
        // Stock report stats
        const totalStockItems = stockData.length;
        const totalStockValue = stockData.reduce((sum, item) => sum + item.totalValue, 0);
        const totalQuantity = stockData.reduce((sum, item) => sum + item.totalQuantity, 0);
        
        document.getElementById('totalStockItems').textContent = totalStockItems;
        document.getElementById('totalStockValue').textContent = formatCurrency(totalStockValue);
        document.getElementById('totalQuantity').textContent = formatNumber(totalQuantity);
        document.getElementById('avgItemValue').textContent = formatCurrency(totalStockItems > 0 ? totalStockValue / totalStockItems : 0);
        
        // Accounts report stats
        const totalRevenue = accountsData.reduce((sum, item) => sum + item.credit, 0);
        const totalExpenses = accountsData.reduce((sum, item) => sum + item.debit, 0);
        const netProfit = totalRevenue - totalExpenses;
        const profitMargin = totalRevenue > 0 ? (netProfit / totalRevenue) * 100 : 0;
        
        document.getElementById('totalRevenue').textContent = formatCurrency(totalRevenue);
        document.getElementById('totalExpenses').textContent = formatCurrency(totalExpenses);
        document.getElementById('netProfit').textContent = formatCurrency(netProfit);
        document.getElementById('profitMargin').textContent = `${profitMargin.toFixed(2)}%`;
        
        // Consignee report stats
        const totalConsignees = consigneeData.length;
        const topConsigneeValue = consigneeData.length > 0 ? consigneeData[0].totalValue : 0;
        const avgConsigneeValue = totalConsignees > 0 ? totalSales / totalConsignees : 0;
        
        // Calculate active consignees (with transactions in last 90 days)
        const now = new Date();
        const ninetyDaysAgo = new Date(now.setDate(now.getDate() - 90));
        const activeConsignees = consigneeData.filter(item => 
            item.lastTransaction && item.lastTransaction >= ninetyDaysAgo
        ).length;
        
        document.getElementById('totalConsignees').textContent = totalConsignees;
        document.getElementById('topConsigneeValue').textContent = formatCurrency(topConsigneeValue);
        document.getElementById('avgConsigneeValue').textContent = formatCurrency(avgConsigneeValue);
        document.getElementById('activeConsignees').textContent = activeConsignees;
    }

    // Filter table based on search query
    function filterTable(tableId, query) {
        const table = document.getElementById(tableId);
        const rows = table.querySelectorAll('tbody tr');
        
        if (!query) {
            rows.forEach(row => {
                row.style.display = '';
            });
            return;
        }
        
        const lowercaseQuery = query.toLowerCase();
        
        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            if (text.includes(lowercaseQuery)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }

    // Export data to CSV
    function exportData(reportType) {
        let data;
        let filename;
        
        switch (reportType) {
            case 'sales':
                data = salesData;
                filename = 'sales_report.csv';
                break;
            case 'tax':
                data = taxData;
                filename = 'tax_report.csv';
                break;
            case 'stock':
                data = stockData;
                filename = 'stock_report.csv';
                break;
            case 'accounts':
                data = accountsData;
                filename = 'accounts_report.csv';
                break;
            case 'consignee':
                data = consigneeData;
                filename = 'consignee_report.csv';
                break;
            case 'rawData':
                data = rawData;
                filename = 'raw_data.csv';
                break;
            default:
                return;
        }
        
        if (!data || data.length === 0) {
            alert('No data to export');
            return;
        }
        
        // Convert data to CSV
        const headers = Object.keys(data[0]);
        let csv = headers.join(',') + '\n';
        
        data.forEach(row => {
            const values = headers.map(header => {
                const value = row[header];
                // Wrap values in quotes if they contain commas
                if (typeof value === 'string' && value.includes(',')) {
                    return `"${value}"`;
                }
                return value;
            });
            csv += values.join(',') + '\n';
        });
        
        // Create download link
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    // Helper functions
    
function parseDate(dateStr) {
    if (!dateStr) return null;

    // Check if dateStr is a number or numeric string (Excel date serial)
    if (typeof dateStr === 'number' || (!isNaN(dateStr) && dateStr !== '')) {
        // Convert Excel date serial to JS Date
        // Excel date serial starts from 1900-01-01 as 1, JS Date starts from 1899-12-30
        const excelEpoch = new Date(Date.UTC(1899, 11, 30));
        const days = Number(dateStr);
        const msPerDay = 24 * 60 * 60 * 1000;
        const date = new Date(excelEpoch.getTime() + days * msPerDay);
        if (!isNaN(date.getTime())) {
            return date;
        }
    }

    // Try different date formats
    const formats = [
        // MM/DD/YYYY
        str => {
            const parts = str.split('/');
            if (parts.length === 3) {
                return new Date(parts[2], parts[0] - 1, parts[1]);
            }
            return null;
        },
        // DD/MM/YYYY
        str => {
            const parts = str.split('/');
            if (parts.length === 3) {
                return new Date(parts[2], parts[1] - 1, parts[0]);
            }
            return null;
        },
        // YYYY-MM-DD
        str => {
            const parts = str.split('-');
            if (parts.length === 3) {
                return new Date(parts[0], parts[1] - 1, parts[2]);
            }
            return null;
        }
    ];

    // Try each format until one works
    for (const format of formats) {
        const date = format(dateStr.toString());
        if (date && !isNaN(date.getTime())) {
            return date;
        }
    }

    // If all else fails, try native parsing
    const date = new Date(dateStr);
    if (!isNaN(date.getTime())) {
        return date;
    }

    return null;
}

    // Format date as string
    function formatDate(date) {
        if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
            return '';
        }
        
        const day = String(date.getDate()).padStart(2, '0');
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const year = date.getFullYear();
        
        return `${day}/${month}/${year}`;
    }

    // Format date for input fields
    function formatDateForInput(date) {
        if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
            return '';
        }
        
        const day = String(date.getDate()).padStart(2, '0');
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const year = date.getFullYear();
        
        return `${year}-${month}-${day}`;
    }

    // Format number with commas
    function formatNumber(num) {
        if (num === null || num === undefined || isNaN(num)) {
            return '0';
        }
        return parseFloat(num).toLocaleString('en-IN');
    }

    // Format currency
    function formatCurrency(num) {
        if (num === null || num === undefined || isNaN(num)) {
            return '₹0';
        }
        return '₹' + parseFloat(num).toLocaleString('en-IN', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }

    // Format number with shortened suffix (K, M, B)
    function formatNumberShort(num) {
        if (num === null || num === undefined || isNaN(num)) {
            return '0';
        }
        
        num = parseFloat(num);
        
        if (num >= 1000000000) {
            return (num / 1000000000).toFixed(1) + 'B';
        }
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1) + 'M';
        }
        if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'K';
        }
        return num.toFixed(0);
    }

    // Truncate string if too long
    function truncateString(str, maxLength) {
        if (!str) return '';
        if (str.length <= maxLength) return str;
        return str.substring(0, maxLength) + '...';
    }

    // Extract CGST value from row
    function getCGSTValue(row) {
        return parseFloat(row['Output CGST @ 14%'] || 0) + parseFloat(row['Output CGST @ 9%'] || 0);
    }

    // Extract SGST value from row
    function getSGSTValue(row) {
        return parseFloat(row['Output SGST @ 14%'] || 0) + parseFloat(row['Output SGST @ 9%'] || 0);
    }

    // Extract IGST value from row
    function getIGSTValue(row) {
        return parseFloat(row['Output IGST @ 18%'] || 0);
    }

    // Calculate total tax
    function getTotalTaxValue(row) {
        return getCGSTValue(row) + getSGSTValue(row) + getIGSTValue(row);
    }
</script> uploading and mapping and porcessing not working rewrite without css full code