<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$report_type = isset($_GET['type']) ? $_GET['type'] : 'sales';
$from_date = isset($_GET['from_date']) ? $_GET['from_date'] : date('Y-m-01');
$to_date = isset($_GET['to_date']) ? $_GET['to_date'] : date('Y-m-d');

// ============================================
// SALES REPORT DATA
// ============================================
$sales_sql = "SELECT ls.*, c.name as customer_name 
              FROM lube_sales ls
              LEFT JOIN customers c ON ls.customer_id = c.id
              WHERE DATE(ls.sale_date) BETWEEN '$from_date' AND '$to_date'
              ORDER BY ls.id DESC";
$sales_result = mysqli_query($conn, $sales_sql);

$total_sales_amount = 0;
$total_walkin = 0;
$total_credit = 0;
while($row = mysqli_fetch_assoc($sales_result)) {
    $total_sales_amount += $row['total_amount'];
    if($row['customer_type'] == 'walkin') $total_walkin += $row['total_amount'];
    else $total_credit += $row['total_amount'];
}
mysqli_data_seek($sales_result, 0);

// ============================================
// COGS (COST OF GOODS SOLD) CALCULATION
// ============================================
$cogs_sql = "SELECT 
                SUM(lsi.quantity * lp.purchase_price) as total_cogs
             FROM lube_sale_items lsi
             JOIN lube_products lp ON lsi.product_id = lp.id
             JOIN lube_sales ls ON lsi.sale_id = ls.id
             WHERE DATE(ls.sale_date) BETWEEN '$from_date' AND '$to_date'";
$cogs_result = mysqli_query($conn, $cogs_sql);
$cogs_data = mysqli_fetch_assoc($cogs_result);
$total_cogs = $cogs_data['total_cogs'] ?? 0;

// ============================================
// PURCHASE REPORT DATA WITH PRODUCT DETAILS
// ============================================
$purchase_sql = "SELECT lp.*, s.name as supplier_name 
                 FROM lube_purchases lp
                 LEFT JOIN suppliers s ON lp.supplier_id = s.id
                 WHERE DATE(lp.purchase_date) BETWEEN '$from_date' AND '$to_date'
                 ORDER BY lp.id DESC";
$purchase_result = mysqli_query($conn, $purchase_sql);
$total_purchase_amount = 0;

// Store purchase data with items
$purchases_with_items = [];
while($row = mysqli_fetch_assoc($purchase_result)) {
    $total_purchase_amount += $row['total_amount'];
    
    // Get items for this purchase
    $items_sql = "SELECT lpi.*, lp.product_name, lp.product_code, lp.purchase_price as product_purchase_price
                  FROM lube_purchase_items lpi
                  JOIN lube_products lp ON lpi.product_id = lp.id
                  WHERE lpi.purchase_id = '{$row['id']}'";
    $items_result = mysqli_query($conn, $items_sql);
    $items = [];
    while($item = mysqli_fetch_assoc($items_result)) {
        $items[] = $item;
    }
    $row['items'] = $items;
    $purchases_with_items[] = $row;
}
mysqli_data_seek($purchase_result, 0);

// ============================================
// STOCK REPORT - Low Stock Products
// ============================================
$low_stock_sql = "SELECT * FROM lube_products WHERE current_stock <= minimum_stock AND minimum_stock > 0 ORDER BY current_stock ASC";
$low_stock_result = mysqli_query($conn, $low_stock_sql);

// ============================================
// TOP SELLING PRODUCTS with COGS and Profit
// ============================================
$top_products_sql = "SELECT 
                        lp.product_name, 
                        lp.product_code, 
                        lp.purchase_price,
                        SUM(lsi.quantity) as total_sold, 
                        SUM(lsi.total) as total_sales_value,
                        SUM(lsi.quantity * lp.purchase_price) as total_cogs,
                        SUM(lsi.total) - SUM(lsi.quantity * lp.purchase_price) as total_profit
                     FROM lube_sale_items lsi
                     JOIN lube_products lp ON lsi.product_id = lp.id
                     JOIN lube_sales ls ON lsi.sale_id = ls.id
                     WHERE DATE(ls.sale_date) BETWEEN '$from_date' AND '$to_date'
                     GROUP BY lp.id
                     ORDER BY total_sold DESC
                     LIMIT 10";
$top_products_result = mysqli_query($conn, $top_products_sql);

// ============================================
// CALCULATE PROFIT MARGIN
// ============================================
$gross_profit = $total_sales_amount - $total_cogs;
$profit_margin = $total_sales_amount > 0 ? ($gross_profit / $total_sales_amount) * 100 : 0;
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<div class="lube-reports-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-chart-bar"></i> Lube Reports</h2>
            <p>Sales, Purchase and Inventory Reports</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-calendar"></i>
                <span><?php echo date('d-m-Y'); ?></span>
            </div>
        </div>
    </div>

    <!-- Report Type Tabs -->
    <div class="report-tabs">
        <a href="?type=sales&from_date=<?php echo $from_date; ?>&to_date=<?php echo $to_date; ?>" class="tab-btn <?php echo $report_type == 'sales' ? 'active' : ''; ?>">
            <i class="fas fa-chart-line"></i> Sales Report
        </a>
        <a href="?type=purchase&from_date=<?php echo $from_date; ?>&to_date=<?php echo $to_date; ?>" class="tab-btn <?php echo $report_type == 'purchase' ? 'active' : ''; ?>">
            <i class="fas fa-shopping-cart"></i> Purchase Report
        </a>
        <a href="?type=stock&from_date=<?php echo $from_date; ?>&to_date=<?php echo $to_date; ?>" class="tab-btn <?php echo $report_type == 'stock' ? 'active' : ''; ?>">
            <i class="fas fa-boxes"></i> Stock Report
        </a>
        <a href="?type=profit&from_date=<?php echo $from_date; ?>&to_date=<?php echo $to_date; ?>" class="tab-btn <?php echo $report_type == 'profit' ? 'active' : ''; ?>">
            <i class="fas fa-chart-pie"></i> Profit Report
        </a>
    </div>

    <!-- Filter Card -->
    <div class="filter-card">
        <div class="filter-header">
            <i class="fas fa-filter"></i> Filter by Date
        </div>
        <div class="filter-body">
            <form method="GET" action="" class="filter-form">
                <input type="hidden" name="type" value="<?php echo $report_type; ?>">
                <div class="filter-row">
                    <div class="filter-group">
                        <label><i class="fas fa-calendar-alt"></i> From Date</label>
                        <input type="date" name="from_date" class="form-control-modern" value="<?php echo $from_date; ?>">
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-calendar-alt"></i> To Date</label>
                        <input type="date" name="to_date" class="form-control-modern" value="<?php echo $to_date; ?>">
                    </div>
                    <div class="filter-actions">
                        <button type="submit" class="btn-search"><i class="fas fa-search"></i> Apply Filter</button>
                        <button type="button" onclick="window.print()" class="btn-print"><i class="fas fa-print"></i> Print</button>
                        <button type="button" class="btn-pdf" onclick="downloadPDF()">
                            <i class="fas fa-file-pdf"></i> Download PDF
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Summary Cards (visible on all tabs) -->
    <div class="summary-cards">
        <div class="summary-card">
            <div class="summary-icon sales-icon"><i class="fas fa-chart-line"></i></div>
            <div class="summary-content">
                <h4>Rs <?php echo number_format($total_sales_amount, 2); ?></h4>
                <p>Total Sales</p>
                <small><?php echo date('d-m-Y', strtotime($from_date)); ?> to <?php echo date('d-m-Y', strtotime($to_date)); ?></small>
            </div>
        </div>
        <div class="summary-card">
            <div class="summary-icon purchase-icon"><i class="fas fa-shopping-cart"></i></div>
            <div class="summary-content">
                <h4>Rs <?php echo number_format($total_cogs, 2); ?></h4>
                <p>COGS (Cost of Goods Sold)</p>
                <small>Actual cost of sold products</small>
            </div>
        </div>
        <div class="summary-card">
            <div class="summary-icon profit-icon"><i class="fas fa-chart-pie"></i></div>
            <div class="summary-content">
                <h4 class="profit-text">Rs <?php echo number_format($gross_profit, 2); ?></h4>
                <p>Gross Profit</p>
                <small>Sales - COGS</small>
            </div>
        </div>
        <div class="summary-card">
            <div class="summary-icon margin-icon"><i class="fas fa-percent"></i></div>
            <div class="summary-content">
                <h4><?php echo number_format($profit_margin, 2); ?>%</h4>
                <p>Profit Margin</p>
                <small>Gross margin percentage</small>
            </div>
        </div>
    </div>

    <!-- Report Content Wrappers (for PDF capture) -->
    <?php if($report_type == 'sales'): ?>
        <div id="report-content-sales">
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-list"></i>
                        <h4>Sales Transactions</h4>
                    </div>
                    <div class="table-stats">
                        Walk-in: Rs <?php echo number_format($total_walkin, 2); ?> | 
                        Credit: Rs <?php echo number_format($total_credit, 2); ?>
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th>Invoice No</th>
                                    <th>Date</th>
                                    <th>Customer Type</th>
                                    <th>Customer</th>
                                    <th>Subtotal</th>
                                    <th>Discount</th>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(mysqli_num_rows($sales_result) > 0): ?>
                                    <?php while($sale = mysqli_fetch_assoc($sales_result)): ?>
                                        <tr>
                                            <td data-label="Invoice No"><?php echo $sale['sale_invoice']; ?></td>
                                            <td data-label="Date"><?php echo date('d-m-Y', strtotime($sale['sale_date'])); ?></td>
                                            <td data-label="Customer Type"><?php echo ucfirst($sale['customer_type']); ?></td>
                                            <td data-label="Customer"><?php echo $sale['customer_name'] ?: '-'; ?></td>
                                            <td data-label="Subtotal">Rs <?php echo number_format($sale['subtotal'], 2); ?></td>
                                            <td data-label="Discount">Rs <?php echo number_format($sale['discount'], 2); ?></td>
                                            <td data-label="Total"><strong>Rs <?php echo number_format($sale['total_amount'], 2); ?></strong></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="7" class="empty-state">No sales found</div></tr>
                                <?php endif; ?>
                            </tbody>
                            <tfoot>
                                <tr class="totals-row">
                                    <td colspan="6"><strong>Total Sales</strong></td>
                                    <td><strong>Rs <?php echo number_format($total_sales_amount, 2); ?></strong></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    <?php elseif($report_type == 'purchase'): ?>
        <div id="report-content-purchase">
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-list"></i>
                        <h4>Purchase Transactions with Product Details</h4>
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="modern-table purchase-table">
                            <thead>
                                <tr>
                                    <th>Invoice No</th>
                                    <th>Date</th>
                                    <th>Supplier</th>
                                    <th>Product</th>
                                    <th>Quantity</th>
                                    <th>Unit Price</th>
                                    <th>Total</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(count($purchases_with_items) > 0): ?>
                                    <?php foreach($purchases_with_items as $purchase): 
                                        $item_count = count($purchase['items']);
                                        $rowspan = $item_count > 0 ? $item_count : 1;
                                    ?>
                                        <?php if($item_count > 0): ?>
                                            <?php $first = true; foreach($purchase['items'] as $item): ?>
                                                <tr>
                                                    <?php if($first): ?>
                                                        <td data-label="Invoice No" rowspan="<?php echo $rowspan; ?>"><?php echo $purchase['purchase_invoice']; ?></td>
                                                        <td data-label="Date" rowspan="<?php echo $rowspan; ?>"><?php echo date('d-m-Y', strtotime($purchase['purchase_date'])); ?></td>
                                                        <td data-label="Supplier" rowspan="<?php echo $rowspan; ?>"><?php echo htmlspecialchars($purchase['supplier_name']); ?></td>
                                                    <?php endif; ?>
                                                    <td data-label="Product">
                                                        <strong><?php echo htmlspecialchars($item['product_name']); ?></strong>
                                                        <br><small><?php echo $item['product_code']; ?></small>
                                                    </div>
                                                    <td data-label="Quantity"><?php echo number_format($item['quantity'], 2); ?> <?php echo $item['pack_size'] ?? 'units'; ?></div>
                                                    <td data-label="Unit Price">Rs <?php echo number_format($item['purchase_price'], 2); ?></div>
                                                    <td data-label="Total">Rs <?php echo number_format($item['total'], 2); ?></div>
                                                    <?php if($first): ?>
                                                        <td data-label="Status" rowspan="<?php echo $rowspan; ?>">
                                                            <span class="status-badge <?php echo $purchase['status'] == 'completed' ? 'status-completed' : 'status-pending'; ?>">
                                                                <?php echo ucfirst($purchase['status']); ?>
                                                            </span>
                                                        </div>
                                                    <?php endif; ?>
                                                </tr>
                                            <?php $first = false; endforeach; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td data-label="Invoice No"><?php echo $purchase['purchase_invoice']; ?></td>
                                                <td data-label="Date"><?php echo date('d-m-Y', strtotime($purchase['purchase_date'])); ?></td>
                                                <td data-label="Supplier"><?php echo htmlspecialchars($purchase['supplier_name']); ?></td>
                                                <td data-label="Product">-</div>
                                                <td data-label="Quantity">-</div>
                                                <td data-label="Unit Price">-</div>
                                                <td data-label="Total">Rs <?php echo number_format($purchase['total_amount'], 2); ?></div>
                                                <td data-label="Status">
                                                    <span class="status-badge <?php echo $purchase['status'] == 'completed' ? 'status-completed' : 'status-pending'; ?>">
                                                        <?php echo ucfirst($purchase['status']); ?>
                                                    </span>
                                                </div>
                                            </tr>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="8" class="empty-state">No purchases found</div></tr>
                                <?php endif; ?>
                            </tbody>
                            <tfoot>
                                <tr class="totals-row">
                                    <td colspan="6"><strong>Total Purchases</strong></td>
                                    <td colspan="2"><strong>Rs <?php echo number_format($total_purchase_amount, 2); ?></strong></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    <?php elseif($report_type == 'stock'): ?>
        <div id="report-content-stock">
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-list"></i>
                        <h4>Inventory Status</h4>
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th>Product Code</th>
                                    <th>Product Name</th>
                                    <th>Current Stock</th>
                                    <th>Minimum Stock</th>
                                    <th>Purchase Price</th>
                                    <th>Sale Price</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $stock_sql = "SELECT * FROM lube_products ORDER BY product_name";
                                $stock_result = mysqli_query($conn, $stock_sql);
                                ?>
                                <?php if(mysqli_num_rows($stock_result) > 0): ?>
                                    <?php while($prod = mysqli_fetch_assoc($stock_result)): 
                                        $stock_status = $prod['current_stock'] <= $prod['minimum_stock'] ? 'Low Stock' : 'In Stock';
                                        $status_class = $prod['current_stock'] <= $prod['minimum_stock'] ? 'status-low' : 'status-normal';
                                    ?>
                                        <tr>
                                            <td data-label="Product Code"><?php echo $prod['product_code']; ?></td>
                                            <td data-label="Product Name"><?php echo htmlspecialchars($prod['product_name']); ?></td>
                                            <td data-label="Current Stock"><?php echo number_format($prod['current_stock'], 2); ?></td>
                                            <td data-label="Minimum Stock"><?php echo number_format($prod['minimum_stock'], 2); ?></td>
                                            <td data-label="Purchase Price">Rs <?php echo number_format($prod['purchase_price'], 2); ?></td>
                                            <td data-label="Sale Price">Rs <?php echo number_format($prod['sale_price'], 2); ?></td>
                                            <td data-label="Status"><span class="stock-status <?php echo $status_class; ?>"><?php echo $stock_status; ?></span></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="7" class="empty-state">No products found</div></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <?php if(mysqli_num_rows($low_stock_result) > 0): ?>
                <div class="warning-card">
                    <i class="fas fa-exclamation-triangle"></i>
                    <div class="warning-content">
                        <strong>Low Stock Alert!</strong>
                        <p>The following products are below minimum stock level:</p>
                        <ul>
                            <?php while($low = mysqli_fetch_assoc($low_stock_result)): ?>
                                <li><?php echo htmlspecialchars($low['product_name']); ?> - Stock: <?php echo number_format($low['current_stock'], 2); ?> (Min: <?php echo number_format($low['minimum_stock'], 2); ?>)</li>
                            <?php endwhile; ?>
                        </ul>
                    </div>
                    <a href="lube_purchase.php" class="btn-reorder"><i class="fas fa-shopping-cart"></i> Reorder</a>
                </div>
            <?php endif; ?>
        </div>

    <?php elseif($report_type == 'profit'): ?>
        <div id="report-content-profit">
            <div class="profit-summary-grid">
                <div class="profit-card">
                    <div class="profit-title">Sales Revenue</div>
                    <div class="profit-amount">Rs <?php echo number_format($total_sales_amount, 2); ?></div>
                    <div class="profit-desc">Total sales value</div>
                </div>
                <div class="profit-card">
                    <div class="profit-title">COGS (Cost of Goods Sold)</div>
                    <div class="profit-amount">Rs <?php echo number_format($total_cogs, 2); ?></div>
                    <div class="profit-desc">Actual cost of sold products</div>
                </div>
                <div class="profit-card highlight">
                    <div class="profit-title">Gross Profit</div>
                    <div class="profit-amount">Rs <?php echo number_format($gross_profit, 2); ?></div>
                    <div class="profit-desc">Sales - COGS</div>
                </div>
                <div class="profit-card">
                    <div class="profit-title">Profit Margin</div>
                    <div class="profit-amount"><?php echo number_format($profit_margin, 2); ?>%</div>
                    <div class="profit-desc">Gross margin percentage</div>
                </div>
            </div>

            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-trophy"></i>
                        <h4>Top Selling Products with Profit Analysis</h4>
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Product</th>
                                    <th>Quantity Sold</th>
                                    <th>Sales Value</th>
                                    <th>COGS</th>
                                    <th>Profit</th>
                                    <th>Margin</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $rank = 1;
                                if(mysqli_num_rows($top_products_result) > 0):
                                    while($product = mysqli_fetch_assoc($top_products_result)): 
                                        $product_profit = $product['total_sales_value'] - $product['total_cogs'];
                                        $product_margin = $product['total_sales_value'] > 0 ? ($product_profit / $product['total_sales_value']) * 100 : 0;
                                ?>
                                        <tr>
                                            <td data-label="#"><?php echo $rank++; ?></div>
                                            <td data-label="Product"><?php echo htmlspecialchars($product['product_name']); ?><br><small><?php echo $product['product_code']; ?></small></div>
                                            <td data-label="Quantity Sold"><?php echo number_format($product['total_sold'], 2); ?> units</div>
                                            <td data-label="Sales Value">Rs <?php echo number_format($product['total_sales_value'], 2); ?></div>
                                            <td data-label="COGS">Rs <?php echo number_format($product['total_cogs'], 2); ?></div>
                                            <td data-label="Profit" class="profit-text">Rs <?php echo number_format($product_profit, 2); ?></div>
                                            <td data-label="Margin"><?php echo number_format($product_margin, 2); ?>%</div>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="7" class="empty-state">No sales data found</div></tr>
                                <?php endif; ?>
                            </tbody>
                            <tfoot>
                                <tr class="totals-row">
                                    <td colspan="3"><strong>Total</strong></td>
                                    <td><strong>Rs <?php echo number_format($total_sales_amount, 2); ?></strong></td>
                                    <td><strong>Rs <?php echo number_format($total_cogs, 2); ?></strong></td>
                                    <td><strong>Rs <?php echo number_format($gross_profit, 2); ?></strong></td>
                                    <td><strong><?php echo number_format($profit_margin, 2); ?>%</strong></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<style>
/* Lube Reports Styles - Page Specific Only */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

body {
    background: #f5f7fb;
    overflow-x: hidden;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.filter-header,
.header-info h4,
.modern-table th {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

/* Main Content */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    background: #f5f7fb;
}

.lube-reports-container {
    max-width: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 16px;
    padding: 16px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    margin: 0 0 3px 0;
    font-size: 22px;
}

.page-header p {
    margin: 0;
    font-size: 12px;
    opacity: 0.9;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 6px 14px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 600;
}

/* Report Tabs */
.report-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 20px;
    background: #fff;
    padding: 8px 16px;
    border-radius: 50px;
    width: 100%;
}

.tab-btn {
    padding: 8px 20px;
    border-radius: 40px;
    font-weight: 600;
    font-size: 13px;
    text-decoration: none;
    background: #f0f0f0;
    color: #555;
    transition: all 0.3s;
}

.tab-btn i {
    margin-right: 6px;
    font-size: 12px;
}

.tab-btn.active {
    background: #A04657;
    color: #fff;
}

.tab-btn:hover {
    background: #A04657;
    color: #fff;
    text-decoration: none;
}

/* Filter Card */
.filter-card {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 20px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    width: 100%;
}

.filter-header {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    padding: 10px 20px;
    color: #fff;
    font-weight: 600;
    font-size: 14px;
}

.filter-body {
    padding: 16px;
}

.filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-end;
}

.filter-group {
    flex: 1;
    min-width: 150px;
}

.filter-group label {
    display: block;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    color: #666;
    margin-bottom: 4px;
}

.form-control-modern {
    width: 100%;
    padding: 8px 12px;
    border: 2px solid #e8e8e8;
    border-radius: 10px;
    font-size: 13px;
    transition: all 0.3s;
    background: #fafafa;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    background: #fff;
}

.filter-actions {
    display: flex;
    gap: 8px;
}

.btn-search, .btn-print, .btn-pdf {
    padding: 8px 18px;
    border-radius: 10px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    transition: all 0.3s;
}

.btn-search {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    color: #fff;
}

.btn-search:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(160,70,87,0.3);
}

.btn-print {
    background: #6c5ce7;
    color: #fff;
}

.btn-print:hover {
    background: #5a4bd1;
    transform: translateY(-2px);
}

.btn-pdf {
    background: #dc3545;
    color: #fff;
}

.btn-pdf:hover {
    background: #c82333;
    transform: translateY(-2px);
}

/* Summary Cards */
.summary-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 20px;
    width: 100%;
}

.summary-card {
    background: #fff;
    border-radius: 16px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 14px;
    border: 1px solid #f0f0f0;
    transition: all 0.3s;
}

.summary-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 18px rgba(160,70,87,0.1);
}

.summary-icon {
    width: 48px;
    height: 48px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.sales-icon { background: rgba(160,70,87,0.1); }
.sales-icon i { color: #A04657; font-size: 24px; }
.purchase-icon { background: rgba(220,53,69,0.1); }
.purchase-icon i { color: #dc3545; font-size: 24px; }
.profit-icon { background: rgba(40,167,69,0.1); }
.profit-icon i { color: #28a745; font-size: 24px; }
.margin-icon { background: rgba(23,162,184,0.1); }
.margin-icon i { color: #17a2b8; font-size: 24px; }

.summary-content h4 {
    margin: 0;
    font-size: 20px;
    font-weight: 800;
}

.summary-content p {
    margin: 3px 0 0;
    font-size: 11px;
    color: #666;
}

.summary-content small {
    font-size: 10px;
    color: #999;
    display: block;
    margin-top: 2px;
}

.profit-text {
    color: #28a745;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    margin-bottom: 20px;
    width: 100%;
}

.table-card-header {
    padding: 12px 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.header-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-info i {
    font-size: 18px;
    color: #A04657;
}

.header-info h4 {
    margin: 0;
    font-size: 15px;
}

.table-responsive {
    overflow-x: auto;
    width: 100%;
}

/* Modern Table */
.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 800px;
}

.modern-table th {
    padding: 10px 12px;
    background: #f8f9fc;
    font-weight: 700;
    color: #445566;
    font-size: 11px;
    border-bottom: 2px solid #e8e8e8;
    text-align: left;
}

.modern-table td {
    padding: 10px 12px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 12px;
    font-weight: 600;
    vertical-align: middle;
}

.modern-table tr:hover td {
    background: #fefaf8;
}

.totals-row td {
    font-weight: 800;
    background: #e9ecef;
    border-top: 2px solid #ddd;
}

/* Purchase Table Specific */
.purchase-table td {
    vertical-align: top;
}

/* Status Badges */
.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
}

.status-completed {
    background: #e8f5e9;
    color: #2e7d32;
}

.status-pending {
    background: #fff3e0;
    color: #ff9800;
}

/* Profit Summary Grid */
.profit-summary-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    margin-bottom: 20px;
    width: 100%;
}

.profit-card {
    background: #fff;
    border-radius: 16px;
    padding: 18px;
    text-align: center;
    border: 1px solid #f0f0f0;
}

.profit-card.highlight {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    color: #fff;
}

.profit-title {
    font-size: 12px;
    text-transform: uppercase;
    font-weight: 600;
    opacity: 0.7;
}

.profit-amount {
    font-size: 28px;
    font-weight: 800;
    margin: 8px 0;
}

.highlight .profit-amount {
    color: #fff;
}

.profit-desc {
    font-size: 10px;
    opacity: 0.7;
}

/* Warning Card */
.warning-card {
    background: #fff3e0;
    border-radius: 14px;
    padding: 14px 18px;
    display: flex;
    align-items: center;
    gap: 12px;
    border-left: 4px solid #ff9800;
    margin-top: 0;
    width: 100%;
}

.warning-card i {
    font-size: 24px;
    color: #ff9800;
}

.warning-content {
    flex: 1;
}

.warning-card ul {
    margin: 6px 0 0 18px;
    font-size: 11px;
    font-weight: 600;
}

.btn-reorder {
    padding: 6px 16px;
    background: #ff9800;
    color: #fff;
    border-radius: 30px;
    text-decoration: none;
    font-weight: 600;
    font-size: 11px;
    transition: all 0.3s;
}

.btn-reorder:hover {
    background: #e65100;
    text-decoration: none;
    color: #fff;
}

.stock-status {
    display: inline-block;
    padding: 3px 10px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 700;
}

.status-normal {
    background: #e8f5e9;
    color: #2e7d32;
}

.status-low {
    background: #ffebee;
    color: #c62828;
}

.empty-state {
    text-align: center;
    padding: 40px !important;
    color: #999;
}

/* Responsive */
@media (max-width: 1200px) {
    .summary-cards {
        grid-template-columns: repeat(2, 1fr);
    }
    .profit-summary-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 992px) {
    .main-content {
        margin-left: 0;
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 10px 12px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 10px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .report-tabs {
        border-radius: 20px;
        justify-content: center;
        padding: 8px 12px;
    }
    .tab-btn {
        padding: 6px 14px;
        font-size: 11px;
    }
    .filter-row {
        flex-direction: column;
        gap: 10px;
    }
    .filter-group {
        width: 100%;
    }
    .filter-actions {
        flex-direction: row;
        width: 100%;
    }
    .btn-search, .btn-print, .btn-pdf {
        flex: 1;
        justify-content: center;
    }
    .summary-cards {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .profit-summary-grid {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .table-card-header {
        flex-direction: column;
        align-items: stretch;
    }
    .modern-table th {
        display: none;
    }
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
        font-weight: 600;
    }
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 12px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        font-size: 10px;
        color: #A04657;
    }
    .modern-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #e8e8e8;
        border-radius: 12px;
        overflow: hidden;
    }
    .summary-card {
        padding: 12px;
    }
    .summary-icon {
        width: 42px;
        height: 42px;
    }
    .summary-icon i {
        font-size: 20px;
    }
    .summary-content h4 {
        font-size: 18px;
    }
    .profit-card {
        padding: 14px;
    }
    .profit-amount {
        font-size: 24px;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
</style>

<!-- PDF Generation Libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

<script>
const pdfFromDate = '<?php echo date('d-m-Y', strtotime($from_date)); ?>';
const pdfToDate = '<?php echo date('d-m-Y', strtotime($to_date)); ?>';
const reportType = '<?php echo $report_type; ?>';
const reportTitles = {
    sales: 'Sales Report',
    purchase: 'Purchase Report',
    stock: 'Stock Report',
    profit: 'Profit Report'
};
const reportTitle = reportTitles[reportType] || 'Report';

async function downloadPDF() {
    let contentId = 'report-content-' + reportType;
    const element = document.getElementById(contentId);
    if (!element) {
        alert('No report content to download for this tab.');
        return;
    }

    const pdfBtn = document.querySelector('.btn-pdf');
    const originalHTML = pdfBtn.innerHTML;
    pdfBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
    pdfBtn.disabled = true;

    try {
        const canvas = await html2canvas(element, {
            scale: 2,
            useCORS: true,
            logging: false,
            allowTaint: true,
            backgroundColor: '#ffffff'
        });

        const imgData = canvas.toDataURL('image/png');
        const imgWidth = 210;
        const pageHeight = 297;
        const pageWidth = imgWidth - 20;
        const imgHeight = (canvas.height * pageWidth) / canvas.width;
        
        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF('p', 'mm', 'a4');

        function addHeader() {
            pdf.setFont('helvetica', 'bold');
            pdf.setFontSize(18);
            pdf.setTextColor(160, 70, 87);
            pdf.text('ALFATEH PETROLEUM SERVICE', 105, 20, { align: 'center' });
            
            pdf.setFontSize(11);
            pdf.setTextColor(100, 100, 100);
            pdf.text('Complete Fuel Station Management Solution', 105, 27, { align: 'center' });
            
            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text('Shaikh bhirkyo road Tando Muhammad khan', 105, 34, { align: 'center' });
            
            pdf.setDrawColor(160, 70, 87);
            pdf.setLineWidth(0.5);
            pdf.line(15, 40, 195, 40);
            
            pdf.setFontSize(16);
            pdf.setTextColor(0, 0, 0);
            pdf.text(reportTitle, 105, 48, { align: 'center' });
            
            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text(`Period: ${pdfFromDate} To ${pdfToDate}`, 105, 55, { align: 'center' });
            
            pdf.line(15, 59, 195, 59);
        }
        addHeader();

        const topMargin = 65;
        const bottomMargin = 10;
        const availableHeightPage1 = pageHeight - topMargin - bottomMargin;
        
        if (imgHeight <= availableHeightPage1) {
            pdf.addImage(imgData, 'PNG', 10, topMargin, pageWidth, imgHeight);
        } else {
            let remainingHeight = imgHeight;
            let sourceY = 0;
            let pageNum = 1;
            const canvasHeight = canvas.height;

            while (remainingHeight > 0) {
                const available = (pageNum === 1) ? availableHeightPage1 : (pageHeight - topMargin - bottomMargin);
                let sliceHeight = Math.min(remainingHeight, available);

                const sourceHeightPx = (sliceHeight / imgHeight) * canvasHeight;

                pdf.addImage(
                    imgData, 'PNG',
                    10, topMargin,
                    pageWidth, sliceHeight,
                    undefined, 'FAST',
                    0,
                    0, sourceY,
                    canvas.width, sourceHeightPx
                );

                remainingHeight -= sliceHeight;
                sourceY += sourceHeightPx;

                if (remainingHeight > 0) {
                    pdf.addPage();
                    pageNum++;
                    pdf.setFontSize(8);
                    pdf.setTextColor(150);
                    pdf.text('Continued...', 105, 10, { align: 'center' });
                }
            }
        }

        const fileName = `Lube_${reportTitle.replace(/\s+/g, '_')}_${pdfFromDate}_to_${pdfToDate}.pdf`;
        pdf.save(fileName);

    } catch (error) {
        console.error('Error generating PDF:', error);
        alert('An error occurred while generating the PDF. Please try again.');
    } finally {
        pdfBtn.innerHTML = originalHTML;
        pdfBtn.disabled = false;
    }
}
</script>

<?php include('../includes/ft.php'); ?>