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

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

$success_message = "";
$error_message = "";

// Get fuel types for dropdown
$fuel_types_sql = "SELECT id, name, sale_price FROM fuel_types ORDER BY name";
$fuel_types_result = mysqli_query($conn, $fuel_types_sql);

// Add Tank
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_tank'])) {
    $fuel_type_id = mysqli_real_escape_string($conn, $_POST['fuel_type_id']);
    $tank_name = mysqli_real_escape_string($conn, $_POST['tank_name']);
    $capacity = mysqli_real_escape_string($conn, $_POST['capacity']);
    $opening_stock = mysqli_real_escape_string($conn, $_POST['opening_stock']);
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($fuel_type_id) || empty($tank_name) || empty($capacity)) {
        $error_message = "All fields are required!";
    } elseif(!is_numeric($capacity) || $capacity <= 0) {
        $error_message = "Capacity must be a positive number!";
    } elseif(!is_numeric($opening_stock) || $opening_stock < 0) {
        $error_message = "Opening stock must be a valid number!";
    } else {
        $sql = "INSERT INTO tanks (fuel_type_id, tank_name, capacity, current_stock, opening_stock, date_time) 
                VALUES ('$fuel_type_id', '$tank_name', '$capacity', '$opening_stock', '$opening_stock', '$date_time')";
        
        if(mysqli_query($conn, $sql)) {
            $success_message = "Tank added successfully!";
        } else {
            $error_message = "Error: " . mysqli_error($conn);
        }
    }
}

// Update Tank
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_tank'])) {
    $tank_id = mysqli_real_escape_string($conn, $_POST['tank_id']);
    $fuel_type_id = mysqli_real_escape_string($conn, $_POST['fuel_type_id']);
    $tank_name = mysqli_real_escape_string($conn, $_POST['tank_name']);
    $capacity = mysqli_real_escape_string($conn, $_POST['capacity']);
    $opening_stock = mysqli_real_escape_string($conn, $_POST['opening_stock']);
    
    if(empty($fuel_type_id) || empty($tank_name) || empty($capacity)) {
        $error_message = "All fields are required!";
    } elseif(!is_numeric($capacity) || $capacity <= 0) {
        $error_message = "Capacity must be a positive number!";
    } elseif(!is_numeric($opening_stock) || $opening_stock < 0) {
        $error_message = "Opening stock must be a valid number!";
    } else {
        $sql = "UPDATE tanks SET 
                fuel_type_id = '$fuel_type_id',
                tank_name = '$tank_name',
                capacity = '$capacity',
                current_stock = '$opening_stock',
                opening_stock = '$opening_stock'
                WHERE id = '$tank_id'";
        
        if(mysqli_query($conn, $sql)) {
            $success_message = "Tank updated successfully!";
        } else {
            $error_message = "Error: " . mysqli_error($conn);
        }
    }
}

// Delete Tank
if(isset($_GET['delete'])) {
    $delete_id = mysqli_real_escape_string($conn, $_GET['delete']);
    
    $check_purchases = "SELECT id FROM purchases WHERE tank_id = '$delete_id'";
    $purchases_result = mysqli_query($conn, $check_purchases);
    
    if(mysqli_num_rows($purchases_result) > 0) {
        $error_message = "Cannot delete! This tank has purchase records.";
    } else {
        $check_dips = "SELECT id FROM tank_dips WHERE tank_id = '$delete_id'";
        $dips_result = mysqli_query($conn, $check_dips);
        
        if(mysqli_num_rows($dips_result) > 0) {
            $error_message = "Cannot delete! This tank has dip readings.";
        } else {
            $sql = "DELETE FROM tanks WHERE id = '$delete_id'";
            if(mysqli_query($conn, $sql)) {
                $success_message = "Tank deleted successfully!";
            } else {
                $error_message = "Error deleting: " . mysqli_error($conn);
            }
        }
    }
}

// Get all tanks with fuel type names
$sql = "SELECT t.*, f.name as fuel_name, f.sale_price as fuel_price
        FROM tanks t 
        LEFT JOIN fuel_types f ON t.fuel_type_id = f.id 
        ORDER BY t.id DESC";
$result = mysqli_query($conn, $sql);

// Get single tank data for edit
$edit_tank = null;
if(isset($_GET['edit'])) {
    $edit_id = mysqli_real_escape_string($conn, $_GET['edit']);
    $edit_sql = "SELECT * FROM tanks WHERE id = '$edit_id'";
    $edit_result = mysqli_query($conn, $edit_sql);
    $edit_tank = mysqli_fetch_assoc($edit_result);
}

// Get tank statistics
$total_tanks = mysqli_num_rows($result);
$total_capacity = 0;
$total_opening_stock = 0;
$low_stock_count = 0;
$critical_stock_count = 0;

mysqli_data_seek($result, 0);
while($row = mysqli_fetch_assoc($result)) {
    $total_capacity += $row['capacity'];
    $total_opening_stock += $row['opening_stock'];
    $stock_percent = ($row['capacity'] > 0) ? ($row['current_stock'] / $row['capacity']) * 100 : 0;
    if($stock_percent <= 20) $low_stock_count++;
    if($stock_percent <= 10) $critical_stock_count++;
}
mysqli_data_seek($result, 0);
?>

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

<div class="tanks-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-tachometer-alt"></i> Tank Management</h2>
            <p>Monitor tank inventory, stock levels and fuel types</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span><?php echo $total_tanks; ?> Active Tanks</span>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-oil-can"></i></div>
            <div class="stat-info">
                <h3><?php echo $total_tanks; ?></h3>
                <p>Total Tanks</p>
                <span class="stat-trend">Active Containers</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-tachometer-alt"></i></div>
            <div class="stat-info">
                <h3><?php echo number_format($total_capacity, 2); ?> L</h3>
                <p>Total Capacity</p>
                <span class="stat-trend">Maximum Storage</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-chart-line"></i></div>
            <div class="stat-info">
                <h3><?php echo number_format($total_opening_stock, 2); ?> L</h3>
                <p>Total Opening Stock</p>
                <span class="stat-trend">Initial Inventory</span>
            </div>
        </div>
        <div class="stat-card <?php echo $low_stock_count > 0 ? 'stat-warning' : ''; ?>">
            <div class="stat-icon"><i class="fas fa-exclamation-triangle"></i></div>
            <div class="stat-info">
                <h3><?php echo $low_stock_count; ?></h3>
                <p>Low Stock Alerts</p>
                <span class="stat-trend">Below 20% Capacity</span>
            </div>
        </div>
    </div>

    <!-- Alerts -->
    <?php if($success_message): ?>
        <div class="alert-custom alert-success">
            <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>
    
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger">
            <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>
    
    <div class="content-grid">
        <!-- Add/Edit Tank Form -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-plus-circle"></i>
                <h4><?php echo isset($_GET['edit']) ? 'Edit Tank' : 'Add New Tank'; ?></h4>
            </div>
            <div class="form-card-body">
                <form method="POST" action="">
                    <?php if(isset($_GET['edit'])): ?>
                        <input type="hidden" name="tank_id" value="<?php echo $edit_tank['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-oil-can"></i> Fuel Type <span class="required">*</span></label>
                        <select name="fuel_type_id" class="form-control-modern" required>
                            <option value="">-- Select Fuel Type --</option>
                            <?php 
                            mysqli_data_seek($fuel_types_result, 0);
                            while($fuel = mysqli_fetch_assoc($fuel_types_result)): 
                                $selected = (isset($edit_tank) && $edit_tank['fuel_type_id'] == $fuel['id']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $fuel['id']; ?>" <?php echo $selected; ?>>
                                    <?php echo htmlspecialchars($fuel['name']); ?> 
                                    (Rs <?php echo number_format($fuel['sale_price'], 2); ?>/L)
                                </option>
                            <?php endwhile; ?>
                        </select>
                        <small class="input-help">Select the fuel type for this tank</small>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-tag"></i> Tank Name <span class="required">*</span></label>
                        <input type="text" name="tank_name" class="form-control-modern" required 
                               value="<?php echo isset($edit_tank) ? htmlspecialchars($edit_tank['tank_name']) : ''; ?>"
                               placeholder="e.g., Petrol Tank 1">
                        <small class="input-help">Unique identifier for this tank</small>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-ruler"></i> Capacity (Liters) <span class="required">*</span></label>
                        <input type="number" step="0.01" name="capacity" class="form-control-modern" required 
                               value="<?php echo isset($edit_tank) ? $edit_tank['capacity'] : ''; ?>"
                               placeholder="Enter capacity in liters">
                        <small class="input-help">Maximum storage capacity of the tank</small>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-chart-line"></i> Opening Stock (Liters)</label>
                        <input type="number" step="0.01" name="opening_stock" class="form-control-modern" 
                               value="<?php echo isset($edit_tank) ? ($edit_tank['opening_stock'] ?? $edit_tank['current_stock']) : '0'; ?>"
                               placeholder="Initial opening stock">
                        <small class="input-help warning-text">⚠️ STATIC VALUE - This value NEVER changes after tank creation</small>
                    </div>
                    
                    <div class="stock-preview" id="stockPreview" style="display: none;">
                        <div class="preview-row">
                            <span><i class="fas fa-chart-line"></i> Fill Level:</span>
                            <strong id="fillLevel">0%</strong>
                        </div>
                        <div class="preview-row">
                            <span><i class="fas fa-info-circle"></i> Status:</span>
                            <strong id="stockStatus">-</strong>
                        </div>
                    </div>
                    
                    <button type="submit" name="<?php echo isset($_GET['edit']) ? 'update_tank' : 'add_tank'; ?>" class="btn-submit">
                        <i class="fas fa-save"></i> <?php echo isset($_GET['edit']) ? 'Update Tank' : 'Add Tank'; ?>
                    </button>
                    
                    <?php if(isset($_GET['edit'])): ?>
                        <a href="tanks.php" class="btn-cancel-full mt-2">
                            <i class="fas fa-times"></i> Cancel Edit
                        </a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        
        <!-- Tanks List -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-list"></i>
                    <h4>Tanks Inventory Details</h4>
                </div>
                <div class="table-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="tableSearch" placeholder="Search tank..." class="search-input">
                </div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="tanksTable">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Tank Name</th>
                                <th>Fuel Type</th>
                                <th>Capacity (L)</th>
                                <th>Opening Stock (L)</th>
                                <th>Purchase (L)</th>
                                <th>Sale (L)</th>
                                <th>Calculated Closing (L)</th>
                                <th>Dip Reading (L)</th>
                                <th>Loss/Gain (L)</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($result) > 0): ?>
                                <?php while($row = mysqli_fetch_assoc($result)): 
                                    $tank_id = $row['id'];
                                    
                                    // Get total purchases
                                    $purchase_res = mysqli_query($conn, "SELECT SUM(quantity) as total FROM purchases WHERE tank_id = '$tank_id'");
                                    $purchase_data = mysqli_fetch_assoc($purchase_res);
                                    $total_purchase = $purchase_data['total'] ?? 0;
                                    
                                    // Get total sales
                                    $sales_res = mysqli_query($conn, "SELECT SUM(nr.sale_liters) as total FROM nozzle_readings nr INNER JOIN nozzles n ON nr.nozzle_id = n.id WHERE n.tank_id = '$tank_id'");
                                    $sales_data = mysqli_fetch_assoc($sales_res);
                                    $total_sale = $sales_data['total'] ?? 0;
                                    
                                    // Get dip reading
                                    $dip_res = mysqli_query($conn, "SELECT dip_value FROM tank_dips WHERE tank_id = '$tank_id' ORDER BY id DESC LIMIT 1");
                                    $dip_data = mysqli_fetch_assoc($dip_res);
                                    $latest_dip = $dip_data ? $dip_data['dip_value'] : null;
                                    
                                    // STATIC OPENING STOCK - This NEVER changes (from opening_stock column)
                                    $opening_stock = $row['opening_stock'] ?? $row['current_stock'];
                                    
                                    // CALCULATED CLOSING = Opening Stock + Total Purchases - Total Sales
                                    $calculated_closing = $opening_stock + $total_purchase - $total_sale;
                                    
                                    // Loss/Gain = Dip Reading - Calculated Closing
                                    $loss_gain = ($latest_dip !== null) ? $latest_dip - $calculated_closing : null;
                                    
                                    // Calculate stock percentage for status (based on calculated closing)
                                    $capacity = $row['capacity'];
                                    $stock_percent = ($capacity > 0) ? ($calculated_closing / $capacity) * 100 : 0;
                                    $stock_percent = min(100, max(0, $stock_percent));
                                    
                                    if($stock_percent <= 10) {
                                        $status = 'Critical';
                                        $status_class = 'status-critical';
                                        $status_icon = 'fa-skull-crosswalk';
                                    } elseif($stock_percent <= 20) {
                                        $status = 'Low';
                                        $status_class = 'status-low';
                                        $status_icon = 'fa-exclamation-triangle';
                                    } elseif($stock_percent <= 50) {
                                        $status = 'Moderate';
                                        $status_class = 'status-moderate';
                                        $status_icon = 'fa-chart-line';
                                    } elseif($stock_percent <= 80) {
                                        $status = 'Good';
                                        $status_class = 'status-good';
                                        $status_icon = 'fa-check-circle';
                                    } else {
                                        $status = 'Full';
                                        $status_class = 'status-full';
                                        $status_icon = 'fa-database';
                                    }
                                ?>
                                    <tr>
                                        <td data-label="ID"><strong>#<?php echo $row['id']; ?></strong></td>
                                        <td data-label="Tank Name">
                                            <div class="tank-name-cell">
                                                <i class="fas fa-tachometer-alt"></i>
                                                <strong><?php echo htmlspecialchars($row['tank_name']); ?></strong>
                                            </div>
                                         </div>
                                        <td data-label="Fuel Type">
                                            <div class="fuel-type-cell">
                                                <i class="fas fa-oil-can"></i>
                                                <?php echo htmlspecialchars($row['fuel_name']); ?>
                                                <span class="fuel-price">(Rs <?php echo number_format($row['fuel_price'], 2); ?>/L)</span>
                                            </div>
                                         </div>
                                        <td data-label="Capacity (L)"><?php echo number_format($capacity, 2); ?> L</div>
                                        <td data-label="Opening Stock (L)">
                                            <div class="opening-stock-value">
                                                <strong><?php echo number_format($opening_stock, 2); ?> L</strong>
                                                <span class="static-badge">STATIC</span>
                                            </div>
                                            <small class="formula-hint">Initial value (never changes)</small>
                                         </div>
                                        <td data-label="Purchase (L)">
                                            <div class="purchase-value">
                                                <?php echo number_format($total_purchase, 2); ?> L
                                                <i class="fas fa-plus-circle text-success"></i>
                                            </div>
                                            <small class="formula-hint">Added to stock</small>
                                         </div>
                                        <td data-label="Sale (L)">
                                            <div class="sale-value">
                                                <?php echo number_format($total_sale, 2); ?> L
                                                <i class="fas fa-minus-circle text-danger"></i>
                                            </div>
                                            <small class="formula-hint">Subtracted from stock</small>
                                         </div>
                                        <td data-label="Calculated Closing (L)">
                                            <div class="calculated-closing">
                                                <strong><?php echo number_format($calculated_closing, 2); ?> L</strong>
                                                <div class="formula-details">
                                                    <small><?php echo number_format($opening_stock, 2); ?> + <?php echo number_format($total_purchase, 2); ?> - <?php echo number_format($total_sale, 2); ?></small>
                                                </div>
                                            </div>
                                         </div>
                                        <td data-label="Dip Reading (L)">
                                            <?php if($latest_dip !== null): ?>
                                                <div class="dip-value">
                                                    <strong><?php echo number_format($latest_dip, 2); ?> L</strong>
                                                    <i class="fas fa-tape"></i>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-muted">Not recorded</span>
                                            <?php endif; ?>
                                         </div>
                                        <td data-label="Loss/Gain (L)">
                                            <?php if($loss_gain !== null): ?>
                                                <div class="<?php echo $loss_gain > 0 ? 'text-success' : ($loss_gain < 0 ? 'text-danger' : ''); ?> fw-bold">
                                                    <i class="fas <?php echo $loss_gain > 0 ? 'fa-arrow-up' : ($loss_gain < 0 ? 'fa-arrow-down' : 'fa-minus'); ?>"></i>
                                                    <?php echo ($loss_gain > 0 ? '+' : '') . number_format($loss_gain, 2); ?> L
                                                </div>
                                                <small class="formula-hint">Dip - Calculated</small>
                                            <?php else: ?>
                                                <span class="text-muted">No dip recorded</span>
                                            <?php endif; ?>
                                         </div>
                                        <td data-label="Status">
                                            <div class="status-container">
                                                <span class="status-badge <?php echo $status_class; ?>">
                                                    <i class="fas <?php echo $status_icon; ?>"></i>
                                                    <?php echo $status; ?>
                                                </span>
                                                <div class="progress-mini">
                                                    <div class="progress-fill" style="width: <?php echo $stock_percent; ?>%; background-color: <?php echo ($stock_percent <= 20) ? '#ffc107' : (($stock_percent <= 10) ? '#dc3545' : '#28a745'); ?>;"></div>
                                                </div>
                                                <small class="formula-hint"><?php echo round($stock_percent, 1); ?>% of capacity</small>
                                            </div>
                                         </div>
                                        <td data-label="Actions">
                                            <div class="action-buttons">
                                                <a href="?edit=<?php echo $row['id']; ?>" class="btn-action btn-edit" title="Edit Tank">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="?delete=<?php echo $row['id']; ?>" class="btn-action btn-delete" title="Delete Tank" onclick="return confirm('Delete this tank? This action cannot be undone!')">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </div>
                                         </div>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="12" class="empty-state">
                                        <i class="fas fa-database"></i>
                                        <p>No tanks found</p>
                                        <small>Click "Add New Tank" to get started</small>
                                     </div>
                                    </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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

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

h1, h2, h3, h4, h5, h6,
.page-header h2,
.stat-info h3,
.form-card-header h4,
.header-info h4,
.modern-table th {
    font-family: 'Times New Roman', serif;
}

/* Tanks Container */
.tanks-container {
    width: 100%;
    max-width: 100%;
    margin: 0;
    padding: 20px 30px;
}

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

.page-header h2 {
    margin: 0 0 5px 0;
    font-size: 22px;
    font-weight: 700;
}

.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: 30px;
    font-size: 12px;
    font-weight: 600;
}

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

.stat-card {
    background: #fff;
    border-radius: 14px;
    padding: 15px 18px;
    display: flex;
    align-items: center;
    gap: 15px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    border-left: 4px solid #A04657;
    transition: all 0.3s;
}

.stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(160,70,87,0.12);
}

.stat-icon {
    width: 48px;
    height: 48px;
    background: rgba(160,70,87,0.1);
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.stat-icon i {
    font-size: 22px;
    color: #A04657;
}

.stat-info h3 {
    font-size: 22px;
    margin: 0;
    font-weight: 700;
    color: #1a1a2e;
}

.stat-info p {
    margin: 3px 0 0;
    font-weight: 500;
    color: #6c7a8a;
    font-size: 11px;
}

.stat-trend {
    font-size: 9px;
    color: #999;
    display: block;
    margin-top: 2px;
}

.stat-warning {
    border-left-color: #ffc107;
}
.stat-warning .stat-icon i {
    color: #ffc107;
}

/* Alerts */
.alert-custom {
    padding: 12px 18px;
    border-radius: 12px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    width: 100%;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border-left: 4px solid #dc3545;
}

.close-alert {
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
    opacity: 0.6;
}

/* Content Grid */
.content-grid {
    display: grid;
    grid-template-columns: 340px 1fr;
    gap: 20px;
    width: 100%;
}

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 14px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    border: 1px solid #eee;
}

.form-card-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    padding: 14px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #fff;
}

.form-card-header i {
    font-size: 18px;
}

.form-card-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.form-card-body {
    padding: 20px;
}

.input-group-custom {
    margin-bottom: 15px;
}

.input-group-custom label {
    display: block;
    margin-bottom: 5px;
    font-weight: 600;
    color: #333;
    font-size: 12px;
}

.input-group-custom label i {
    color: #A04657;
    margin-right: 5px;
    width: 16px;
}

.required {
    color: #dc3545;
}

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

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    background: #fff;
    box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
}

.input-help {
    display: block;
    font-size: 10px;
    color: #999;
    margin-top: 4px;
}

.warning-text {
    color: #dc3545 !important;
}

.stock-preview {
    background: #f8f9fc;
    border-radius: 10px;
    padding: 10px;
    margin-bottom: 15px;
    border-left: 3px solid #A04657;
}

.preview-row {
    display: flex;
    justify-content: space-between;
    padding: 3px 0;
    font-size: 11px;
}

.btn-submit {
    width: 100%;
    padding: 10px;
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
}

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

.btn-cancel-full {
    display: block;
    text-align: center;
    padding: 8px;
    background: #f0f0f0;
    color: #666;
    text-decoration: none;
    border-radius: 10px;
    font-size: 12px;
    transition: all 0.2s;
    margin-top: 10px;
}

.btn-cancel-full:hover {
    background: #e0e0e0;
    color: #333;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 14px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    border: 1px solid #eee;
    width: 100%;
}

.table-card-header {
    padding: 14px 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: 16px;
    font-weight: 600;
}

.table-search {
    position: relative;
}

.table-search i {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #999;
    font-size: 11px;
}

.search-input {
    padding: 7px 10px 7px 32px;
    border: 2px solid #e0e0e0;
    border-radius: 30px;
    width: 200px;
    font-size: 11px;
}

.search-input:focus {
    border-color: #A04657;
    outline: none;
}

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

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

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

.modern-table td {
    padding: 9px 10px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
}

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

/* Numeric columns alignment */
.modern-table td:nth-child(4),
.modern-table td:nth-child(5),
.modern-table td:nth-child(6),
.modern-table td:nth-child(7),
.modern-table td:nth-child(8),
.modern-table td:nth-child(9),
.modern-table td:nth-child(10) {
    text-align: right;
}

/* Cell Components */
.tank-name-cell, .fuel-type-cell {
    display: flex;
    align-items: center;
    gap: 6px;
}

.tank-name-cell i, .fuel-type-cell i {
    color: #A04657;
    font-size: 12px;
}

.fuel-price {
    font-size: 9px;
    color: #999;
    margin-left: 4px;
}

.opening-stock-value {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 5px;
    flex-wrap: wrap;
}

.static-badge {
    background: #6c5ce7;
    color: #fff;
    padding: 2px 5px;
    border-radius: 15px;
    font-size: 7px;
    font-weight: 600;
}

.purchase-value, .sale-value {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 4px;
    font-weight: 600;
}

.purchase-value { color: #17a2b8; }
.sale-value { color: #fd7e14; }

.calculated-closing strong {
    color: #A04657;
    font-size: 12px;
}

.formula-details {
    margin-top: 2px;
}

.formula-details small {
    font-family: monospace;
    background: #f0f0f0;
    padding: 1px 4px;
    border-radius: 4px;
    font-size: 8px;
}

.dip-value {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 4px;
    font-weight: 600;
    color: #A04657;
}

.formula-hint {
    display: block;
    font-size: 8px;
    color: #999;
    margin-top: 2px;
}

.text-success { color: #28a745 !important; }
.text-danger { color: #dc3545 !important; }
.text-muted { color: #999 !important; }
.fw-bold { font-weight: 700; }

/* Status Badge */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 2px 8px;
    border-radius: 15px;
    font-size: 9px;
    font-weight: 600;
    white-space: nowrap;
}

.status-critical { background: #ffebee; color: #dc3545; }
.status-low { background: #fff3cd; color: #ffc107; }
.status-moderate { background: #d1ecf1; color: #17a2b8; }
.status-good { background: #d4edda; color: #28a745; }
.status-full { background: #e8d5f5; color: #6c5ce7; }

/* Progress Bar */
.progress-mini {
    width: 100%;
    height: 3px;
    background: #e0e0e0;
    border-radius: 10px;
    overflow: hidden;
    margin: 5px 0 2px;
}

.progress-fill {
    height: 100%;
    border-radius: 10px;
    transition: width 0.3s;
}

/* Action Buttons */
.action-buttons {
    display: flex;
    gap: 5px;
    justify-content: center;
}

.btn-action {
    width: 26px;
    height: 26px;
    border-radius: 6px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    transition: all 0.2s;
}

.btn-edit {
    background: #fff3e0;
    color: #ff9800;
}

.btn-edit:hover {
    background: #ff9800;
    color: #fff;
    transform: scale(1.05);
}

.btn-delete {
    background: #ffebee;
    color: #dc3545;
}

.btn-delete:hover {
    background: #dc3545;
    color: #fff;
    transform: scale(1.05);
}

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

.empty-state i {
    font-size: 40px;
    color: #A04657;
    opacity: 0.4;
    margin-bottom: 10px;
    display: block;
}

.empty-state p {
    margin: 0;
    color: #666;
    font-weight: 500;
    font-size: 13px;
}

.empty-state small {
    color: #999;
    font-size: 11px;
}

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

@media (max-width: 992px) {
    .tanks-container {
        padding: 15px;
    }
}

@media (max-width: 768px) {
    .tanks-container {
        padding: 12px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 15px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .stats-row {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .stat-card {
        padding: 12px 15px;
    }
    .stat-icon {
        width: 40px;
        height: 40px;
    }
    .stat-icon i {
        font-size: 18px;
    }
    .stat-info h3 {
        font-size: 18px;
    }
    .table-card-header {
        flex-direction: column;
        align-items: stretch;
    }
    .search-input {
        width: 100%;
    }
    .modern-table th {
        display: none;
    }
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 45%;
        position: relative;
    }
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 10px;
        width: 40%;
        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: 10px;
        overflow: hidden;
    }
    .form-card-body {
        padding: 15px;
    }
}

/* 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>

<script>
// Table search functionality
document.getElementById('tableSearch')?.addEventListener('keyup', function() {
    let searchValue = this.value.toLowerCase();
    let rows = document.querySelectorAll('#tanksTable tbody tr');
    rows.forEach(row => {
        let text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchValue) ? '' : 'none';
    });
});

// Stock preview in form
const capacityInput = document.querySelector('input[name="capacity"]');
const stockInput = document.querySelector('input[name="opening_stock"]');
const stockPreview = document.getElementById('stockPreview');
const fillLevelSpan = document.getElementById('fillLevel');
const stockStatusSpan = document.getElementById('stockStatus');

function updateStockPreview() {
    const capacity = parseFloat(capacityInput?.value) || 0;
    const stock = parseFloat(stockInput?.value) || 0;
    
    if(capacity > 0 && stockPreview) {
        stockPreview.style.display = 'block';
        const percent = (stock / capacity) * 100;
        fillLevelSpan.innerHTML = percent.toFixed(1) + '%';
        
        if(percent <= 10) {
            stockStatusSpan.innerHTML = '⚠️ Critical - Need immediate refill';
            stockStatusSpan.style.color = '#dc3545';
        } else if(percent <= 20) {
            stockStatusSpan.innerHTML = '⚠️ Low - Refill soon';
            stockStatusSpan.style.color = '#ffc107';
        } else if(percent <= 50) {
            stockStatusSpan.innerHTML = 'ℹ️ Moderate - Acceptable level';
            stockStatusSpan.style.color = '#17a2b8';
        } else if(percent <= 80) {
            stockStatusSpan.innerHTML = '✅ Good - Healthy stock';
            stockStatusSpan.style.color = '#28a745';
        } else {
            stockStatusSpan.innerHTML = '📊 Full - Tank almost full';
            stockStatusSpan.style.color = '#6c5ce7';
        }
    } else if(stockPreview) {
        stockPreview.style.display = 'none';
    }
}

capacityInput?.addEventListener('input', updateStockPreview);
stockInput?.addEventListener('input', updateStockPreview);
</script>

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