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

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

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

// Delete Dip Reading
if(isset($_GET['delete'])) {
    $delete_id = mysqli_real_escape_string($conn, $_GET['delete']);
    $sql = "DELETE FROM tank_dips WHERE id='$delete_id'";
    if(mysqli_query($conn, $sql)) {
        $success_message = "Dip reading deleted successfully!";
    } else {
        $error_message = "Error deleting: " . mysqli_error($conn);
    }
}

// Function to get volume from calibration by fuel_type_id
function getVolumeFromCalibration($conn, $fuel_type_id, $dip_meter) {
    if (!$conn || $fuel_type_id <= 0 || $dip_meter <= 0) {
        return null;
    }
    
    // First, try exact match
    $sql = "SELECT volume_liters FROM tank_calibration 
            WHERE fuel_type_id = ? AND dip_meter = ?";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "id", $fuel_type_id, $dip_meter);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        mysqli_stmt_close($stmt);
        return floatval($row['volume_liters']);
    }
    mysqli_stmt_close($stmt);
    
    // Find lower bound
    $sql_lower = "SELECT dip_meter, volume_liters FROM tank_calibration 
                  WHERE fuel_type_id = ? AND dip_meter <= ?
                  ORDER BY dip_meter DESC LIMIT 1";
    $stmt_lower = mysqli_prepare($conn, $sql_lower);
    mysqli_stmt_bind_param($stmt_lower, "id", $fuel_type_id, $dip_meter);
    mysqli_stmt_execute($stmt_lower);
    $lower_result = mysqli_stmt_get_result($stmt_lower);
    $lower_data = mysqli_fetch_assoc($lower_result);
    mysqli_stmt_close($stmt_lower);
    
    // Find upper bound
    $sql_upper = "SELECT dip_meter, volume_liters FROM tank_calibration 
                  WHERE fuel_type_id = ? AND dip_meter >= ?
                  ORDER BY dip_meter ASC LIMIT 1";
    $stmt_upper = mysqli_prepare($conn, $sql_upper);
    mysqli_stmt_bind_param($stmt_upper, "id", $fuel_type_id, $dip_meter);
    mysqli_stmt_execute($stmt_upper);
    $upper_result = mysqli_stmt_get_result($stmt_upper);
    $upper_data = mysqli_fetch_assoc($upper_result);
    mysqli_stmt_close($stmt_upper);
    
    // Interpolate if both bounds exist
    if ($lower_data && $upper_data) {
        $dip_diff = $upper_data['dip_meter'] - $lower_data['dip_meter'];
        $vol_diff = $upper_data['volume_liters'] - $lower_data['volume_liters'];
        if ($dip_diff == 0) return $lower_data['volume_liters'];
        $ratio = ($dip_meter - $lower_data['dip_meter']) / $dip_diff;
        return round($lower_data['volume_liters'] + ($ratio * $vol_diff), 2);
    }
    
    if ($lower_data) return $lower_data['volume_liters'];
    if ($upper_data) return $upper_data['volume_liters'];
    
    return null;
}

// Function to calculate actual stock - SAME LOGIC AS tanks.php
// Calculated Closing = Opening Stock + Total Purchases - Total Sales
function getActualStock($conn, $tank_id) {
    // Get opening stock from tanks table
    $tank_sql = "SELECT opening_stock, fuel_type_id FROM tanks WHERE id = $tank_id";
    $tank_result = mysqli_query($conn, $tank_sql);
    $tank = mysqli_fetch_assoc($tank_result);
    $opening_stock = $tank['opening_stock'];
    $fuel_type_id = $tank['fuel_type_id'];
    
    // Get total purchases for this tank
    $purchase_sql = "SELECT SUM(quantity) as total_purchases FROM purchases WHERE tank_id = '$tank_id'";
    $purchase_result = mysqli_query($conn, $purchase_sql);
    $purchase_data = mysqli_fetch_assoc($purchase_result);
    $total_purchases = $purchase_data['total_purchases'] ?? 0;
    
    // Get total sales for this tank (from nozzle readings)
    $sales_sql = "SELECT SUM(nr.sale_liters) as total_sales 
                  FROM nozzle_readings nr 
                  INNER JOIN nozzles n ON nr.nozzle_id = n.id 
                  WHERE n.tank_id = '$tank_id'";
    $sales_result = mysqli_query($conn, $sales_sql);
    $sales_data = mysqli_fetch_assoc($sales_result);
    $total_sales = $sales_data['total_sales'] ?? 0;
    
    // Calculated Closing = Opening Stock + Total Purchases - Total Sales
    $calculated_closing = $opening_stock + $total_purchases - $total_sales;
    
    return [
        'stock' => $calculated_closing,
        'opening_stock' => $opening_stock,
        'total_purchases' => $total_purchases,
        'total_sales' => $total_sales,
        'fuel_type_id' => $fuel_type_id
    ];
}

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

// Get all tanks
$tanks_sql = "SELECT id, tank_name, fuel_type_id, capacity, opening_stock FROM tanks ORDER BY tank_name";
$tanks_result = mysqli_query($conn, $tanks_sql);

// Variables for calculation result
$calc_converted = null;
$calc_difference = null;
$calc_status = null;
$calc_message = null;
$calc_dip_meter = null;
$calc_system_stock = null;
$calc_fuel_name = null;
$calc_tank_name = null;
$calc_tank_capacity = null;

// Handle Calculate button (GET request)
if(isset($_GET['calculate'])) {
    $tank_id = isset($_GET['tank_id']) ? intval($_GET['tank_id']) : 0;
    $dip_meter = isset($_GET['dip_meter']) ? floatval($_GET['dip_meter']) : 0;
    $calc_dip_meter = $dip_meter;
    
    if($tank_id > 0 && $dip_meter > 0) {
        // Get calculated stock using same logic as tanks.php
        $stock_data = getActualStock($conn, $tank_id);
        $calc_system_stock = $stock_data['stock'];
        $fuel_type_id = $stock_data['fuel_type_id'];
        
        // Get tank name and capacity
        $tank_info_sql = "SELECT tank_name, capacity FROM tanks WHERE id = $tank_id";
        $tank_info_result = mysqli_query($conn, $tank_info_sql);
        $tank_info = mysqli_fetch_assoc($tank_info_result);
        $calc_tank_name = $tank_info['tank_name'];
        $calc_tank_capacity = $tank_info['capacity'];
        
        // Get fuel name
        $fuel_sql = "SELECT name FROM fuel_types WHERE id = $fuel_type_id";
        $fuel_result = mysqli_query($conn, $fuel_sql);
        $fuel_data = mysqli_fetch_assoc($fuel_result);
        $calc_fuel_name = $fuel_data['name'];
        
        $calc_converted = getVolumeFromCalibration($conn, $fuel_type_id, $dip_meter);
        
        if($calc_converted !== null) {
            $calc_difference = $calc_converted - $calc_system_stock;
            if($calc_difference < 0) {
                $calc_status = 'LOSS';
                $calc_message = 'LOSS: ' . number_format(abs($calc_difference), 2) . ' Liters less than system stock';
            } elseif($calc_difference > 0) {
                $calc_status = 'GAIN';
                $calc_message = 'GAIN: ' . number_format($calc_difference, 2) . ' Liters extra than system stock';
            } else {
                $calc_status = 'OK';
                $calc_message = 'Perfect match! Dip equals system stock.';
            }
        } else {
            $calc_message = 'No calibration data found for dip height: ' . $dip_meter . 'm';
        }
    }
}

// Handle Save button (POST)
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_dip'])) {
    $tank_id = mysqli_real_escape_string($conn, $_POST['tank_id']);
    $dip_meter = mysqli_real_escape_string($conn, $_POST['dip_meter']);
    $dip_date = mysqli_real_escape_string($conn, $_POST['dip_date']);
    $dip_time = mysqli_real_escape_string($conn, $_POST['dip_time']);
    $date_time = $dip_date . ' ' . $dip_time;
    
    if(empty($tank_id)) {
        $error_message = "Please select a tank!";
    } elseif(empty($dip_meter) || !is_numeric($dip_meter) || $dip_meter <= 0) {
        $error_message = "Dip value must be a positive number in meters!";
    } else {
        // Get calculated stock using same logic as tanks.php
        $stock_data = getActualStock($conn, $tank_id);
        $system_stock = $stock_data['stock'];
        $fuel_type_id = $stock_data['fuel_type_id'];
        
        $converted_liters = getVolumeFromCalibration($conn, $fuel_type_id, $dip_meter);
        
        if($converted_liters === null) {
            $error_message = "No calibration data found for dip height: " . $dip_meter . "m. Please add calibration data first.";
        } else {
            $difference = $converted_liters - $system_stock;
            if($difference < 0) { $status = 'LOSS'; }
            elseif($difference > 0) { $status = 'GAIN'; }
            else { $status = 'OK'; }
            
            $sql = "INSERT INTO tank_dips (tank_id, dip_value, date_time, dip_meter, converted_liters, difference, status) 
                    VALUES ('$tank_id', '$converted_liters', '$date_time', '$dip_meter', '$converted_liters', '$difference', '$status')";
            
            if(mysqli_query($conn, $sql)) {
                $success_message = "Dip reading recorded! " . $dip_meter . "m = " . number_format($converted_liters, 2) . " Liters. " . $status;
            } else {
                $error_message = "Error: " . mysqli_error($conn);
            }
        }
    }
}

// Get all dip readings
$dips_sql = "SELECT d.*, t.tank_name, t.capacity, t.opening_stock,
                    f.name as fuel_name
             FROM tank_dips d
             LEFT JOIN tanks t ON d.tank_id = t.id
             LEFT JOIN fuel_types f ON t.fuel_type_id = f.id
             ORDER BY d.id DESC";
$dips_result = mysqli_query($conn, $dips_sql);

$total_readings = ($dips_result) ? mysqli_num_rows($dips_result) : 0;
$loss_count = $gain_count = $ok_count = 0;

if($dips_result && mysqli_num_rows($dips_result) > 0) {
    mysqli_data_seek($dips_result, 0);
    while($row = mysqli_fetch_assoc($dips_result)) {
        $diff = $row['difference'];
        if($diff < 0) $loss_count++;
        elseif($diff > 0) $gain_count++;
        else $ok_count++;
    }
    mysqli_data_seek($dips_result, 0);
}

// Prepare tanks data for JavaScript - with calculated stock
$tanks_data = [];
if($tanks_result && mysqli_num_rows($tanks_result) > 0) {
    mysqli_data_seek($tanks_result, 0);
    while($tank = mysqli_fetch_assoc($tanks_result)) {
        $stock_data = getActualStock($conn, $tank['id']);
        $tanks_data[] = [
            'id' => $tank['id'],
            'name' => $tank['tank_name'],
            'fuel_type_id' => $tank['fuel_type_id'],
            'stock' => $stock_data['stock'],
            'opening_stock' => $stock_data['opening_stock'],
            'total_purchases' => $stock_data['total_purchases'],
            'total_sales' => $stock_data['total_sales'],
            'capacity' => $tank['capacity']
        ];
    }
}
?>

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

<div class="dip-container">
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-tape"></i> Dip Readings Management</h2>
            <p>Record physical dip measurements (in meters) - Auto converted to liters using calibration chart</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span><?php echo $total_readings; ?> Total Readings</span>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row g-4 mb-4">
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon"><i class="fas fa-tape"></i></div>
                <div class="stat-info">
                    <h3><?php echo $total_readings; ?></h3>
                    <p>Total Readings</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card stat-loss">
                <div class="stat-icon"><i class="fas fa-arrow-down"></i></div>
                <div class="stat-info">
                    <h3><?php echo $loss_count; ?></h3>
                    <p>Loss Events</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card stat-gain">
                <div class="stat-icon"><i class="fas fa-arrow-up"></i></div>
                <div class="stat-info">
                    <h3><?php echo $gain_count; ?></h3>
                    <p>Gain Events</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card stat-ok">
                <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
                <div class="stat-info">
                    <h3><?php echo $ok_count; ?></h3>
                    <p>Accurate</p>
                </div>
            </div>
        </div>
    </div>

    <?php if($success_message): ?>
        <div class="alert-custom alert-success"><i class="fas fa-check-circle"></i> <?php echo $success_message; ?></div>
    <?php endif; ?>
    
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger"><i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?></div>
    <?php endif; ?>
    
    <div class="row g-4">
        <div class="col-xl-5 col-lg-6">
            <div class="form-card">
                <div class="form-card-header">
                    <i class="fas fa-plus-circle"></i>
                    <h4>Record New Dip Reading</h4>
                </div>
                <div class="form-card-body">
                    <form method="POST" action="" id="dipForm">
                        <!-- Fuel Type Selection -->
                        <div class="input-group-custom">
                            <label><i class="fas fa-oil-can"></i> Select Fuel Type <span class="required">*</span></label>
                            <select name="fuel_type_id" id="fuel_type_id" class="form-control-modern" required onchange="loadTanksByFuel()">
                                <option value="">-- Select Fuel Type --</option>
                                <?php 
                                if($fuel_types_result && mysqli_num_rows($fuel_types_result) > 0):
                                    mysqli_data_seek($fuel_types_result, 0);
                                    while($fuel = mysqli_fetch_assoc($fuel_types_result)): 
                                ?>
                                    <option value="<?php echo $fuel['id']; ?>"><?php echo htmlspecialchars($fuel['name']); ?></option>
                                <?php endwhile; endif; ?>
                            </select>
                        </div>
                        
                        <!-- Tank Selection -->
                        <div class="input-group-custom">
                            <label><i class="fas fa-tachometer-alt"></i> Select Tank <span class="required">*</span></label>
                            <select name="tank_id" id="tank_id" class="form-control-modern" required>
                                <option value="">-- First select fuel type --</option>
                            </select>
                        </div>
                        
                        <!-- Dip Height -->
                        <div class="input-group-custom">
                            <label><i class="fas fa-ruler"></i> Dip Height (Meters) <span class="required">*</span></label>
                            <input type="number" step="0.001" name="dip_meter" id="dip_meter" class="form-control-modern" required placeholder="e.g., 0.100 or 1.250">
                            <small class="input-help">Physical measurement from dipstick in METERS</small>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="input-group-custom">
                                    <label><i class="fas fa-calendar"></i> Date</label>
                                    <input type="date" name="dip_date" id="dip_date" class="form-control-modern" value="<?php echo date('Y-m-d'); ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="input-group-custom">
                                    <label><i class="fas fa-clock"></i> Time</label>
                                    <input type="time" name="dip_time" id="dip_time" class="form-control-modern" value="<?php echo date('H:i'); ?>">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <button type="button" class="btn-calculate" onclick="calculateAndShow()">
                                    <i class="fas fa-calculator"></i> Calculate
                                </button>
                            </div>
                            <div class="col-md-6">
                                <button type="submit" name="save_dip" class="btn-submit">
                                    <i class="fas fa-save"></i> Save Dip Reading
                                </button>
                            </div>
                        </div>
                    </form>
                    
                    <!-- Calculation Result Display -->
                    <?php if($calc_converted !== null): ?>
                    <div class="calculation-result mt-3">
                        <div class="result-header"><i class="fas fa-chart-line"></i> Calculation Result</div>
                        <div class="result-row">
                            <span>Tank:</span>
                            <strong><?php echo htmlspecialchars($calc_tank_name); ?></strong>
                        </div>
                        <div class="result-row">
                            <span>Fuel Type:</span>
                            <strong><?php echo htmlspecialchars($calc_fuel_name); ?></strong>
                        </div>
                        <div class="result-row">
                            <span>Dip Height:</span>
                            <strong><?php echo number_format($calc_dip_meter, 3); ?> meters</strong>
                        </div>
                        <div class="result-row">
                            <span>Calculated Closing Stock:</span>
                            <strong><?php echo number_format($calc_system_stock, 2); ?> Liters</strong>
                        </div>
                        <div class="result-row">
                            <span>Converted Volume:</span>
                            <strong style="color: #17a2b8;"><?php echo number_format($calc_converted, 2); ?> Liters</strong>
                        </div>
                        <div class="result-row">
                            <span>Difference:</span>
                            <strong style="color: <?php echo ($calc_difference < 0 ? '#dc3545' : ($calc_difference > 0 ? '#28a745' : '#ffc107')); ?>;">
                                <?php echo ($calc_difference >= 0 ? '+' : '') . number_format($calc_difference, 2); ?> Liters
                            </strong>
                        </div>
                        <div class="result-message <?php echo strtolower($calc_status); ?>-msg">
                            <i class="fas <?php echo ($calc_status == 'LOSS' ? 'fa-arrow-down' : ($calc_status == 'GAIN' ? 'fa-arrow-up' : 'fa-check')); ?>"></i>
                            <?php echo $calc_message; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-xl-7 col-lg-6">
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-history"></i>
                        <h4>Dip Reading History</h4>
                    </div>
                    <div class="table-search">
                        <input type="text" id="tableSearch" placeholder="Search by tank..." class="search-input">
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="modern-table" id="dipTable">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Tank Name</th>
                                    <th>Fuel Type</th>
                                    <th>Dip (m)</th>
                                    <th>Volume (L)</th>
                                    <th>Calculated Closing (L)</th>
                                    <th>Diff (L)</th>
                                    <th>Status</th>
                                    <th>Date & Time</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if($dips_result && mysqli_num_rows($dips_result) > 0): ?>
                                    <?php while($row = mysqli_fetch_assoc($dips_result)): 
                                        $difference = $row['difference'];
                                        if($difference < 0) { $status = 'LOSS'; $status_class = 'status-loss'; }
                                        elseif($difference > 0) { $status = 'GAIN'; $status_class = 'status-gain'; }
                                        else { $status = 'OK'; $status_class = 'status-ok'; }
                                        
                                        // Calculate current closing stock for this tank
                                        $current_stock_data = getActualStock($conn, $row['tank_id']);
                                        $current_closing = $current_stock_data['stock'];
                                    ?>
                                        <tr>
                                            <td data-label="#"><?php echo $row['id']; ?></td>
                                            <td data-label="Tank Name"><strong><?php echo htmlspecialchars($row['tank_name']); ?></strong></td>
                                            <td data-label="Fuel Type"><?php echo htmlspecialchars($row['fuel_name']); ?></td>
                                            <td data-label="Dip (m)"><?php echo number_format($row['dip_meter'], 3); ?></td>
                                            <td data-label="Volume (L)"><?php echo number_format($row['dip_value'], 2); ?></td>
                                            <td data-label="Calculated Closing (L)"><strong><?php echo number_format($current_closing, 2); ?> L</strong></div>
                                            <td data-label="Diff (L)"><?php echo ($difference >= 0 ? '+' : '') . number_format($difference, 2); ?> </div>
                                            <td data-label="Status"><span class="status-badge <?php echo $status_class; ?>"><?php echo $status; ?></span></div>
                                            <td data-label="Date & Time"><?php echo date('d-m-Y H:i', strtotime($row['date_time'])); ?></div>
                                            <td data-label="Actions"><a href="?delete=<?php echo $row['id']; ?>" class="btn-delete" onclick="return confirm('Delete?')"><i class="fas fa-trash"></i></a></div>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="10" class="text-center empty-state"><i class="fas fa-tape"></i><p>No dip readings found</p></td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.dip-container { padding: 0; }
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 20px;
    padding: 25px 30px;
    margin-bottom: 25px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
}
.page-header h2 { color: #fff; margin: 0; font-size: 28px; }
.page-header p { color: rgba(255,255,255,0.9); margin: 5px 0 0; font-size: 13px; }
.stats-badge { background: rgba(255,255,255,0.2); padding: 10px 18px; border-radius: 12px; font-size: 13px; }
.stat-card {
    background: #fff;
    border-radius: 20px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    border-left: 4px solid #A04657;
}
.stat-card.stat-loss { border-left-color: #dc3545; }
.stat-card.stat-gain { border-left-color: #28a745; }
.stat-card.stat-ok { border-left-color: #ffc107; }
.stat-icon {
    width: 60px;
    height: 60px;
    background: rgba(160,70,87,0.1);
    border-radius: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.stat-icon i { font-size: 28px; color: #A04657; }
.stat-info h3 { font-size: 28px; margin: 0; font-weight: bold; }
.stat-info p { margin: 5px 0 0; color: #555; font-size: 13px; }
.alert-custom { padding: 15px 20px; border-radius: 12px; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; }
.alert-success { background: #d4edda; color: #155724; border-left: 4px solid #28a745; }
.alert-danger { background: #f8d7da; color: #721c24; border-left: 4px solid #dc3545; }
.form-card { background: #fff; border-radius: 20px; overflow: hidden; box-shadow: 0 5px 20px rgba(0,0,0,0.05); margin-bottom: 20px; }
.form-card-header { background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%); padding: 20px; display: flex; align-items: center; gap: 12px; color: #fff; }
.form-card-header h4 { margin: 0; font-size: 18px; color: #fff; }
.form-card-body { padding: 25px; }
.input-group-custom { margin-bottom: 20px; }
.input-group-custom label { display: block; margin-bottom: 8px; font-weight: 700; color: #333; font-size: 14px; }
.input-group-custom label i { color: #A04657; margin-right: 5px; }
.required { color: #dc3545; }
.form-control-modern {
    width: 100%;
    padding: 12px 15px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    font-size: 14px;
    transition: all 0.3s;
}
.form-control-modern:focus { border-color: #A04657; outline: none; box-shadow: 0 0 0 3px rgba(160,70,87,0.1); }
.input-help { font-size: 11px; color: #666; margin-top: 5px; display: block; }
.btn-calculate, .btn-submit {
    width: 100%;
    padding: 14px;
    border: none;
    border-radius: 10px;
    font-weight: 700;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s;
}
.btn-calculate { background: #6c757d; color: #fff; }
.btn-calculate:hover { background: #5a6268; transform: translateY(-2px); }
.btn-submit { background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%); color: #fff; margin-top: 10px; }
.btn-submit:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(160,70,87,0.3); }
.calculation-result { background: #fff; border: 2px solid #A04657; border-radius: 15px; padding: 15px; margin-top: 15px; }
.result-header { font-weight: bold; margin-bottom: 10px; color: #A04657; border-bottom: 1px solid #eee; padding-bottom: 5px; }
.result-header i { margin-right: 5px; }
.result-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px dashed #eee; }
.result-row:last-child { border-bottom: none; }
.result-message { margin-top: 10px; padding: 10px; border-radius: 8px; text-align: center; font-weight: 500; }
.loss-msg { background: #f8d7da; color: #dc3545; }
.gain-msg { background: #d4edda; color: #28a745; }
.ok-msg { background: #fff3cd; color: #ffc107; }
.table-card { background: #fff; border-radius: 20px; overflow: hidden; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
.table-card-header { padding: 20px; border-bottom: 1px solid #f0f0f0; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; }
.header-info { display: flex; align-items: center; gap: 10px; }
.header-info i { font-size: 20px; color: #A04657; }
.header-info h4 { margin: 0; font-size: 18px; }
.search-input { padding: 10px 15px; border: 2px solid #e0e0e0; border-radius: 10px; width: 250px; }
.modern-table { width: 100%; border-collapse: collapse; }
.modern-table th { padding: 15px; background: #f8f9fa; font-weight: 700; color: #444; font-size: 13px; }
.modern-table td { padding: 15px; border-bottom: 1px solid #f0f0f0; }
.status-badge { display: inline-flex; padding: 5px 12px; border-radius: 20px; font-size: 12px; font-weight: 700; }
.status-loss { background: #f8d7da; color: #dc3545; }
.status-gain { background: #d4edda; color: #28a745; }
.status-ok { background: #fff3cd; color: #ffc107; }
.btn-delete { background: #fee; color: #dc3545; padding: 5px 10px; border-radius: 5px; display: inline-block; text-decoration: none; }
.btn-delete:hover { background: #dc3545; color: #fff; }
.empty-state { padding: 50px; text-align: center; }
.empty-state i { font-size: 48px; color: #A04657; }
.text-center { text-align: center; }
@media (max-width: 768px) {
    .page-header { flex-direction: column; text-align: center; gap: 15px; }
    .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: 50%; position: relative; }
    .modern-table td::before { content: attr(data-label); position: absolute; left: 15px; width: 45%; text-align: left; font-weight: bold; }
}
</style>

<script>
// Store tanks data from PHP
const allTanks = <?php echo json_encode($tanks_data); ?>;

function loadTanksByFuel() {
    const fuelTypeId = document.getElementById('fuel_type_id').value;
    const tankSelect = document.getElementById('tank_id');
    
    if(!fuelTypeId) {
        tankSelect.innerHTML = '<option value="">-- First select fuel type --</option>';
        return;
    }
    
    const filteredTanks = allTanks.filter(tank => tank.fuel_type_id == fuelTypeId);
    
    if(filteredTanks.length > 0) {
        let options = '<option value="">-- Select Tank --</option>';
        filteredTanks.forEach(tank => {
            let stockValue = parseFloat(tank.stock).toFixed(2);
            let percentage = tank.capacity > 0 ? ((tank.stock / tank.capacity) * 100).toFixed(1) : 0;
            options += `<option value="${tank.id}" data-stock="${tank.stock}">${tank.name} - Calculated Closing: ${stockValue}L (${percentage}% of capacity)</option>`;
        });
        tankSelect.innerHTML = options;
    } else {
        tankSelect.innerHTML = '<option value="">No tanks found for this fuel type</option>';
    }
}

function calculateAndShow() {
    const tankId = document.getElementById('tank_id').value;
    const dipMeter = document.getElementById('dip_meter').value;
    
    if(!tankId) {
        alert('Please select a tank first');
        return;
    }
    if(!dipMeter || dipMeter <= 0) {
        alert('Please enter valid dip height in meters');
        return;
    }
    
    // Redirect to same page with GET parameters
    window.location.href = window.location.pathname + '?calculate=1&tank_id=' + tankId + '&dip_meter=' + dipMeter;
}

// Set default date
document.getElementById('dip_date').value = new Date().toISOString().split('T')[0];

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

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