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

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

// Create table if not exists
$create_table = "CREATE TABLE IF NOT EXISTS `manual_entries` (
    `id` int NOT NULL AUTO_INCREMENT,
    `entry_date` date NOT NULL,
    `serial_no` varchar(50) DEFAULT NULL,
    `vehicle_no` varchar(50) DEFAULT NULL,
    `hsd_liters` decimal(10,2) DEFAULT '0.00',
    `super_liters` decimal(10,2) DEFAULT '0.00',
    `other_liters` decimal(10,2) DEFAULT '0.00',
    `amount` decimal(12,2) DEFAULT '0.00',
    `hsd_rate` decimal(10,2) DEFAULT NULL,
    `super_rate` decimal(10,2) DEFAULT NULL,
    `other_rate` decimal(10,2) DEFAULT NULL,
    `other_description` varchar(200) DEFAULT NULL,
    `notes` text,
    `created_by` varchar(50) DEFAULT NULL,
    `created_at` datetime NOT NULL,
    PRIMARY KEY (`id`)
)";
mysqli_query($conn, $create_table);

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

// Get rates from fuel_types (default values)
$default_hsd_rate = 415.17;
$default_super_rate = 415.22;
$rate_query = "SELECT name, sale_price FROM fuel_types";
$rate_result = mysqli_query($conn, $rate_query);
if($rate_result) {
    while($rate = mysqli_fetch_assoc($rate_result)) {
        if($rate['name'] == 'Diesel') $default_hsd_rate = $rate['sale_price'];
        if($rate['name'] == 'super') $default_super_rate = $rate['sale_price'];
    }
}

// Get rates from POST or default
$hsd_rate = isset($_POST['hsd_rate']) ? floatval($_POST['hsd_rate']) : $default_hsd_rate;
$super_rate = isset($_POST['super_rate']) ? floatval($_POST['super_rate']) : $default_super_rate;
$other_rate = isset($_POST['other_rate']) ? floatval($_POST['other_rate']) : 0;

// Save multiple entries
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_entries'])) {
    $entry_dates = $_POST['entry_date'];
    $serial_nos = $_POST['serial_no'];
    $vehicle_nos = $_POST['vehicle_no'];
    $hsd_liters_arr = $_POST['hsd_liters'];
    $super_liters_arr = $_POST['super_liters'];
    $other_liters_arr = $_POST['other_liters'];
    $amounts = $_POST['amount'];
    $other_description = mysqli_real_escape_string($conn, $_POST['other_description']);
    $notes = mysqli_real_escape_string($conn, $_POST['notes']);
    $current_user = $_SESSION['username'];
    $current_time = date('Y-m-d H:i:s');
    
    $success_count = 0;
    $error_count = 0;
    
    for($i = 0; $i < count($entry_dates); $i++) {
        if(empty($entry_dates[$i])) continue;
        
        $entry_date = mysqli_real_escape_string($conn, $entry_dates[$i]);
        $serial_no = mysqli_real_escape_string($conn, $serial_nos[$i]);
        $vehicle_no = mysqli_real_escape_string($conn, $vehicle_nos[$i]);
        $hsd_liters = floatval($hsd_liters_arr[$i]);
        $super_liters = floatval($super_liters_arr[$i]);
        $other_liters = floatval($other_liters_arr[$i]);
        $amount = floatval($amounts[$i]);
        
        $insert_sql = "INSERT INTO manual_entries (entry_date, serial_no, vehicle_no, hsd_liters, super_liters, other_liters, amount, hsd_rate, super_rate, other_rate, other_description, notes, created_by, created_at) 
                       VALUES ('$entry_date', '$serial_no', '$vehicle_no', $hsd_liters, $super_liters, $other_liters, $amount, $hsd_rate, $super_rate, $other_rate, '$other_description', '$notes', '$current_user', '$current_time')";
        
        if(mysqli_query($conn, $insert_sql)) {
            $success_count++;
        } else {
            $error_count++;
        }
    }
    
    if($success_count > 0) {
        $success_message = "$success_count entries saved successfully!";
        echo '<script>setTimeout(function(){ window.location.href = "manual_entries_list.php"; }, 1500);</script>';
    } else {
        $error_message = "Error saving entries: " . mysqli_error($conn);
    }
}
?>

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

<div class="manual-entry-container">
    <div class="page-header">
        <div>
            <h2><i class="fas fa-table"></i> Manual Entry - Tabular Format</h2>
            <p>Enter multiple entries at once - like Excel sheet</p>
        </div>
        <div class="stats-badge">
            <i class="fas fa-calculator"></i>
            <span>Entries: <?php echo date('d-m-Y'); ?></span>
        </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="form-card">
        <div class="form-card-header">
            <i class="fas fa-table"></i>
            <h4>Data Entry Sheet</h4>
        </div>
        <div class="form-card-body">
            <form method="POST" action="" id="entryForm">
                <!-- FUEL RATES SECTION - EDITABLE -->
                <div class="rates-section">
                    <div class="rates-header">
                        <i class="fas fa-gas-pump"></i>
                        <h5>Fuel Rates (Rs/Liter)</h5>
                        <small>Edit rates as needed - they will apply to all rows</small>
                    </div>
                    <div class="rates-row">
                        <div class="rate-box">
                            <label><i class="fas fa-oil-can"></i> HSD (Diesel)</label>
                            <input type="number" step="0.01" name="hsd_rate" id="hsd_rate" 
                                   class="rate-input" value="<?php echo $hsd_rate; ?>" 
                                   onchange="updateAllCalculations()" onkeyup="updateAllCalculations()">
                        </div>
                        <div class="rate-box">
                            <label><i class="fas fa-gas-pump"></i> Super (Petrol)</label>
                            <input type="number" step="0.01" name="super_rate" id="super_rate" 
                                   class="rate-input" value="<?php echo $super_rate; ?>" 
                                   onchange="updateAllCalculations()" onkeyup="updateAllCalculations()">
                        </div>
                        <div class="rate-box">
                            <label><i class="fas fa-oil-can"></i> Other (Lube/Etc)</label>
                            <input type="number" step="0.01" name="other_rate" id="other_rate" 
                                   class="rate-input" value="<?php echo $other_rate; ?>" 
                                   onchange="updateAllCalculations()" onkeyup="updateAllCalculations()">
                        </div>
                    </div>
                </div>

                <!-- DATA TABLE -->
                <div class="table-responsive">
                    <table class="data-table" id="dataTable">
                        <thead>
                            <tr>
                                <th width="10%">Date</th>
                                <th width="8%">S/No</th>
                                <th width="15%">Veh No</th>
                                <th width="12%">HSD (L)</th>
                                <th width="12%">Super (L)</th>
                                <th width="12%">Others (L)</th>
                                <th width="12%">Amount (Rs)</th>
                                <th width="5%"></th>
                            </tr>
                        </thead>
                        <tbody id="tableBody">
                            <tr>
                                <td><input type="date" name="entry_date[]" class="form-control-sm" value="<?php echo date('Y-m-d'); ?>"></td>
                                <td><input type="text" name="serial_no[]" class="form-control-sm" placeholder="S/No"></td>
                                <td><input type="text" name="vehicle_no[]" class="form-control-sm" placeholder="Veh No"></td>
                                <td><input type="number" step="0.01" name="hsd_liters[]" class="hsd-input form-control-sm" value="0" onchange="calculateRowAmount(this)"></td>
                                <td><input type="number" step="0.01" name="super_liters[]" class="super-input form-control-sm" value="0" onchange="calculateRowAmount(this)"></td>
                                <td><input type="number" step="0.01" name="other_liters[]" class="other-input form-control-sm" value="0" onchange="calculateRowAmount(this)"></td>
                                <td><input type="text" name="amount[]" class="amount-input form-control-sm" value="0" readonly style="background:#f0f0f0;"></td>
                                <td><button type="button" class="remove-row" onclick="removeRow(this)"><i class="fas fa-trash"></i></button></td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="7">
                                    <button type="button" class="btn-add-row" onclick="addNewRow()">
                                        <i class="fas fa-plus"></i> Add New Row
                                    </button>
                                    <button type="button" class="btn-clear-all" onclick="clearAllRows()">
                                        <i class="fas fa-trash-alt"></i> Clear All
                                    </button>
                                 </div>
                            </tr>
                            <tr class="totals-row">
                                <td colspan="3" class="text-right"><strong>GRAND TOTAL:</strong></td>
                                <td><strong id="total_hsd">0.00</strong> L</div>
                                <td><strong id="total_super">0.00</strong> L</div>
                                <td><strong id="total_other">0.00</strong> L</div>
                                <td><strong id="total_amount">Rs 0.00</strong></div>
                                <td></div>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <!-- OTHER INFO -->
                <div class="other-info">
                    <div class="row-custom">
                        <div class="form-group">
                            <label><i class="fas fa-file-alt"></i> Other Description</label>
                            <input type="text" name="other_description" class="form-control-modern" placeholder="e.g., Engine Oil, Grease, etc.">
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-sticky-note"></i> Notes</label>
                            <input type="text" name="notes" class="form-control-modern" placeholder="Additional notes...">
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" name="save_entries" class="btn-submit">
                        <i class="fas fa-save"></i> Save All Entries
                    </button>
                    <a href="manual_entries_list.php" class="btn-cancel">
                        <i class="fas fa-list"></i> View All Entries
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
@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,
.rates-header h5 {
    font-family: 'Times New Roman', serif;
}

.manual-entry-container {
    padding: 20px 30px;
    width: 100%;
}

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

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

.page-header p {
    margin: 0;
    font-size: 12px;
    opacity: 0.9;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 8px 16px;
    border-radius: 30px;
    font-size: 12px;
}

.form-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    border: 1px solid #eee;
}

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

.form-card-header h4 {
    margin: 0;
    font-size: 16px;
    color: #fff;
}

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

/* Rates Section */
.rates-section {
    background: linear-gradient(135deg, #f8f9fc 0%, #eef2f7 100%);
    border-radius: 12px;
    padding: 15px 20px;
    margin-bottom: 25px;
    border: 1px solid #e0e8f0;
}

.rates-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 1px solid #d0d8e0;
}

.rates-header i {
    font-size: 20px;
    color: #A04657;
}

.rates-header h5 {
    margin: 0;
    font-size: 15px;
    color: #333;
}

.rates-header small {
    margin-left: auto;
    font-size: 10px;
    color: #888;
}

.rates-row {
    display: flex;
    gap: 20px;
}

.rate-box {
    flex: 1;
    text-align: center;
}

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

.rate-input {
    width: 100%;
    padding: 10px 12px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 700;
    text-align: center;
    background: #fff;
    color: #A04657;
}

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

/* Data Table */
.table-responsive {
    overflow-x: auto;
    margin-bottom: 20px;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 900px;
}

.data-table th {
    padding: 12px;
    background: #f8f9fc;
    font-weight: 700;
    color: #555;
    font-size: 12px;
    text-align: center;
    border-bottom: 2px solid #e8e8e8;
}

.data-table td {
    padding: 8px;
    border-bottom: 1px solid #f0f0f0;
    text-align: center;
}

.form-control-sm {
    width: 100%;
    padding: 8px 8px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 12px;
    text-align: center;
}

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

.remove-row {
    background: none;
    border: none;
    color: #dc3545;
    cursor: pointer;
    font-size: 14px;
    padding: 5px;
}

.remove-row:hover {
    color: #bd2130;
}

.btn-add-row, .btn-clear-all {
    padding: 8px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    margin-right: 10px;
}

.btn-add-row {
    background: #28a745;
    color: #fff;
}

.btn-add-row:hover {
    background: #1e7e34;
}

.btn-clear-all {
    background: #ffc107;
    color: #333;
}

.btn-clear-all:hover {
    background: #e0a800;
}

.totals-row td {
    background: #f8f9fa;
    font-weight: bold;
    padding: 12px;
}

.text-right {
    text-align: right;
}

/* Other Info */
.other-info {
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fc;
    border-radius: 12px;
}

.row-custom {
    display: flex;
    gap: 20px;
}

.form-group {
    flex: 1;
}

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

.form-control-modern {
    width: 100%;
    padding: 10px 14px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    font-size: 14px;
    background: #fafafa;
}

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

.form-actions {
    display: flex;
    gap: 15px;
    margin-top: 20px;
}

.btn-submit {
    padding: 12px 28px;
    background: linear-gradient(135deg, #28a745, #1e7e34);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 700;
    font-size: 14px;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(40,167,69,0.3);
}

.btn-cancel {
    padding: 12px 28px;
    background: #6c757d;
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 14px;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

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

.alert-custom {
    padding: 12px 18px;
    border-radius: 12px;
    margin-bottom: 20px;
    font-size: 13px;
}

.alert-success {
    background: #e8f5e9;
    color: #2e7d32;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #ffebee;
    color: #c62828;
    border-left: 4px solid #dc3545;
}

@media (max-width: 768px) {
    .manual-entry-container { padding: 12px; }
    .rates-row { flex-direction: column; gap: 10px; }
    .row-custom { flex-direction: column; gap: 10px; }
    .form-actions { flex-direction: column; }
    .data-table th, .data-table td { font-size: 10px; padding: 4px; }
}

::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 10px; }
::-webkit-scrollbar-thumb { background: #A04657; border-radius: 10px; }
</style>

<script>
function calculateRowAmount(element) {
    const row = element.closest('tr');
    const hsd = parseFloat(row.querySelector('.hsd-input')?.value) || 0;
    const superVal = parseFloat(row.querySelector('.super-input')?.value) || 0;
    const other = parseFloat(row.querySelector('.other-input')?.value) || 0;
    
    const hsdRate = parseFloat(document.getElementById('hsd_rate').value) || 0;
    const superRate = parseFloat(document.getElementById('super_rate').value) || 0;
    const otherRate = parseFloat(document.getElementById('other_rate').value) || 0;
    
    const hsdAmount = hsd * hsdRate;
    const superAmount = superVal * superRate;
    const otherAmount = other * otherRate;
    const totalAmount = hsdAmount + superAmount + otherAmount;
    
    const amountInput = row.querySelector('.amount-input');
    if(amountInput) {
        amountInput.value = totalAmount.toFixed(2);
    }
    
    updateTotals();
}

function updateTotals() {
    let totalHSD = 0;
    let totalSuper = 0;
    let totalOther = 0;
    let totalAmount = 0;
    
    document.querySelectorAll('#tableBody tr').forEach(row => {
        const hsd = parseFloat(row.querySelector('.hsd-input')?.value) || 0;
        const superVal = parseFloat(row.querySelector('.super-input')?.value) || 0;
        const other = parseFloat(row.querySelector('.other-input')?.value) || 0;
        const amount = parseFloat(row.querySelector('.amount-input')?.value) || 0;
        
        totalHSD += hsd;
        totalSuper += superVal;
        totalOther += other;
        totalAmount += amount;
    });
    
    document.getElementById('total_hsd').innerText = totalHSD.toFixed(2);
    document.getElementById('total_super').innerText = totalSuper.toFixed(2);
    document.getElementById('total_other').innerText = totalOther.toFixed(2);
    document.getElementById('total_amount').innerHTML = 'Rs ' + totalAmount.toFixed(2);
}

function updateAllCalculations() {
    document.querySelectorAll('#tableBody tr').forEach(row => {
        const hsdInput = row.querySelector('.hsd-input');
        const superInput = row.querySelector('.super-input');
        const otherInput = row.querySelector('.other-input');
        
        if(hsdInput) calculateRowAmount(hsdInput);
        if(superInput) calculateRowAmount(superInput);
        if(otherInput) calculateRowAmount(otherInput);
    });
}

function addNewRow() {
    const tbody = document.getElementById('tableBody');
    const newRow = document.createElement('tr');
    const today = new Date().toISOString().split('T')[0];
    
    newRow.innerHTML = `
        <td><input type="date" name="entry_date[]" class="form-control-sm" value="${today}"></td>
        <td><input type="text" name="serial_no[]" class="form-control-sm" placeholder="S/No"></td>
        <td><input type="text" name="vehicle_no[]" class="form-control-sm" placeholder="Veh No"></td>
        <td><input type="number" step="0.01" name="hsd_liters[]" class="hsd-input form-control-sm" value="0" onchange="calculateRowAmount(this)"></td>
        <td><input type="number" step="0.01" name="super_liters[]" class="super-input form-control-sm" value="0" onchange="calculateRowAmount(this)"></td>
        <td><input type="number" step="0.01" name="other_liters[]" class="other-input form-control-sm" value="0" onchange="calculateRowAmount(this)"></td>
        <td><input type="text" name="amount[]" class="amount-input form-control-sm" value="0" readonly style="background:#f0f0f0;"></td>
        <td><button type="button" class="remove-row" onclick="removeRow(this)"><i class="fas fa-trash"></i></button></td>
    `;
    tbody.appendChild(newRow);
}

function clearAllRows() {
    if(confirm('Are you sure you want to clear all rows? Only one empty row will remain.')) {
        const tbody = document.getElementById('tableBody');
        tbody.innerHTML = '';
        addNewRow();
        updateTotals();
    }
}

function removeRow(btn) {
    const row = btn.closest('tr');
    if(document.querySelectorAll('#tableBody tr').length > 1) {
        row.remove();
        updateTotals();
    } else {
        alert("At least one row is required!");
    }
}

document.addEventListener('DOMContentLoaded', function() {
    updateTotals();
    
    // Add event listeners to rate inputs
    document.getElementById('hsd_rate')?.addEventListener('input', updateAllCalculations);
    document.getElementById('super_rate')?.addEventListener('input', updateAllCalculations);
    document.getElementById('other_rate')?.addEventListener('input', updateAllCalculations);
});
</script>

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