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

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

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

// Add Fuel Type with both prices
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_fuel_type'])) {
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $sale_price = mysqli_real_escape_string($conn, $_POST['sale_price']);
    $purchase_price = mysqli_real_escape_string($conn, $_POST['purchase_price']);
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($name)) {
        $error_message = "Fuel Type name is required!";
    } elseif(empty($sale_price) || !is_numeric($sale_price) || $sale_price <= 0) {
        $error_message = "Valid sale price is required!";
    } elseif(empty($purchase_price) || !is_numeric($purchase_price) || $purchase_price <= 0) {
        $error_message = "Valid purchase price is required!";
    } else {
        $check_sql = "SELECT id FROM fuel_types WHERE name = '$name'";
        $check_result = mysqli_query($conn, $check_sql);
        
        if(mysqli_num_rows($check_result) > 0) {
            $error_message = "Fuel Type already exists!";
        } else {
            $sql = "INSERT INTO fuel_types (name, sale_price, purchase_price, date_time) 
                    VALUES ('$name', '$sale_price', '$purchase_price', '$date_time')";
            if(mysqli_query($conn, $sql)) {
                $success_message = "Fuel Type added successfully! Sale: Rs $sale_price | Purchase: Rs $purchase_price";
            } else {
                $error_message = "Error: " . mysqli_error($conn);
            }
        }
    }
}

// Update Prices
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_prices'])) {
    $fuel_id = mysqli_real_escape_string($conn, $_POST['fuel_id']);
    $sale_price = mysqli_real_escape_string($conn, $_POST['sale_price']);
    $purchase_price = mysqli_real_escape_string($conn, $_POST['purchase_price']);
    
    if(empty($sale_price) || !is_numeric($sale_price) || $sale_price <= 0) {
        $error_message = "Valid sale price is required!";
    } elseif(empty($purchase_price) || !is_numeric($purchase_price) || $purchase_price <= 0) {
        $error_message = "Valid purchase price is required!";
    } else {
        $sql = "UPDATE fuel_types SET sale_price = '$sale_price', purchase_price = '$purchase_price' WHERE id = '$fuel_id'";
        if(mysqli_query($conn, $sql)) {
            $success_message = "Prices updated successfully!";
        } else {
            $error_message = "Error updating prices: " . mysqli_error($conn);
        }
    }
}

// Delete Fuel Type
if(isset($_GET['delete'])) {
    $delete_id = mysqli_real_escape_string($conn, $_GET['delete']);
    
    // Check if fuel type is used in tanks or purchases
    $check_tanks = "SELECT id FROM tanks WHERE fuel_type_id = '$delete_id'";
    $tanks_result = mysqli_query($conn, $check_tanks);
    
    if(mysqli_num_rows($tanks_result) > 0) {
        $error_message = "Cannot delete! This fuel type is used in tanks.";
    } else {
        $sql = "DELETE FROM fuel_types WHERE id = '$delete_id'";
        if(mysqli_query($conn, $sql)) {
            $success_message = "Fuel Type deleted successfully!";
        } else {
            $error_message = "Error deleting: " . mysqli_error($conn);
        }
    }
}

// Get all fuel types
$sql = "SELECT * FROM fuel_types ORDER BY id DESC";
$result = mysqli_query($conn, $sql);

// Calculate statistics
$total_fuel_types = mysqli_num_rows($result);
$total_profit = 0;
$avg_sale_price = 0;

// Store all rows for statistics calculation
$all_fuels = [];
$total_purchase = 0;
while($row = mysqli_fetch_assoc($result)) {
    $all_fuels[] = $row;
    $total_profit += ($row['sale_price'] - $row['purchase_price']);
    $total_purchase += $row['purchase_price'];
}

if($total_fuel_types > 0) {
    $total_sale = 0;
    foreach($all_fuels as $fuel) {
        $total_sale += $fuel['sale_price'];
    }
    $avg_sale_price = $total_sale / $total_fuel_types;
}
?>

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

<!-- Main Content - Same as tanks.php layout -->
<div class="fuel-types-container">
    <!-- Page Header -->
    <div class="page-header">
        <div>
            <h2><i class="fas fa-oil-can"></i> Fuel Types Management</h2>
            <p>Manage fuel categories, sale prices and purchase margins</p>
        </div>
        <div class="stats-badge">
            <i class="fas fa-chart-line"></i> <span><?php echo $total_fuel_types; ?></span> Active Types
        </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_fuel_types; ?></h3>
                <p>Fuel Types</p>
                <span class="stat-trend">Total Categories</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-rupee-sign"></i>
            </div>
            <div class="stat-info">
                <h3>Rs <?php echo number_format($avg_sale_price, 2); ?></h3>
                <p>Avg Sale Price</p>
                <span class="stat-trend">Per Liter</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="stat-info">
                <h3>Rs <?php echo number_format($total_profit, 2); ?></h3>
                <p>Total Profit Margin</p>
                <span class="stat-trend">Per Liter (Sale - Purchase)</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; ?>
    
    <!-- Content Grid -->
    <div class="content-grid">
        <!-- Add Fuel Type Form -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-plus-circle"></i>
                <h4>Add New Fuel Type</h4>
            </div>
            <div class="form-card-body">
                <form method="POST" action="" id="addFuelForm">
                    <div class="input-group-custom">
                        <label><i class="fas fa-gas-pump"></i> Fuel Name <span class="required">*</span></label>
                        <input type="text" name="name" class="form-control-modern" required placeholder="e.g., Petrol, Diesel, HOBC">
                        <small class="input-help">Unique fuel type identifier</small>
                    </div>
                    
                    <div class="row-inputs">
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-tag"></i> Sale Price <span class="required">*</span></label>
                                <input type="number" step="0.01" name="sale_price" id="salePriceInput" class="form-control-modern" required placeholder="Sale price per liter">
                            </div>
                        </div>
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-shopping-cart"></i> Purchase Price <span class="required">*</span></label>
                                <input type="number" step="0.01" name="purchase_price" id="purchasePriceInput" class="form-control-modern" required placeholder="Purchase price per liter">
                            </div>
                        </div>
                    </div>
                    
                    <div class="profit-preview">
                        <div class="preview-row">
                            <span><i class="fas fa-chart-line"></i> Your Profit Margin:</span>
                            <strong id="formProfitValue">Rs 0.00</strong>
                        </div>
                    </div>
                    
                    <button type="submit" name="add_fuel_type" class="btn-submit">
                        <i class="fas fa-save"></i> Add Fuel Type
                    </button>
                </form>
            </div>
        </div>
        
        <!-- Fuel Types List -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-list-ul"></i>
                    <h4>Fuel Inventory</h4>
                </div>
                <div class="table-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="tableSearch" class="search-input" placeholder="Search by fuel name...">
                </div>
            </div>
            <div class="table-responsive">
                <table class="modern-table" id="fuelTable">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Fuel Name</th>
                            <th>Sale Price</th>
                            <th>Purchase Price</th>
                            <th>Profit/L</th>
                            <th>Profit %</th>
                            <th>Date Added</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(count($all_fuels) > 0): ?>
                            <?php foreach($all_fuels as $row): 
                                $profit = $row['sale_price'] - $row['purchase_price'];
                                $profit_percent = ($row['purchase_price'] > 0) ? ($profit / $row['purchase_price']) * 100 : 0;
                                $profit_class = $profit > 0 ? 'profit-positive' : ($profit < 0 ? 'profit-negative' : '');
                            ?>
                                <tr>
                                    <td data-label="ID">#<?php echo $row['id']; ?></td>
                                    <td data-label="Fuel Name">
                                        <div class="fuel-name-cell">
                                            <i class="fas fa-oil-can"></i>
                                            <strong><?php echo htmlspecialchars($row['name']); ?></strong>
                                        </div>
                                    </div>
                                    <td data-label="Sale Price">
                                        <span class="price-sale">Rs <?php echo number_format($row['sale_price'], 2); ?></span>
                                    </div>
                                    <td data-label="Purchase Price">
                                        <span class="price-purchase">Rs <?php echo number_format($row['purchase_price'], 2); ?></span>
                                    </div>
                                    <td data-label="Profit/L">
                                        <span class="<?php echo $profit_class; ?>">
                                            <i class="fas <?php echo $profit > 0 ? 'fa-arrow-up' : ($profit < 0 ? 'fa-arrow-down' : 'fa-minus'); ?>"></i>
                                            Rs <?php echo number_format(abs($profit), 2); ?>
                                        </span>
                                    </div>
                                    <td data-label="Profit %">
                                        <span class="<?php echo $profit_class; ?>"><?php echo number_format($profit_percent, 1); ?>%</span>
                                    </div>
                                    <td data-label="Date Added">
                                        <small><?php echo date('d-m-Y', strtotime($row['date_time'])); ?></small>
                                    </div>
                                    <td data-label="Actions">
                                        <div class="action-buttons">
                                            <button class="btn-action btn-edit" 
                                                    data-bs-toggle="modal" 
                                                    data-bs-target="#updatePriceModal" 
                                                    data-id="<?php echo $row['id']; ?>" 
                                                    data-name="<?php echo htmlspecialchars($row['name']); ?>" 
                                                    data-sale-price="<?php echo $row['sale_price']; ?>"
                                                    data-purchase-price="<?php echo $row['purchase_price']; ?>">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <a href="?delete=<?php echo $row['id']; ?>" 
                                               class="btn-action btn-delete" 
                                               onclick="return confirm('Are you sure you want to delete this fuel type?')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </div>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" class="empty-state">
                                    <i class="fas fa-database"></i>
                                    <p>No fuel types found</p>
                                    <small>Click "Add New Fuel Type" to get started</small>
                                 </div>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Update Price Modal -->
<div class="modal fade" id="updatePriceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header-custom">
                <i class="fas fa-edit"></i>
                <div>
                    <h5 class="modal-title">Update Fuel Prices</h5>
                    <p class="mb-0">Modify sale & purchase rate</p>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <input type="hidden" name="fuel_id" id="modal_fuel_id">
                    <div class="fuel-info-badge">
                        <i class="fas fa-gas-pump"></i>
                        <strong id="modal_fuel_name"></strong>
                    </div>
                    
                    <div class="row-inputs">
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-tag"></i> Sale Price (Rs/L)</label>
                                <input type="number" step="0.01" name="sale_price" id="modal_sale_price" class="form-control-modern" required>
                            </div>
                        </div>
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-shopping-cart"></i> Purchase Price (Rs/L)</label>
                                <input type="number" step="0.01" name="purchase_price" id="modal_purchase_price" class="form-control-modern" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="profit-preview-modal">
                        <div class="preview-row">
                            <span>Profit Margin:</span>
                            <strong id="profitPreview">Rs 0.00</strong>
                        </div>
                        <div class="preview-row">
                            <span>Profit Percentage:</span>
                            <strong id="profitPercentPreview">0%</strong>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-cancel" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="update_prices" class="btn-update"><i class="fas fa-save"></i> Update Prices</button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
/* Fuel Types Container - Same as tanks.php */
@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,
.stat-info h3,
.form-card-header h4,
.header-info h4,
.modern-table th {
    font-family: 'Times New Roman', serif;
}

/* Main Container - NO EXTRA SPACING */
.fuel-types-container {
    margin-left: 280px;
    padding: 20px 30px;
    min-height: 100vh;
    width: calc(100% - 280px);
    max-width: 100%;
}

/* 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(3, 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;
}

/* 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: 360px 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;
}

.row-inputs {
    display: flex;
    gap: 15px;
    margin-bottom: 5px;
}

.input-half {
    flex: 1;
}

.profit-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: 12px;
}

.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);
}

/* 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: 12px;
    min-width: 900px;
}

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

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

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

.fuel-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.fuel-name-cell i {
    font-size: 14px;
    color: #A04657;
}

.price-sale {
    color: #28a745;
    font-weight: 700;
}

.price-purchase {
    color: #A04657;
    font-weight: 600;
}

.profit-positive {
    background: #e8f5e9;
    color: #2e7d32;
    border-radius: 20px;
    padding: 3px 10px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-weight: 600;
    font-size: 11px;
}

.profit-negative {
    background: #ffebee;
    color: #c62828;
    border-radius: 20px;
    padding: 3px 10px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-weight: 600;
    font-size: 11px;
}

/* Action Buttons */
.action-buttons {
    display: flex;
    gap: 6px;
}

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

.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;
}

/* Modal Styles */
.modal-content {
    border-radius: 14px;
    border: none;
    overflow: hidden;
}

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

.modal-header-custom i {
    font-size: 20px;
}

.modal-header-custom h5 {
    margin: 0;
    font-size: 16px;
}

.modal-header-custom p {
    margin: 2px 0 0;
    font-size: 11px;
    opacity: 0.8;
}

.modal-header-custom .btn-close {
    filter: brightness(0) invert(1);
}

.modal-body {
    padding: 20px;
}

.fuel-info-badge {
    background: #fef5f7;
    border-radius: 10px;
    padding: 10px;
    margin-bottom: 20px;
    text-align: center;
}

.fuel-info-badge i {
    color: #A04657;
    margin-right: 8px;
}

.profit-preview-modal {
    background: #f8f9fc;
    border-radius: 10px;
    padding: 12px;
    margin-top: 15px;
    border-left: 3px solid #A04657;
}

.modal-footer {
    padding: 15px 20px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.btn-cancel {
    padding: 8px 20px;
    background: #f0f0f0;
    border: none;
    border-radius: 8px;
    font-weight: 600;
    font-size: 12px;
    cursor: pointer;
}

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

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

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

@media (max-width: 992px) {
    .fuel-types-container {
        margin-left: 0;
        padding: 15px;
        width: 100%;
    }
}

@media (max-width: 768px) {
    .fuel-types-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: 12px;
        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;
    }
    .row-inputs {
        flex-direction: column;
        gap: 0;
    }
    .form-card-body {
        padding: 15px;
    }
}

@media print {
    .sidebar, .action-buttons, .table-search, .btn-delete, .btn-edit, .modal {
        display: none !important;
    }
    .fuel-types-container {
        margin-left: 0 !important;
        padding: 0 !important;
        width: 100% !important;
    }
    .page-header {
        background: #A04657 !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
}

/* 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 src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Live profit preview in form
    const salePriceInput = document.querySelector('#salePriceInput');
    const purchasePriceInput = document.querySelector('#purchasePriceInput');
    const formProfitValue = document.getElementById('formProfitValue');

    function updateFormProfit() {
        const salePrice = parseFloat(salePriceInput?.value) || 0;
        const purchasePrice = parseFloat(purchasePriceInput?.value) || 0;
        const profit = salePrice - purchasePrice;
        if(formProfitValue) {
            formProfitValue.innerHTML = 'Rs ' + profit.toFixed(2);
            formProfitValue.style.color = profit > 0 ? '#28a745' : (profit < 0 ? '#dc3545' : '#666');
        }
    }

    if(salePriceInput) salePriceInput.addEventListener('input', updateFormProfit);
    if(purchasePriceInput) purchasePriceInput.addEventListener('input', updateFormProfit);

    // Table search functionality
    const searchInput = document.getElementById('tableSearch');
    if(searchInput) {
        searchInput.addEventListener('keyup', function() {
            let searchValue = this.value.toLowerCase();
            let table = document.getElementById('fuelTable');
            let rows = table.getElementsByTagName('tr');
            
            for (let i = 1; i < rows.length; i++) {
                let row = rows[i];
                let text = row.textContent.toLowerCase();
                if (text.includes(searchValue)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            }
        });
    }

    // Modal data passing
    const updatePriceModal = document.getElementById('updatePriceModal');
    if (updatePriceModal) {
        updatePriceModal.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;
            const fuelId = button.getAttribute('data-id');
            const fuelName = button.getAttribute('data-name');
            const salePrice = button.getAttribute('data-sale-price');
            const purchasePrice = button.getAttribute('data-purchase-price');
            
            document.getElementById('modal_fuel_id').value = fuelId;
            document.getElementById('modal_fuel_name').innerHTML = fuelName;
            document.getElementById('modal_sale_price').value = salePrice;
            document.getElementById('modal_purchase_price').value = purchasePrice;
            
            updateProfitPreview();
        });
    }

    function updateProfitPreview() {
        const salePrice = parseFloat(document.getElementById('modal_sale_price')?.value) || 0;
        const purchasePrice = parseFloat(document.getElementById('modal_purchase_price')?.value) || 0;
        const profit = salePrice - purchasePrice;
        const profitPercent = purchasePrice > 0 ? (profit / purchasePrice) * 100 : 0;
        
        const profitPreview = document.getElementById('profitPreview');
        const profitPercentPreview = document.getElementById('profitPercentPreview');
        
        if(profitPreview) profitPreview.innerHTML = 'Rs ' + profit.toFixed(2);
        if(profitPercentPreview) profitPercentPreview.innerHTML = profitPercent.toFixed(1) + '%';
        
        if (profit > 0) {
            if(profitPreview) profitPreview.style.color = '#28a745';
            if(profitPercentPreview) profitPercentPreview.style.color = '#28a745';
        } else if (profit < 0) {
            if(profitPreview) profitPreview.style.color = '#dc3545';
            if(profitPercentPreview) profitPercentPreview.style.color = '#dc3545';
        } else {
            if(profitPreview) profitPreview.style.color = '#666';
            if(profitPercentPreview) profitPercentPreview.style.color = '#666';
        }
    }

    const modalSalePrice = document.getElementById('modal_sale_price');
    const modalPurchasePrice = document.getElementById('modal_purchase_price');
    
    if(modalSalePrice) modalSalePrice.addEventListener('input', updateProfitPreview);
    if(modalPurchasePrice) modalPurchasePrice.addEventListener('input', updateProfitPreview);
</script>

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