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

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

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

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

// Add calibration entry
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_calibration'])) {
    $fuel_type_id = mysqli_real_escape_string($conn, $_POST['fuel_type_id']);
    $dip_meter = mysqli_real_escape_string($conn, $_POST['dip_meter']);
    $volume_liters = mysqli_real_escape_string($conn, $_POST['volume_liters']);
    
    if(empty($fuel_type_id) || empty($dip_meter)) {
        $error_message = "Fuel Type and Dip Height are required fields!";
    } else {
        // If volume_liters is empty, set to 0
        if(empty($volume_liters)) {
            $volume_liters = 0;
        }
        
        $check_sql = "SELECT id FROM tank_calibration WHERE fuel_type_id = '$fuel_type_id' AND dip_meter = '$dip_meter'";
        $check_result = mysqli_query($conn, $check_sql);
        
        if(mysqli_num_rows($check_result) > 0) {
            $update_sql = "UPDATE tank_calibration SET volume_liters = '$volume_liters' WHERE fuel_type_id = '$fuel_type_id' AND dip_meter = '$dip_meter'";
            if(mysqli_query($conn, $update_sql)) {
                $success_message = "Calibration entry updated successfully!";
            } else {
                $error_message = "Error: " . mysqli_error($conn);
            }
        } else {
            $insert_sql = "INSERT INTO tank_calibration (fuel_type_id, dip_meter, volume_liters) VALUES ('$fuel_type_id', '$dip_meter', '$volume_liters')";
            if(mysqli_query($conn, $insert_sql)) {
                $success_message = "Calibration entry added successfully!";
            } else {
                $error_message = "Error: " . mysqli_error($conn);
            }
        }
    }
}

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

// Get calibration data with fuel type info
$calibration_sql = "SELECT c.*, f.name as fuel_name
                    FROM tank_calibration c
                    LEFT JOIN fuel_types f ON c.fuel_type_id = f.id
                    ORDER BY c.fuel_type_id, c.dip_meter";
$calibration_result = mysqli_query($conn, $calibration_sql);
?>

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

<div class="calibration-container">
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-chart-line"></i> Calibration Data Management</h2>
            <p>Manage dip-to-volume calibration charts for fuel types</p>
        </div>
    </div>

    <?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="row g-4">
        <!-- Add Calibration Form -->
        <div class="col-md-4">
            <div class="form-card">
                <div class="form-card-header">
                    <i class="fas fa-plus-circle"></i>
                    <h4>Add/Update Calibration Data</h4>
                </div>
                <div class="form-card-body">
                    <form method="POST" id="calibrationForm" novalidate>
                        <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>
                                <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>
                            <small class="input-help">Select fuel type for calibration</small>
                        </div>
                        
                        <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., 1.250">
                            <small>Physical dip measurement in meters</small>
                        </div>
                        
                        <div class="input-group-custom">
                            <label><i class="fas fa-chart-line"></i> Volume (Liters) <span class="optional">(Optional)</span></label>
                            <input type="number" step="any" name="volume_liters" id="volume_liters" class="form-control-modern" placeholder="e.g., 8488.02 (leave empty if not available)">
                            <small>Corresponding volume in liters from dip chart (optional)</small>
                        </div>
                        
                        <button type="submit" name="add_calibration" class="btn-submit">
                            <i class="fas fa-save"></i> Save Calibration Data
                        </button>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-md-8">
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-list"></i>
                        <h4>Calibration Data</h4>
                    </div>
                    <div class="table-search">
                        <select id="fuelFilter" class="search-input" style="width: auto;" onchange="filterTable()">
                            <option value="">All Fuel Types</option>
                            <?php 
                            mysqli_data_seek($fuel_types_result, 0);
                            while($fuel = mysqli_fetch_assoc($fuel_types_result)): 
                            ?>
                                <option value="<?php echo htmlspecialchars($fuel['name']); ?>"><?php echo htmlspecialchars($fuel['name']); ?></option>
                            <?php endwhile; ?>
                        </select>
                        <input type="text" id="searchInput" placeholder="Search fuel type..." class="search-input" onkeyup="filterTable()">
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="modern-table" id="calibrationTable">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Fuel Type</th>
                                    <th>Dip (Meters)</th>
                                    <th>Volume (Liters)</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(mysqli_num_rows($calibration_result) > 0): ?>
                                    <?php while($row = mysqli_fetch_assoc($calibration_result)): ?>
                                        <tr data-fuel="<?php echo htmlspecialchars($row['fuel_name']); ?>">
                                            <td data-label="ID"><?php echo $row['id']; ?></td>
                                            <td data-label="Fuel Type">
                                                <span class="fuel-badge">
                                                    <i class="fas fa-oil-can"></i>
                                                    <?php echo htmlspecialchars($row['fuel_name']); ?>
                                                </span>
                                             </div>
                                            <td data-label="Dip (Meters)"><?php echo number_format($row['dip_meter'], 4); ?> m</div>
                                            <td data-label="Volume (Liters)">
                                                <?php if($row['volume_liters'] > 0): ?>
                                                    <?php echo number_format($row['volume_liters'], 2); ?> L
                                                <?php else: ?>
                                                    <span class="text-muted">-- Not set --</span>
                                                <?php endif; ?>
                                             </div>
                                            <td data-label="Actions">
                                                <a href="?delete=<?php echo $row['id']; ?>" class="btn-delete-small" onclick="return confirm('Delete this calibration entry?')">
                                                    <i class="fas fa-trash"></i> Delete
                                                </a>
                                             </div>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="5" class="empty-state">
                                            <i class="fas fa-chart-line"></i>
                                            <p>No calibration data found</p>
                                            <small>Add calibration data using the form</small>
                                         </div>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.calibration-container { padding: 0; }

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 16px;
    padding: 20px 25px;
    margin-bottom: 25px;
    color: #fff;
}
.page-header h2 { 
    color: #fff; 
    margin: 0 0 5px 0; 
    font-size: 22px; 
    font-weight: 600;
}
.page-header p { 
    color: rgba(255,255,255,0.9); 
    margin: 0; 
    font-size: 12px; 
}

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    border: 1px solid #eee;
}
.form-card-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    padding: 14px 20px;
    color: #fff;
    display: flex;
    align-items: center;
    gap: 8px;
}
.form-card-header i { font-size: 18px; }
.form-card-header h4 { 
    margin: 0; 
    font-size: 16px; 
    font-weight: 600;
    color: #fff;
}
.form-card-body { padding: 20px; }

.input-group-custom { margin-bottom: 16px; }
.input-group-custom label { 
    display: block; 
    margin-bottom: 6px; 
    font-weight: 600; 
    font-size: 12px; 
    color: #333;
}
.input-group-custom label i { color: #A04657; margin-right: 5px; width: 16px; }
.required { color: #dc3545; font-size: 11px; }
.optional { color: #6c757d; font-size: 10px; font-weight: normal; }

.input-help {
    display: block;
    font-size: 10px;
    color: #999;
    margin-top: 4px;
}
.form-control-modern {
    width: 100%;
    padding: 10px 14px;
    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);
}
.btn-submit {
    width: 100%;
    padding: 12px;
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s;
    margin-top: 5px;
}
.btn-submit:hover { 
    transform: translateY(-1px); 
    box-shadow: 0 4px 12px rgba(160,70,87,0.3);
}

/* Info Card */
.info-card {
    background: #f8f9fc;
    border-radius: 14px;
    padding: 16px;
    border: 1px solid #e8e8e8;
}
.info-card-header { 
    display: flex; 
    align-items: center; 
    gap: 8px; 
    margin-bottom: 10px;
}
.info-card-header i { color: #A04657; font-size: 18px; }
.info-card-header h5 { margin: 0; font-size: 14px; font-weight: 600; }
.info-card-body p { 
    font-size: 12px; 
    color: #555; 
    margin-bottom: 8px; 
    line-height: 1.4;
}
.info-card-body hr { margin: 8px 0; border-color: #e0e0e0; }

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    border: 1px solid #eee;
}
.table-card-header {
    padding: 14px 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
}
.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 { display: flex; gap: 10px; flex-wrap: wrap; }
.search-input {
    padding: 8px 14px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    font-size: 12px;
    transition: all 0.2s;
}
.search-input:focus { border-color: #A04657; outline: none; }

/* Modern Table */
.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
}
.modern-table th {
    padding: 12px 15px;
    background: #f8f9fa;
    font-weight: 700;
    color: #444;
    font-size: 12px;
    text-align: left;
    border-bottom: 2px solid #e8e8e8;
}
.modern-table td {
    padding: 10px 15px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
    font-size: 12px;
}
.modern-table tr:hover { background: #fef8f9; }

.fuel-badge {
    background: rgba(160,70,87,0.1);
    color: #A04657;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 5px;
}
.fuel-badge i { font-size: 11px; }

.text-muted { color: #999; font-style: italic; }

.btn-delete-small {
    background: #fee;
    color: #dc3545;
    padding: 5px 12px;
    border-radius: 6px;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-size: 11px;
    font-weight: 500;
    transition: all 0.2s;
}
.btn-delete-small:hover { background: #dc3545; color: #fff; }

/* Alerts */
.alert-custom {
    padding: 12px 18px;
    border-radius: 12px;
    margin-bottom: 20px;
    font-weight: 500;
    font-size: 13px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.alert-success { 
    background: #e8f5e9; 
    color: #2e7d32; 
    border-left: 3px solid #28a745; 
}
.alert-danger { 
    background: #ffebee; 
    color: #c62828; 
    border-left: 3px solid #dc3545; 
}
.close-alert {
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
    opacity: 0.6;
}
.close-alert:hover { opacity: 1; }

.empty-state {
    text-align: center;
    padding: 40px !important;
}
.empty-state i {
    font-size: 48px;
    color: #A04657;
    opacity: 0.4;
    margin-bottom: 12px;
    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: 768px) {
    .page-header { flex-direction: column; text-align: center; padding: 15px 20px; }
    .page-header h2 { font-size: 18px; }
    .table-card-header { flex-direction: column; align-items: flex-start; }
    .table-search { width: 100%; }
    .search-input { flex: 1; 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: 15px;
        width: 40%;
        text-align: left;
        font-weight: 600;
        font-size: 11px;
        color: #A04657;
    }
    .modern-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #eee;
        border-radius: 10px;
        overflow: hidden;
    }
}
</style>

<script>
// Filter table by fuel type and search
function filterTable() {
    const fuelFilter = document.getElementById('fuelFilter').value.toLowerCase();
    const searchValue = document.getElementById('searchInput').value.toLowerCase();
    const table = document.getElementById('calibrationTable');
    const rows = table.getElementsByTagName('tr');
    
    for(let i = 1; i < rows.length; i++) {
        const row = rows[i];
        const fuel = row.getAttribute('data-fuel')?.toLowerCase() || '';
        
        let showByFuel = true;
        let showBySearch = true;
        
        if(fuelFilter !== '') {
            showByFuel = fuel === fuelFilter;
        }
        if(searchValue !== '') {
            showBySearch = fuel.includes(searchValue);
        }
        
        row.style.display = (showByFuel && showBySearch) ? '' : 'none';
    }
}

// Auto hide alerts after 5 seconds
document.querySelectorAll('.alert-custom').forEach(alert => {
    setTimeout(() => {
        alert.style.opacity = '0';
        setTimeout(() => {
            if(alert && alert.parentElement) alert.remove();
        }, 300);
    }, 5000);
});
</script>

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