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

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

$tank_id = isset($_GET['tank_id']) ? (int)$_GET['tank_id'] : 0;
$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');
$tank_details = null;

// Get all tanks for dropdown
$all_tanks_sql = "SELECT t.*, f.name as fuel_name, f.sale_price, f.purchase_price 
                  FROM tanks t 
                  LEFT JOIN fuel_types f ON t.fuel_type_id = f.id 
                  ORDER BY t.id DESC";
$all_tanks_result = mysqli_query($conn, $all_tanks_sql);

if($tank_id > 0) {
    // Get tank details with fuel info
    $tank_sql = "SELECT t.*, f.name as fuel_name, f.sale_price, f.purchase_price 
                 FROM tanks t 
                 LEFT JOIN fuel_types f ON t.fuel_type_id = f.id 
                 WHERE t.id = '$tank_id'";
    $tank_result = mysqli_query($conn, $tank_sql);
    $tank_details = mysqli_fetch_assoc($tank_result);
    
    if($tank_details) {
        // Calculate Opening Stock
        $opening_stock = $tank_details['current_stock'];
        
        // Calculate Purchases for this tank and date range
        $purchase_sql = "SELECT SUM(quantity) as total_purchase, SUM(total_amount) as total_purchase_amount 
                         FROM purchases 
                         WHERE tank_id = '$tank_id' 
                         AND date_time BETWEEN '$from_date 00:00:00' AND '$to_date 23:59:59'";
        $purchase_result = mysqli_query($conn, $purchase_sql);
        $purchase_data = mysqli_fetch_assoc($purchase_result);
        $total_purchase = $purchase_data['total_purchase'] ? $purchase_data['total_purchase'] : 0;
        $total_purchase_amount = $purchase_data['total_purchase_amount'] ? $purchase_data['total_purchase_amount'] : 0;
        
        // Calculate Sales for this tank (from nozzle_readings via nozzles)
        $sales_sql = "SELECT SUM(nr.sale_liters) as total_sale 
                      FROM nozzle_readings nr
                      INNER JOIN nozzles n ON nr.nozzle_id = n.id
                      WHERE n.tank_id = '$tank_id'
                      AND nr.date_time BETWEEN '$from_date 00:00:00' AND '$to_date 23:59:59'";
        $sales_result = mysqli_query($conn, $sales_sql);
        $sales_data = mysqli_fetch_assoc($sales_result);
        $total_sale = $sales_data['total_sale'] ? $sales_data['total_sale'] : 0;
        
        // Calculate total sale amount
        $sale_price = $tank_details['sale_price'] ? $tank_details['sale_price'] : 100;
        $total_sale_amount = $total_sale * $sale_price;
        
        // Get latest dip reading
        $dip_sql = "SELECT dip_value, date_time FROM tank_dips WHERE tank_id = '$tank_id' ORDER BY id DESC LIMIT 1";
        $dip_result = mysqli_query($conn, $dip_sql);
        $dip_data = mysqli_fetch_assoc($dip_result);
        $latest_dip = $dip_data ? $dip_data['dip_value'] : null;
        $dip_date = $dip_data ? $dip_data['date_time'] : null;
        
        // Calculate Expected Closing Stock
        $expected_closing = $opening_stock + $total_purchase - $total_sale;
        
        // Calculate Loss/Gain
        $loss_gain = null;
        if($latest_dip !== null) {
            $loss_gain = $latest_dip - $expected_closing;
        }
        
        // Use dip reading as closing if available, otherwise expected
        $closing_stock = ($latest_dip !== null) ? $latest_dip : $expected_closing;
        
        // Calculate purchase rate (average)
        $avg_purchase_rate = $total_purchase > 0 ? $total_purchase_amount / $total_purchase : 0;
        
        // Calculate profit/loss for sales
        $profit_per_liter = $sale_price - $avg_purchase_rate;
        $total_profit = $total_sale * $profit_per_liter;
        
        // Get all purchases for this tank in date range
        $purchases_details_sql = "SELECT p.*, f.name as fuel_name 
                                  FROM purchases p
                                  LEFT JOIN fuel_types f ON p.fuel_type_id = f.id
                                  WHERE p.tank_id = '$tank_id'
                                  AND p.date_time BETWEEN '$from_date 00:00:00' AND '$to_date 23:59:59'
                                  ORDER BY p.id DESC";
        $purchases_details_result = mysqli_query($conn, $purchases_details_sql);
        
        // Get all sales transactions for this tank in date range
        $sales_details_sql = "SELECT nr.*, n.nozzle_name, s.shift_name
                              FROM nozzle_readings nr
                              INNER JOIN nozzles n ON nr.nozzle_id = n.id
                              LEFT JOIN shift_entries s ON nr.shift_id = s.id
                              WHERE n.tank_id = '$tank_id'
                              AND nr.date_time BETWEEN '$from_date 00:00:00' AND '$to_date 23:59:59'
                              ORDER BY nr.id DESC";
        $sales_details_result = mysqli_query($conn, $sales_details_sql);
        
        // Get dip readings history
        $dip_history_sql = "SELECT * FROM tank_dips WHERE tank_id = '$tank_id' ORDER BY id DESC LIMIT 10";
        $dip_history_result = mysqli_query($conn, $dip_history_sql);
    }
}
?>

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

<div class="tank-closing-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-chart-line"></i> Tank Closing Report</h2>
            <p>Complete stock movement analysis with loss/gain calculation</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-calendar"></i>
                <span><?php echo date('d-m-Y H:i'); ?></span>
            </div>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="filter-card">
        <div class="filter-header">
            <i class="fas fa-filter"></i>
            <h4>Filter Report</h4>
        </div>
        <div class="filter-body">
            <form method="GET" action="" class="filter-form">
                <div class="form-row">
                    <div class="form-group">
                        <label><i class="fas fa-tachometer-alt"></i> Select Tank</label>
                        <select name="tank_id" class="form-control-modern" onchange="this.form.submit()">
                            <option value="">-- Select Tank --</option>
                            <?php 
                            mysqli_data_seek($all_tanks_result, 0);
                            while($tank = mysqli_fetch_assoc($all_tanks_result)): 
                                $selected = ($tank_id == $tank['id']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $tank['id']; ?>" <?php echo $selected; ?>>
                                    <?php echo htmlspecialchars($tank['tank_name']); ?> (<?php echo htmlspecialchars($tank['fuel_name']); ?>) - Stock: <?php echo number_format($tank['current_stock'], 2); ?>L
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="form-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="form-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="form-group">
                        <label>&nbsp;</label>
                        <button type="submit" class="btn-filter">
                            <i class="fas fa-search"></i> Generate Report
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <?php if($tank_id > 0 && $tank_details): ?>
        <!-- Report Content Wrapper (for PDF capture) -->
        <div id="report-content">
            <!-- Tank Info Card -->
            <div class="tank-info-card">
                <div class="tank-icon">
                    <i class="fas fa-tachometer-alt"></i>
                </div>
                <div class="tank-details">
                    <h3><?php echo htmlspecialchars($tank_details['tank_name']); ?></h3>
                    <div class="info-grid">
                        <div class="info-item">
                            <span><i class="fas fa-oil-can"></i> Fuel Type:</span>
                            <strong><?php echo htmlspecialchars($tank_details['fuel_name']); ?></strong>
                        </div>
                        <div class="info-item">
                            <span><i class="fas fa-tag"></i> Sale Price:</span>
                            <strong>Rs <?php echo number_format($tank_details['sale_price'], 2); ?>/L</strong>
                        </div>
                        <div class="info-item">
                            <span><i class="fas fa-shopping-cart"></i> Purchase Price:</span>
                            <strong>Rs <?php echo number_format($tank_details['purchase_price'], 2); ?>/L</strong>
                        </div>
                        <div class="info-item">
                            <span><i class="fas fa-ruler"></i> Capacity:</span>
                            <strong><?php echo number_format($tank_details['capacity'], 2); ?> Liters</strong>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Summary Cards -->
            <div class="summary-row">
                <div class="summary-card opening">
                    <div class="summary-icon"><i class="fas fa-play-circle"></i></div>
                    <div class="summary-content">
                        <p>Opening Stock</p>
                        <h4><?php echo number_format($opening_stock, 2); ?> L</h4>
                        <small>As on <?php echo date('d-m-Y', strtotime($from_date)); ?></small>
                    </div>
                </div>
                <div class="summary-card purchase">
                    <div class="summary-icon"><i class="fas fa-shopping-cart"></i></div>
                    <div class="summary-content">
                        <p>Total Purchases</p>
                        <h4><?php echo number_format($total_purchase, 2); ?> L</h4>
                        <small>Rs <?php echo number_format($total_purchase_amount, 2); ?></small>
                    </div>
                </div>
                <div class="summary-card sale">
                    <div class="summary-icon"><i class="fas fa-gas-pump"></i></div>
                    <div class="summary-content">
                        <p>Total Sales</p>
                        <h4><?php echo number_format($total_sale, 2); ?> L</h4>
                        <small>Rs <?php echo number_format($total_sale_amount, 2); ?></small>
                    </div>
                </div>
                <div class="summary-card closing">
                    <div class="summary-icon"><i class="fas fa-stop-circle"></i></div>
                    <div class="summary-content">
                        <p>Closing Stock</p>
                        <h4><?php echo number_format($closing_stock, 2); ?> L</h4>
                        <small><?php echo $latest_dip ? 'As per Dip Reading' : 'Calculated'; ?></small>
                    </div>
                </div>
            </div>

            <!-- Loss/Gain Card -->
            <div class="loss-gain-card <?php echo ($loss_gain !== null) ? (($loss_gain > 0) ? 'gain' : (($loss_gain < 0) ? 'loss' : 'neutral')) : 'neutral'; ?>">
                <div class="loss-gain-icon">
                    <i class="fas <?php echo ($loss_gain > 0) ? 'fa-arrow-up' : (($loss_gain < 0) ? 'fa-arrow-down' : 'fa-minus'); ?>"></i>
                </div>
                <div class="loss-gain-content">
                    <h4>Stock <?php echo ($loss_gain > 0) ? 'Gain' : (($loss_gain < 0) ? 'Loss' : 'Match'); ?></h4>
                    <h2><?php echo ($loss_gain !== null) ? number_format(abs($loss_gain), 2) . ' Liters' : 'No Dip Reading'; ?></h2>
                    <p><?php echo ($loss_gain !== null) ? (($loss_gain > 0) ? 'Physical stock is higher than calculated' : (($loss_gain < 0) ? 'Physical stock is lower than calculated' : 'Physical stock matches calculated stock')) : 'Please record a dip reading to calculate loss/gain'; ?></p>
                </div>
            </div>

            <!-- Stock Flow Formula -->
            <div class="formula-card">
                <div class="formula-header">
                    <i class="fas fa-calculator"></i>
                    <span>Stock Calculation Formula</span>
                </div>
                <div class="formula-body">
                    <code>Closing Stock = Opening Stock + Purchases - Sales ± Loss/Gain</code>
                    <div class="formula-example">
                        <?php echo number_format($closing_stock, 2); ?> = <?php echo number_format($opening_stock, 2); ?> + <?php echo number_format($total_purchase, 2); ?> - <?php echo number_format($total_sale, 2); ?> 
                        <?php echo ($loss_gain !== null) ? (($loss_gain >= 0) ? '+ ' . number_format(abs($loss_gain), 2) : '- ' . number_format(abs($loss_gain), 2)) : ''; ?>
                    </div>
                </div>
            </div>

            <!-- Stock Movement Table -->
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-exchange-alt"></i>
                        <h4>Stock Movement Summary</h4>
                    </div>
                    <div class="table-stats">
                        <span>Period: <?php echo date('d-m-Y', strtotime($from_date)); ?> to <?php echo date('d-m-Y', strtotime($to_date)); ?></span>
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="stock-table">
                            <thead>
                                <tr>
                                    <th>Particulars</th>
                                    <th>In (Liters)</th>
                                    <th>Out (Liters)</th>
                                    <th>Balance (Liters)</th>
                                    <th>Amount (Rs)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><strong>Opening Stock</strong></td>
                                    <td><?php echo number_format($opening_stock, 2); ?> L</div>
                                    <td>-</div>
                                    <td><?php echo number_format($opening_stock, 2); ?> L</div>
                                    <td>Rs <?php echo number_format($opening_stock * $tank_details['purchase_price'], 2); ?></div>
                                </tr>
                                <tr>
                                    <td><strong>+ Purchases</strong></div>
                                    <td><?php echo number_format($total_purchase, 2); ?> L</div>
                                    <td>-</div>
                                    <td><?php echo number_format($opening_stock + $total_purchase, 2); ?> L</div>
                                    <td>Rs <?php echo number_format($total_purchase_amount, 2); ?></div>
                                </tr>
                                <tr>
                                    <td><strong>- Sales</strong></div>
                                    <td>-</div>
                                    <td><?php echo number_format($total_sale, 2); ?> L</div>
                                    <td><?php echo number_format($opening_stock + $total_purchase - $total_sale, 2); ?> L</div>
                                    <td>Rs <?php echo number_format($total_sale_amount, 2); ?></div>
                                </tr>
                                <?php if($loss_gain !== null && $loss_gain != 0): ?>
                                <tr class="<?php echo $loss_gain > 0 ? 'gain-row' : 'loss-row'; ?>">
                                    <td><strong><?php echo $loss_gain > 0 ? '+ Loss/Gain (Gain)' : '- Loss/Gain (Loss)'; ?></strong></div>
                                    <td><?php echo $loss_gain > 0 ? number_format($loss_gain, 2) . ' L' : '-'; ?></div>
                                    <td><?php echo $loss_gain < 0 ? number_format(abs($loss_gain), 2) . ' L' : '-'; ?></div>
                                    <td><?php echo number_format($closing_stock, 2); ?> L</div>
                                    <td>-</div>
                                </tr>
                                <?php endif; ?>
                                <tr class="total-row">
                                    <td><strong>CLOSING STOCK</strong></div>
                                    <td><strong><?php echo number_format($closing_stock, 2); ?> L</strong></div>
                                    <td>-</div>
                                    <td><strong><?php echo number_format($closing_stock, 2); ?> L</strong></div>
                                    <td><strong>Rs <?php echo number_format($closing_stock * $tank_details['purchase_price'], 2); ?></strong></div>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Purchases Details Table -->
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-shopping-cart"></i>
                        <h4>Purchase Details</h4>
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="details-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Date & Time</th>
                                    <th>DO Number</th>
                                    <th>Quantity (L)</th>
                                    <th>Rate (Rs/L)</th>
                                    <th>Total Amount (Rs)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $purchase_count = 0;
                                if(mysqli_num_rows($purchases_details_result) > 0):
                                    while($purchase = mysqli_fetch_assoc($purchases_details_result)):
                                        $purchase_count++;
                                ?>
                                    <tr>
                                        <td><?php echo $purchase_count; ?></td>
                                        <td><?php echo date('d-m-Y h:i A', strtotime($purchase['date_time'])); ?></td>
                                        <td><?php echo htmlspecialchars($purchase['do_number']); ?></td>
                                        <td><?php echo number_format($purchase['quantity'], 2); ?> L</div>
                                        <td>Rs <?php echo number_format($purchase['rate'], 2); ?>/L</div>
                                        <td>Rs <?php echo number_format($purchase['total_amount'], 2); ?></div>
                                    </tr>
                                <?php 
                                    endwhile;
                                else:
                                ?>
                                    <tr>
                                        <td colspan="6" class="empty-state">No purchase records found for this period</div>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                            <?php if($purchase_count > 0): ?>
                            <tfoot>
                                <tr class="footer-row">
                                    <td colspan="3"><strong>Total</strong></div>
                                    <td><strong><?php echo number_format($total_purchase, 2); ?> L</strong></div>
                                    <td>-</div>
                                    <td><strong>Rs <?php echo number_format($total_purchase_amount, 2); ?></strong></div>
                                </tr>
                            </tfoot>
                            <?php endif; ?>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Sales Details Table -->
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-gas-pump"></i>
                        <h4>Sales Details</h4>
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="details-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Date & Time</th>
                                    <th>Nozzle</th>
                                    <th>Shift</th>
                                    <th>Opening (L)</th>
                                    <th>Closing (L)</th>
                                    <th>Sale (L)</th>
                                    <th>Amount (Rs)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $sale_count = 0;
                                if(mysqli_num_rows($sales_details_result) > 0):
                                    while($sale = mysqli_fetch_assoc($sales_details_result)):
                                        $sale_count++;
                                        $sale_amount = $sale['sale_liters'] * $tank_details['sale_price'];
                                ?>
                                    <tr>
                                        <td><?php echo $sale_count; ?></td>
                                        <td><?php echo date('d-m-Y h:i A', strtotime($sale['date_time'])); ?></td>
                                        <td><?php echo htmlspecialchars($sale['nozzle_name']); ?></div>
                                        <td><?php echo htmlspecialchars($sale['shift_name']); ?></div>
                                        <td><?php echo number_format($sale['opening_reading'], 2); ?></div>
                                        <td><?php echo number_format($sale['closing_reading'], 2); ?></div>
                                        <td><strong><?php echo number_format($sale['sale_liters'], 2); ?> L</strong></div>
                                        <td>Rs <?php echo number_format($sale_amount, 2); ?></div>
                                    </tr>
                                <?php 
                                    endwhile;
                                else:
                                ?>
                                    <tr>
                                        <td colspan="8" class="empty-state">No sales records found for this period</div>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                            <?php if($sale_count > 0): ?>
                            <tfoot>
                                <tr class="footer-row">
                                    <td colspan="6"><strong>Total</strong></div>
                                    <td><strong><?php echo number_format($total_sale, 2); ?> L</strong></div>
                                    <td><strong>Rs <?php echo number_format($total_sale_amount, 2); ?></strong></div>
                                </tr>
                            </tfoot>
                            <?php endif; ?>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Dip Reading History -->
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-tape"></i>
                        <h4>Dip Reading History</h4>
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="details-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Date & Time</th>
                                    <th>Dip Value (Liters)</th>
                                    <th>Notes</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $dip_count = 0;
                                if(mysqli_num_rows($dip_history_result) > 0):
                                    while($dip = mysqli_fetch_assoc($dip_history_result)):
                                        $dip_count++;
                                ?>
                                    <tr>
                                        <td><?php echo $dip_count; ?></td>
                                        <td><?php echo date('d-m-Y h:i A', strtotime($dip['date_time'])); ?></td>
                                        <td><strong><?php echo number_format($dip['dip_value'], 2); ?> L</strong></td>
                                        <td>Dip Reading</div>
                                    </tr>
                                <?php 
                                    endwhile;
                                else:
                                ?>
                                    <tr>
                                        <td colspan="4" class="empty-state">No dip readings recorded</div>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div><!-- #report-content ends -->

        <!-- Action Buttons -->
        <div class="action-buttons-container">
            <button class="btn-print" onclick="window.print()">
                <i class="fas fa-print"></i> Print Report
            </button>
            <button class="btn-pdf" onclick="downloadPDF()">
                <i class="fas fa-file-pdf"></i> Download PDF
            </button>
            <a href="tanks.php" class="btn-back">
                <i class="fas fa-arrow-left"></i> Back to Tanks
            </a>
        </div>

    <?php elseif($tank_id > 0): ?>
        <div class="error-card">
            <i class="fas fa-exclamation-triangle"></i>
            <h4>Tank Not Found</h4>
            <p>The selected tank does not exist. Please select a valid tank.</p>
            <a href="tanks.php" class="btn-primary">Go to Tanks</a>
        </div>
    <?php else: ?>
        <div class="welcome-card">
            <i class="fas fa-tachometer-alt"></i>
            <h4>Select a Tank</h4>
            <p>Please select a tank from the dropdown above to view its closing report.</p>
        </div>
    <?php endif; ?>
</div>

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

* {
    font-family: 'Inter', sans-serif;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.filter-header h4,
.tank-info-card h3,
.summary-card h4,
.loss-gain-card h4 {
    font-family: 'Inter', sans-serif;
    font-weight: 600;
}

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

.tank-closing-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: 18px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    margin: 0 0 4px 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 16px;
    border-radius: 40px;
    font-weight: 500;
    font-size: 12px;
}

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

.filter-header {
    background: #f8f9fc;
    padding: 12px 20px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    align-items: center;
    gap: 8px;
}

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

.filter-header h4 {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
}

.filter-body {
    padding: 16px 20px;
}

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

.form-row {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    width: 100%;
}

.form-group {
    flex: 1;
    min-width: 160px;
}

.form-group label {
    display: block;
    margin-bottom: 6px;
    font-weight: 600;
    font-size: 12px;
    color: #555;
}

.form-group label i {
    color: #A04657;
    margin-right: 5px;
}

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

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

.btn-filter {
    background: #A04657;
    color: #fff;
    border: none;
    padding: 8px 20px;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 13px;
}

.btn-filter:hover {
    background: #6b2a36;
    transform: translateY(-2px);
}

/* Tank Info Card */
.tank-info-card {
    background: #fff;
    border-radius: 16px;
    padding: 18px 24px;
    margin-bottom: 20px;
    display: flex;
    gap: 20px;
    align-items: center;
    border: 1px solid #e8e8e8;
    width: 100%;
}

.tank-icon i {
    font-size: 52px;
    color: #A04657;
}

.tank-details h3 {
    margin: 0 0 8px 0;
    font-size: 20px;
}

.info-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.info-item {
    display: flex;
    gap: 6px;
    font-size: 13px;
}

.info-item span {
    color: #666;
}

.info-item strong {
    color: #333;
}

/* Summary Row */
.summary-row {
    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 #e8e8e8;
    transition: all 0.3s;
}

.summary-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 16px rgba(0,0,0,0.06);
}

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

.summary-card.opening .summary-icon {
    background: rgba(108, 92, 231, 0.1);
    color: #6c5ce7;
}

.summary-card.purchase .summary-icon {
    background: rgba(40, 167, 69, 0.1);
    color: #28a745;
}

.summary-card.sale .summary-icon {
    background: rgba(220, 53, 69, 0.1);
    color: #dc3545;
}

.summary-card.closing .summary-icon {
    background: rgba(160, 70, 87, 0.1);
    color: #A04657;
}

.summary-icon i {
    font-size: 24px;
}

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

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

.summary-content small {
    font-size: 10px;
    color: #999;
}

/* Loss/Gain Card */
.loss-gain-card {
    background: #fff;
    border-radius: 16px;
    padding: 18px 24px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 20px;
    border: 1px solid #e8e8e8;
    width: 100%;
}

.loss-gain-card.gain {
    border-left: 5px solid #28a745;
    background: linear-gradient(135deg, #fff 0%, #e8f5e9 100%);
}

.loss-gain-card.loss {
    border-left: 5px solid #dc3545;
    background: linear-gradient(135deg, #fff 0%, #ffebee 100%);
}

.loss-gain-card.neutral {
    border-left: 5px solid #6c757d;
}

.loss-gain-icon i {
    font-size: 40px;
}

.loss-gain-card.gain .loss-gain-icon i {
    color: #28a745;
}

.loss-gain-card.loss .loss-gain-icon i {
    color: #dc3545;
}

.loss-gain-card.neutral .loss-gain-icon i {
    color: #6c757d;
}

.loss-gain-content h4 {
    margin: 0 0 4px 0;
    font-size: 14px;
}

.loss-gain-content h2 {
    margin: 0;
    font-size: 24px;
    font-weight: 800;
}

.loss-gain-card.gain .loss-gain-content h2 {
    color: #28a745;
}

.loss-gain-card.loss .loss-gain-content h2 {
    color: #dc3545;
}

.loss-gain-content p {
    margin: 4px 0 0;
    font-size: 11px;
    color: #666;
}

/* Formula Card */
.formula-card {
    background: #f8f9fc;
    border-radius: 14px;
    padding: 12px 18px;
    margin-bottom: 20px;
    border: 1px solid #e8e8e8;
    width: 100%;
}

.formula-header {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 8px;
}

.formula-header i {
    color: #A04657;
    font-size: 16px;
}

.formula-header span {
    font-weight: 600;
    font-size: 12px;
    color: #555;
}

.formula-body code {
    font-family: monospace;
    background: #fff;
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 12px;
    display: inline-block;
    margin-bottom: 6px;
}

.formula-example {
    font-size: 11px;
    color: #666;
    margin-top: 6px;
}

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

.table-card-header {
    padding: 12px 20px;
    border-bottom: 1px solid #e8e8e8;
    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;
    font-weight: 600;
}

.table-stats {
    font-size: 11px;
    color: #666;
    background: #f0f0f0;
    padding: 4px 10px;
    border-radius: 20px;
}

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

/* Stock Table */
.stock-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
}

.stock-table th, .stock-table td {
    padding: 10px 16px;
    text-align: left;
    border-bottom: 1px solid #f0f0f0;
}

.stock-table th {
    background: #fafbfc;
    font-weight: 600;
    color: #555;
    font-size: 12px;
}

.stock-table td {
    font-size: 12px;
}

.total-row {
    background: #f8f9fc;
    font-weight: 600;
    border-top: 2px solid #e8e8e8;
}

.gain-row {
    background: #e8f5e9;
    color: #28a745;
}

.loss-row {
    background: #ffebee;
    color: #dc3545;
}

/* Details Table */
.details-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
}

.details-table th, .details-table td {
    padding: 10px 16px;
    text-align: left;
    border-bottom: 1px solid #f0f0f0;
}

.details-table th {
    background: #fafbfc;
    font-weight: 600;
    color: #555;
    font-size: 11px;
}

.details-table td {
    font-size: 12px;
}

.footer-row {
    background: #f8f9fc;
    font-weight: 600;
    border-top: 2px solid #e8e8e8;
}

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

.empty-state i {
    font-size: 48px;
    color: #A04657;
    opacity: 0.4;
    margin-bottom: 12px;
}

.empty-state p {
    font-size: 13px;
}

/* Action Buttons */
.action-buttons-container {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    margin-top: 20px;
    margin-bottom: 0;
    flex-wrap: wrap;
}

.btn-print, .btn-back, .btn-primary, .btn-pdf {
    padding: 8px 22px;
    border-radius: 40px;
    font-weight: 600;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s;
    border: none;
    cursor: pointer;
    font-size: 12px;
}

.btn-print {
    background: #28a745;
    color: white;
}

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

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

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

.btn-back {
    background: #6c757d;
    color: white;
}

.btn-back:hover {
    background: #5a6268;
    transform: translateY(-2px);
    color: white;
}

.btn-primary {
    background: #A04657;
    color: white;
}

.btn-primary:hover {
    background: #6b2a36;
    transform: translateY(-2px);
}

/* Welcome & Error Cards */
.welcome-card, .error-card {
    background: #fff;
    border-radius: 16px;
    padding: 40px;
    text-align: center;
    border: 1px solid #e8e8e8;
    width: 100%;
}

.welcome-card i, .error-card i {
    font-size: 56px;
    color: #A04657;
    opacity: 0.5;
    margin-bottom: 16px;
}

.welcome-card h4, .error-card h4 {
    margin: 0 0 8px 0;
    font-size: 18px;
}

.welcome-card p, .error-card p {
    color: #666;
    margin-bottom: 16px;
    font-size: 13px;
}

/* Responsive */
@media (max-width: 1200px) {
    .summary-row {
        grid-template-columns: repeat(2, 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: 12px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .tank-info-card {
        flex-direction: column;
        text-align: center;
    }
    .info-grid {
        justify-content: center;
    }
    .summary-row {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .form-group {
        min-width: 100%;
    }
    .stock-table th, .stock-table td,
    .details-table th, .details-table td {
        font-size: 11px;
        padding: 8px 10px;
    }
    .action-buttons-container {
        flex-direction: column;
        align-items: stretch;
    }
    .btn-print, .btn-back, .btn-pdf {
        width: 100%;
        justify-content: center;
    }
    .filter-body {
        padding: 12px 16px;
    }
    .filter-header {
        padding: 10px 16px;
    }
}

/* Print Styles */
@media print {
    .sidebar, .top-header, .footer, .page-header, .filter-card, .action-buttons-container, .btn-print, .btn-back, .btn-pdf {
        display: none !important;
    }
    
    .main-content {
        margin: 0 !important;
        padding: 0 !important;
        width: 100% !important;
    }
    
    body {
        background: #fff;
        padding: 0;
    }
    
    .tank-info-card, .summary-card, .table-card, .loss-gain-card {
        break-inside: avoid;
        box-shadow: none;
        border: 1px solid #ddd;
    }
}

/* 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>
// Pass PHP variables to JavaScript for PDF header
const pdfFromDate = '<?php echo date('d-m-Y', strtotime($from_date)); ?>';
const pdfToDate = '<?php echo date('d-m-Y', strtotime($to_date)); ?>';
const pdfTankName = '<?php echo isset($tank_details) ? htmlspecialchars($tank_details['tank_name'], ENT_QUOTES) : ''; ?>';
const pdfFuelName = '<?php echo isset($tank_details) ? htmlspecialchars($tank_details['fuel_name'], ENT_QUOTES) : ''; ?>';

async function downloadPDF() {
    const element = document.getElementById('report-content');
    if (!element) {
        alert('No report content to download.');
        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(16);
            pdf.setTextColor(0, 0, 0);
            pdf.text('Tank Closing Report', 105, 36, { align: 'center' });
            
            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text(`Tank: ${pdfTankName} (${pdfFuelName})`, 105, 43, { align: 'center' });
            pdf.text(`Report Period: ${pdfFromDate} To ${pdfToDate}`, 105, 48, { align: 'center' });
            
            pdf.setDrawColor(160, 70, 87);
            pdf.setLineWidth(0.5);
            pdf.line(15, 52, 195, 52);
        }
        addHeader();

        const topMargin = 55;
        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 = `Tank_Closing_Report_${pdfTankName}_${pdfFromDate}_to_${pdfToDate}.pdf`.replace(/\s+/g, '_');
        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'); ?>