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

$currentUserId = $_SESSION['uid'];

// Get all customers for dropdown
$customersQuery = "SELECT ID, CustomerID, CustomerName, Mobile, City FROM tblcustomers WHERE Status = 'Active' ORDER BY CustomerName";
$customersResult = mysqli_query($con, $customersQuery);
$availableCustomers = [];
if ($customersResult) {
    while ($customer = mysqli_fetch_assoc($customersResult)) {
        $availableCustomers[] = $customer;
    }
}

// Get sales types for dropdown
$salesTypesQuery = "SELECT ID, SalesType, InvoicePrefix, Description FROM tblsales_type_config WHERE IsActive = 1 ORDER BY SalesType";
$salesTypesResult = mysqli_query($con, $salesTypesQuery);
$availableSalesTypes = [];
if ($salesTypesResult) {
    while ($type = mysqli_fetch_assoc($salesTypesResult)) {
        $availableSalesTypes[] = $type;
    }
}

// Get categories for dropdown
$categoriesQuery = "SELECT ID, CategoryName FROM tblcategories WHERE Status = 'Active' ORDER BY CategoryName";
$categoriesResult = mysqli_query($con, $categoriesQuery);
$availableCategories = [];
if ($categoriesResult) {
    while ($cat = mysqli_fetch_assoc($categoriesResult)) {
        $availableCategories[] = $cat;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Category-wise Sales Report | UZRS Inventory</title>
    
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <link href="css/category-wise-sales-report.css" rel="stylesheet">
</head>

<body id="page-top">
    <div id="wrapper">
        <?php include_once('../includes/sidebar.php'); ?>
        
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('../includes/topbar.php'); ?>
                
                <div class="container-fluid">
                    <!-- Navigation Buttons -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-3">
                        <div>
                            <a href="index.php" class="btn btn-sm btn-primary shadow-sm">
                                <i class="fas fa-arrow-left fa-sm text-white-50"></i> Back to Reports Dashboard
                            </a>
                            <a href="../dashboard.php" class="btn btn-sm btn-secondary shadow-sm">
                                <i class="fas fa-home fa-sm text-white-50"></i> Home
                            </a>
                        </div>
                    </div>
                    
                    <div class="report-container">
                        <div class="report-header">
                            <div class="company-name">UZRS Inventory System</div>
                            <h1>Category-wise Sales Report</h1>
                            <div class="report-meta">
                                <span id="reportPeriod">Select date range to view report</span>
                            </div>
                        </div>
                        
                        <div class="filter-section">
                            <div class="quick-filters">
                                <button class="quick-filter-btn" onclick="setQuickFilter('today')">Today</button>
                                <button class="quick-filter-btn" onclick="setQuickFilter('yesterday')">Yesterday</button>
                                <button class="quick-filter-btn" onclick="setQuickFilter('thisWeek')">This Week</button>
                                <button class="quick-filter-btn" onclick="setQuickFilter('lastWeek')">Last Week</button>
                                <button class="quick-filter-btn" onclick="setQuickFilter('thisMonth')">This Month</button>
                                <button class="quick-filter-btn" onclick="setQuickFilter('lastMonth')">Last Month</button>
                                <button class="quick-filter-btn" onclick="setQuickFilter('thisYear')">This Year</button>
                                <button class="quick-filter-btn" onclick="setQuickFilter('custom')">Custom Range</button>
                            </div>
                            
                            <div class="filter-row">
                                <div class="filter-group">
                                    <label>Category</label>
                                    <select id="categoryFilter" class="form-control">
                                        <option value="">All Categories</option>
                                        <?php foreach ($availableCategories as $category): ?>
                                            <option value="<?php echo htmlspecialchars($category['ID']); ?>">
                                                <?php echo htmlspecialchars($category['CategoryName']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="filter-group">
                                    <label>Customer</label>
                                    <select id="customerFilter" class="form-control">
                                        <option value="">All Customers</option>
                                        <?php foreach ($availableCustomers as $customer): ?>
                                            <option value="<?php echo htmlspecialchars($customer['CustomerID']); ?>">
                                                <?php echo htmlspecialchars($customer['CustomerName']); ?>
                                                <?php if ($customer['City']): ?>
                                                    - <?php echo htmlspecialchars($customer['City']); ?>
                                                <?php endif; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="filter-group">
                                    <label>Sales Type</label>
                                    <select id="salesTypeFilter" class="form-control">
                                        <option value="">All Types</option>
                                        <?php foreach ($availableSalesTypes as $type): ?>
                                            <option value="<?php echo htmlspecialchars($type['SalesType']); ?>">
                                                <?php echo htmlspecialchars($type['SalesType']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="filter-group">
                                    <button class="btn-filter" onclick="loadReport()">
                                        <i class="fas fa-search"></i> Generate Report
                                    </button>
                                </div>
                                
                                <div class="filter-group">
                                    <button class="btn-print" onclick="openPrintView()">
                                        <i class="fas fa-print"></i> Print
                                    </button>
                                </div>
                                
                                <div class="filter-group">
                                    <button class="btn-export" onclick="exportToExcel()">
                                        <i class="fas fa-file-excel"></i> Export
                                    </button>
                                </div>
                            </div>
                            
                            <div class="custom-dates-row" id="customDatesRow">
                                <div class="filter-group">
                                    <label>Start Date</label>
                                    <input type="date" id="startDate" class="form-control" value="<?php echo date('Y-m-01'); ?>">
                                </div>
                                
                                <div class="filter-group">
                                    <label>End Date</label>
                                    <input type="date" id="endDate" class="form-control" value="<?php echo date('Y-m-t'); ?>">
                                </div>
                            </div>
                        </div>
                        
                        <div id="loadingState" class="loading" style="display: none;">
                            <i class="fas fa-spinner fa-spin"></i> Loading report data...
                        </div>
                        
                        <div id="reportContent" style="display: none;">
                            <div class="summary-cards">
                                <div class="summary-card">
                                    <h3>Total Categories</h3>
                                    <div class="amount" id="totalCategories">0</div>
                                </div>
                                
                                <div class="summary-card">
                                    <h3>Total Items</h3>
                                    <div class="amount" id="totalItems">0</div>
                                </div>
                                
                                <div class="summary-card">
                                    <h3>Total Quantity</h3>
                                    <div class="amount" id="totalQuantity">0</div>
                                </div>
                                
                                <div class="summary-card">
                                    <h3>Gross Amount</h3>
                                    <div class="amount" id="totalAmount">₹0.00</div>
                                </div>
                                
                                <div class="summary-card">
                                    <h3>Total Discount</h3>
                                    <div class="amount" id="totalDiscount">₹0.00</div>
                                </div>
                                
                                <div class="summary-card highlight">
                                    <h3>Net Sales</h3>
                                    <div class="amount" id="totalSales">₹0.00</div>
                                </div>
                                
                                <div class="summary-card success">
                                    <h3>Total Profit</h3>
                                    <div class="amount" id="totalProfit">₹0.00</div>
                                </div>
                                
                                <div class="summary-card">
                                    <h3>Profit Margin</h3>
                                    <div class="amount" id="avgProfitMargin">0.00%</div>
                                </div>
                            </div>
                            
                            <h2 class="section-title">Category Sales Details <span id="categoryCount" style="font-size: 14px; color: #858796;">(0)</span></h2>
                            
                            <div class="table-responsive">
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th style="width: 5%;">S.No</th>
                                            <th style="width: 20%;">Category Name</th>
                                            <th style="width: 8%;" class="text-center">Items Count</th>
                                            <th style="width: 8%;" class="text-right">Quantity</th>
                                            <th style="width: 10%;" class="text-right">Avg Rate</th>
                                            <th style="width: 10%;" class="text-right">Gross Amount</th>
                                            <th style="width: 8%;" class="text-right">Discount</th>
                                            <th style="width: 10%;" class="text-right">Net Sales</th>
                                            <th style="width: 10%;" class="text-right">Total Profit</th>
                                            <th style="width: 6%;" class="text-right">Margin %</th>
                                            <th style="width: 5%;" class="text-center">% of Total</th>
                                        </tr>
                                    </thead>
                                    <tbody id="categoriesTableBody">
                                        <tr>
                                            <td colspan="11" class="no-data">No data available. Please select filters and generate report.</td>
                                        </tr>
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td colspan="3" class="text-right"><strong>TOTALS:</strong></td>
                                            <td class="text-right" id="totalQuantityFooter">0</td>
                                            <td class="text-right">-</td>
                                            <td class="text-right" id="totalAmountFooter">₹0.00</td>
                                            <td class="text-right" id="totalDiscountFooter">₹0.00</td>
                                            <td class="text-right" id="totalSalesFooter">₹0.00</td>
                                            <td class="text-right" id="totalProfitFooter">₹0.00</td>
                                            <td class="text-right" id="avgMarginFooter">0.00%</td>
                                            <td class="text-center">100%</td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <?php include_once('../includes/footer.php'); ?>
        </div>
    </div>
    
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>
    
    <!-- Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script src="js/category-wise-sales-report.js"></script>
</body>
</html>
