<?php
/**
 * Enterprise HRM ERP System - DFC (Daily Food Cost) Management
 * Excel-like DFC sheet with all columns and calculations from DFC.xlsx
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

$pageTitle = 'SSA (Staff Strength & Attendance)';
$currentModule = 'dfc';

$siteId = getCurrentSiteId();
$userId = $_SESSION['user_id'];
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');
$selectedDate = isset($_GET['date']) ? $_GET['date'] : '';
$periodId = isset($_GET['period_id']) ? (int)$_GET['period_id'] : 0;

// Validate
if ($selectedMonth < 1 || $selectedMonth > 12) $selectedMonth = (int)date('m');
if ($selectedYear < 2020 || $selectedYear > 2100) $selectedYear = (int)date('Y');
if (!empty($selectedDate) && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $selectedDate)) {
    $selectedDate = '';
}

$errors = [];
$success = false;
$period = null;
$entries = [];

// Master Rates (from settings or defaults)
$cylinderRate = getSetting('DFC_CYLINDER_RATE', 0.00);
$benchmarkPercent = getSetting('DFC_BENCHMARK_PERCENT', 74.00);

// Handle save "To" name
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_to_name'])) {
    try {
        $db = getDB();
        $toName = sanitize($_POST['to_name'] ?? '');
        
        // Create table if not exists
        $db->exec("CREATE TABLE IF NOT EXISTS dfc_to_names (
            id INT AUTO_INCREMENT PRIMARY KEY,
            site_id INT NOT NULL,
            to_name VARCHAR(255) DEFAULT '',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY unique_site (site_id)
        )");
        
        // Insert or update
        $stmt = $db->prepare("INSERT INTO dfc_to_names (site_id, to_name) VALUES (?, ?) 
                              ON DUPLICATE KEY UPDATE to_name = VALUES(to_name), updated_at = CURRENT_TIMESTAMP");
        $stmt->execute([$siteId, $toName]);
        
        echo json_encode(['success' => true, 'message' => 'Name saved successfully']);
        exit;
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit;
    }
}

// Load existing "To" name for this site
$toName = '';
try {
    $db = getDB();
    // Create table if not exists
    $db->exec("CREATE TABLE IF NOT EXISTS dfc_to_names (
        id INT AUTO_INCREMENT PRIMARY KEY,
        site_id INT NOT NULL,
        to_name VARCHAR(255) DEFAULT '',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_site (site_id)
    )");
    
    $stmt = $db->prepare("SELECT to_name FROM dfc_to_names WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $toNameRow = $stmt->fetch();
    if ($toNameRow) {
        $toName = $toNameRow['to_name'];
    }
} catch (Exception $e) {
    // Table might not exist yet, ignore
}

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_dfc'])) {
    try {
        $db = getDB();
        $db->beginTransaction();
        
        $fromDate = $_POST['from_date'] ?? '';
        $toDate = $_POST['to_date'] ?? '';
        $periodName = sanitize($_POST['period_name'] ?? '');
        $cylinderRateInput = (float)($_POST['cylinder_rate'] ?? $cylinderRate);
        $benchmarkPercentInput = (float)($_POST['benchmark_percent'] ?? $benchmarkPercent);
        
        if (empty($fromDate) || empty($toDate)) {
            throw new Exception('From Date and To Date are required.');
        }
        
        $month = (int)date('m', strtotime($fromDate));
        $year = (int)date('Y', strtotime($fromDate));
        
        // Check if editing existing period
        $editPeriodId = isset($_POST['period_id']) ? (int)$_POST['period_id'] : 0;
        
        if ($editPeriodId > 0) {
            // Update existing period
            $stmt = $db->prepare("SELECT period_id FROM dfc_periods WHERE period_id = ? AND site_id = ?");
            $stmt->execute([$editPeriodId, $siteId]);
            $existingPeriod = $stmt->fetch();
            
            if ($existingPeriod) {
                $periodId = $editPeriodId;
                // Update period details
                if (empty($periodName)) {
                    $periodName = 'DFC Period ' . date('d-M-Y', strtotime($fromDate)) . ' to ' . date('d-M-Y', strtotime($toDate));
                }
                $stmt = $db->prepare("UPDATE dfc_periods SET period_name = ?, start_date = ?, end_date = ?, month = ?, year = ?, cylinder_rate = ?, benchmark_percent = ? WHERE period_id = ? AND site_id = ?");
                $stmt->execute([$periodName, $fromDate, $toDate, $month, $year, $cylinderRateInput, $benchmarkPercentInput, $periodId, $siteId]);
                
                // Delete existing entries for this period (will re-insert all)
                $stmt = $db->prepare("DELETE FROM dfc_entries WHERE period_id = ?");
                $stmt->execute([$periodId]);
            } else {
                throw new Exception('Period not found or you do not have permission to edit it.');
            }
        } else {
            // Create new period
            if (empty($periodName)) {
                $periodName = 'DFC Period ' . date('d-M-Y', strtotime($fromDate)) . ' to ' . date('d-M-Y', strtotime($toDate));
            }
            
            $stmt = $db->prepare("INSERT INTO dfc_periods (period_name, start_date, end_date, month, year, cylinder_rate, benchmark_percent, site_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$periodName, $fromDate, $toDate, $month, $year, $cylinderRateInput, $benchmarkPercentInput, $siteId, $userId]);
            $periodId = $db->lastInsertId();
        }
        
        // Save entries
        if (isset($_POST['entries']) && is_array($_POST['entries'])) {
            $srNo = 1;
            foreach ($_POST['entries'] as $row) {
                // Use from_date as default if entry_date is empty
                $entryDate = $row['entry_date'] ?? '';
                if (empty($entryDate)) {
                    $entryDate = $fromDate; // Use period's from_date as default
                }
                
                // Skip rows that have no data at all (no date AND no numeric values)
                $hasData = !empty($row['cash_sale_net']) || !empty($row['catering_btc_regular']) || 
                           !empty($row['catering_btc_extra']) || !empty($row['housekeeping_lumpsum']) ||
                           !empty($row['laundry']) || !empty($row['cash_purchase']) || 
                           !empty($row['catering_cost']) || !empty($row['housekeeping_cost']) ||
                           !empty($row['manpower_days']) || !empty($row['odc_cost']) ||
                           !empty($row['cylinder_quantity']);
                
                if (empty($row['entry_date']) && !$hasData) continue; // Skip truly empty rows
                
                // Get all input values
                $cashSaleNet = (float)($row['cash_sale_net'] ?? 0);
                $cateringBtcRegular = (float)($row['catering_btc_regular'] ?? 0);
                $cateringBtcExtra = (float)($row['catering_btc_extra'] ?? 0);
                $housekeepingLumpsum = (float)($row['housekeeping_lumpsum'] ?? 0);
                $laundry = (float)($row['laundry'] ?? 0);
                $cashPurchase = (float)($row['cash_purchase'] ?? 0);
                $cateringCost = (float)($row['catering_cost'] ?? 0);
                $housekeepingCost = (float)($row['housekeeping_cost'] ?? 0);
                $manpowerDays = (float)($row['manpower_days'] ?? 0);
                $odcCost = (float)($row['odc_cost'] ?? 0);
                $odcCost2 = (float)($row['odc_cost_2'] ?? 0);
                $cylinderQuantity = (float)($row['cylinder_quantity'] ?? 0);
                $additionalCost = (float)($row['additional_cost'] ?? 0);
                
                // Calculate all Excel formulas
                // I = F + G (Total Food Sale - Cash Sale Net + Catering BTC Regular + Extra)
                $totalFoodSale = round($cashSaleNet + $cateringBtcRegular + $cateringBtcExtra, 2);
                
                // L = I + J + K (Total Sale)
                $totalSale = round($totalFoodSale + $housekeepingLumpsum + $laundry, 2);
                
                // O = M + N (Total Food Cost)
                $totalFoodCost = round($cashPurchase + $cateringCost, 2);
                
                // P = (M+N)/I*(100)% (Food Cost %)
                $foodCostPercent = $totalFoodSale > 0 ? round(($totalFoodCost / $totalFoodSale) * 100, 2) : 0;
                
                // R = Q/(F+G) or (J+K)/L*(100)% (Housekeeping Cost %)
                $housekeepingCostPercent = ($cashSaleNet + $cateringBtcRegular + $cateringBtcExtra) > 0 
                    ? round(($housekeepingCost / ($cashSaleNet + $cateringBtcRegular + $cateringBtcExtra)) * 100, 2) 
                    : 0;
                
                // T = 11000/26*S (Manpower Cost)
                $manpowerCost = round((11000 / 26) * $manpowerDays, 2);
                
                // R (Manpower Cost %)
                $manpowerCostPercent = $totalSale > 0 ? round(($manpowerCost / $totalSale) * 100, 2) : 0;
                
                // V = T/L (Manpower Cost Per Sale)
                $manpowerCostPerSale = $totalSale > 0 ? round($manpowerCost / $totalSale, 4) : 0;
                
                // Y = Z*X (Total Cylinder Cost)
                $totalCylinderCost = round($cylinderRateInput * $cylinderQuantity, 2);
                
                // AA = Y/L (Cylinder Cost %)
                $cylinderCostPercent = $totalSale > 0 ? round(($totalCylinderCost / $totalSale) * 100, 2) : 0;
                
                // W = U/L (Cylinder Cost Per Sale) - U is direct cylinder cost if entered
                $cylinderCostDirect = (float)($row['cylinder_cost_direct'] ?? 0);
                $cylinderCostPerSale = $totalSale > 0 ? round(($cylinderCostDirect > 0 ? $cylinderCostDirect : $totalCylinderCost) / $totalSale, 4) : 0;
                
                // AB = N*AF (Expected Food Cost)
                $expectedFoodCost = round($cateringCost * ($benchmarkPercentInput / 100), 2);
                
                // AC = AB-(M+N+Q) (Variation)
                $variationAmount = round($expectedFoodCost - ($cashPurchase + $cateringCost + $additionalCost), 2);
                $variationType = $variationAmount >= 0 ? 'positive' : 'negative';
                
                // AG = O+Q (Total Cost)
                $totalCost = round($totalFoodCost + $additionalCost, 2);
                
                $stmt = $db->prepare("
                    INSERT INTO dfc_entries (
                        period_id, entry_date, cash_sale_net, catering_btc_regular, catering_btc_extra,
                        total_food_sale, housekeeping_lumpsum, laundry, total_sale,
                        cash_purchase, catering_cost, total_food_cost, food_cost_percent,
                        housekeeping_cost, housekeeping_cost_percent, manpower_days, manpower_cost,
                        manpower_cost_percent, manpower_cost_per_sale, odc_cost, odc_cost_2, cylinder_quantity,
                        cylinder_rate, total_cylinder_cost, cylinder_cost_percent, cylinder_cost_per_sale,
                        expected_food_cost, variation_amount, variation_type, additional_cost, total_cost, sr_no
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $periodId, $entryDate, $cashSaleNet, $cateringBtcRegular, $cateringBtcExtra,
                    $totalFoodSale, $housekeepingLumpsum, $laundry, $totalSale,
                    $cashPurchase, $cateringCost, $totalFoodCost, $foodCostPercent,
                    $housekeepingCost, $housekeepingCostPercent, $manpowerDays, $manpowerCost,
                    $manpowerCostPercent, $manpowerCostPerSale, $odcCost, $odcCost2, $cylinderQuantity,
                    $cylinderRateInput, $totalCylinderCost, $cylinderCostPercent, $cylinderCostPerSale,
                    $expectedFoodCost, abs($variationAmount), $variationType, $additionalCost, $totalCost, $srNo++
                ]);
            }
        }
        
        $db->commit();
        $success = true;
        
        if (function_exists('logAudit')) {
            logAudit('CREATE', 'dfc_periods', $periodId, "DFC Period: {$uniquePeriodName}");
        }
        
        $_SESSION['success'] = 'DFC data saved successfully.';
        header('Location: ' . $_SERVER['PHP_SELF'] . '?period_id=' . $periodId . '&month=' . $month . '&year=' . $year);
        exit;
        
    } catch (Exception $e) {
        if (isset($db) && $db->inTransaction()) {
            $db->rollBack();
        }
        $errors[] = $e->getMessage();
        error_log("DFC save error: " . $e->getMessage());
    }
}

// Load data
try {
    $db = getDB();
    
    // Get all periods for selected month/year
    $stmt = $db->prepare("
        SELECT * FROM dfc_periods 
        WHERE site_id = ? AND month = ? AND year = ?
        ORDER BY period_id DESC
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $periods = $stmt->fetchAll();
    
    // Load period and entries if period_id is set
    if ($periodId > 0) {
        $stmt = $db->prepare("SELECT * FROM dfc_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$periodId, $siteId]);
        $period = $stmt->fetch();
        
        if ($period) {
            $cylinderRate = $period['cylinder_rate'];
            $benchmarkPercent = $period['benchmark_percent'];
            
            $stmt = $db->prepare("
                SELECT * FROM dfc_entries 
                WHERE period_id = ? 
                ORDER BY entry_date, sr_no, entry_id
            ");
            $stmt->execute([$periodId]);
            $entries = $stmt->fetchAll();
        }
    }
    
} catch (Exception $e) {
    error_log("DFC list error: " . $e->getMessage());
    $periods = [];
    $entries = [];
}

// If no entries, create empty array for new entry
if (empty($entries)) {
    $entries = [['entry_date' => '', 'sr_no' => 1]];
}

// Get site name
$siteName = 'Corporate';
try {
    $stmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $site = $stmt->fetch();
    if ($site) {
        $siteName = $site['site_name'];
    }
} catch (Exception $e) {
    // Use default
}

include __DIR__ . '/../../includes/header.php';

// Show success/error messages
if (isset($_SESSION['success'])) {
    echo '<div class="alert alert-success" style="background: #d4edda; color: #155724; padding: 12px; margin: 10px 0; border: 1px solid #c3e6cb; border-radius: 4px;">';
    echo htmlspecialchars($_SESSION['success']);
    echo '</div>';
    unset($_SESSION['success']);
}

if (!empty($errors)) {
    echo '<div class="alert alert-danger" style="background: #f8d7da; color: #721c24; padding: 12px; margin: 10px 0; border: 1px solid #f5c6cb; border-radius: 4px;">';
    foreach ($errors as $error) {
        echo htmlspecialchars($error) . '<br>';
    }
    echo '</div>';
}
?>

<style>
/* ========== SSA ENTRY - MODERN UI STYLES ========== */

/* Main Container */
.excel-register {
    font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
    font-size: 12px;
    background: linear-gradient(135deg, #f0f4f8 0%, #d9e2ec 100%);
    padding: 30px;
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
    overflow-x: auto;
    overflow-y: visible;
    border-radius: 16px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
    min-height: 100vh;
}

/* Data Entry Table */
.excel-register table {
    border-collapse: separate;
    border-spacing: 0;
    width: 100%;
    min-width: 3000px;
    background: #fff;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
    border-radius: 12px;
    overflow: hidden;
}

.excel-register th,
.excel-register td {
    border: none;
    border-bottom: 1px solid #e2e8f0;
    border-right: 1px solid #f1f5f9;
    padding: 8px 10px;
    text-align: center;
    white-space: nowrap;
    font-size: 12px;
    transition: all 0.2s ease;
}

.excel-register th:last-child,
.excel-register td:last-child {
    border-right: none;
}

.excel-register th {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%) !important;
    color: #FFF;
    font-weight: 600;
    font-size: 11px;
    text-align: center;
    text-shadow: none;
    letter-spacing: 0.5px;
    text-transform: uppercase;
    padding: 14px 10px;
}

.excel-register .header-blue {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%) !important;
    color: #fff;
    font-weight: 600;
}

.excel-register .header-yellow {
    background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%) !important;
    color: #1e293b;
    font-weight: 600;
}

.excel-register .header-orange {
    background: linear-gradient(135deg, #fb923c 0%, #f97316 100%) !important;
    color: #1e293b;
    font-weight: 600;
}

.excel-register .summary-row {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%) !important;
    font-weight: 700;
    color: #fff;
    border-top: none;
}

.excel-register .calculation-row {
    background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%) !important;
    font-weight: 700;
    color: #1e293b;
    border-top: none;
}

.excel-register .text-left {
    text-align: left;
}

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

/* Input Fields */
.excel-register input[type="text"],
.excel-register input[type="number"],
.excel-register input[type="date"] {
    width: 100%;
    border: 2px solid transparent;
    background: #f8fafc;
    text-align: center;
    font-size: 12px;
    padding: 6px 8px;
    font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.excel-register input[type="text"]:hover,
.excel-register input[type="number"]:hover,
.excel-register input[type="date"]:hover {
    background: #f1f5f9;
    border-color: #cbd5e1;
}

.excel-register input[type="text"]:focus,
.excel-register input[type="number"]:focus,
.excel-register input[type="date"]:focus {
    background: #fffbeb;
    border-color: #2a5298;
    outline: none;
    box-shadow: 0 0 0 3px rgba(42, 82, 152, 0.15);
    transform: scale(1.02);
    transition: all 0.2s ease;
}

/* Calculated Cells */
.excel-register .calculated {
    background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%) !important;
    font-weight: 600;
    text-align: right !important;
    user-select: none;
    cursor: default;
    color: #166534;
}

.excel-register .variation-positive {
    background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%) !important;
    color: #991b1b !important;
    font-weight: 600;
}

.excel-register .variation-negative {
    background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%) !important;
    color: #166534 !important;
    font-weight: 600;
}

/* Row Striping */
.excel-register tbody tr:nth-child(even) td {
    background: #f8fafc;
}

.excel-register tbody tr:nth-child(odd) td {
    background: #ffffff;
}

.excel-register tbody tr:hover td {
    background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%) !important;
    transition: background 0.2s ease;
}

.excel-register tbody tr.total-row:hover td {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%) !important;
    color: #fff !important;
}

/* Action Buttons */
.btn-action {
    padding: 12px 24px;
    margin: 6px;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-action:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

.btn-action:active {
    transform: translateY(-1px);
}

.btn-success { 
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white; 
}

.btn-success:hover {
    box-shadow: 0 8px 25px rgba(16, 185, 129, 0.4);
}

.btn-info { 
    background: linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%);
    color: white; 
}

.btn-info:hover {
    box-shadow: 0 8px 25px rgba(139, 92, 246, 0.4);
}

.btn-primary { 
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    color: white; 
}

.btn-primary:hover {
    box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
}

.btn-danger { 
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white; 
}

.btn-danger:hover {
    box-shadow: 0 8px 25px rgba(239, 68, 68, 0.4);
}

/* Enhanced Input Focus States */
input[type="date"]:focus,
input[type="text"]:focus,
input[type="number"]:focus,
select:focus {
    border-color: #2a5298 !important;
    box-shadow: 0 0 0 3px rgba(42, 82, 152, 0.15) !important;
    outline: none;
    transform: scale(1.02);
    transition: all 0.2s ease;
}

/* Period Form Card */
.period-form {
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    padding: 25px;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    margin-bottom: 25px;
    border-left: 5px solid #2a5298;
}

.period-form label {
    font-weight: 600;
    color: #334155;
    font-size: 13px;
    margin-bottom: 6px;
    display: block;
}

.period-form input,
.period-form select {
    padding: 12px 16px;
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    font-size: 14px;
    width: 100%;
    transition: all 0.3s ease;
}

.period-form input:focus,
.period-form select:focus {
    border-color: #2a5298;
    box-shadow: 0 0 0 3px rgba(42, 82, 152, 0.15);
}

/* Existing Periods Section */
.period-list-section {
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.06);
    margin-bottom: 20px;
}

.period-list-section strong {
    color: #1e293b;
    font-size: 15px;
}

/* Action Bar */
.action-bar {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    padding: 20px;
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    border-radius: 12px;
    margin-top: 20px;
    box-shadow: 0 -4px 15px rgba(0, 0, 0, 0.05);
    position: sticky;
    bottom: 20px;
}
</style>

<div class="excel-register">
    <!-- Header Section - Modern Card Design -->
    <div style="margin-bottom: 25px;">
        <div style="background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%); border-radius: 16px; box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1); padding: 20px 25px; border-left: 5px solid #2a5298;">
            <div style="display: flex; flex-wrap: wrap; gap: 20px; align-items: center;">
                <!-- Site Name -->
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span style="font-weight: 600; font-size: 13px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">🏢 Site</span>
                    <span style="background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%); color: white; padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 600;"><?php echo htmlspecialchars($siteName); ?></span>
                </div>
                
                <!-- Month -->
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span style="font-weight: 600; font-size: 13px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">📅 Month</span>
                    <select id="filter_month" onchange="filterByMonthYear()" style="border: 2px solid #e2e8f0; font-size: 13px; padding: 8px 14px; background: #fff; font-weight: 500; cursor: pointer; color: #1e293b; border-radius: 8px; transition: all 0.3s;">
                        <?php for ($m = 1; $m <= 12; $m++): ?>
                        <option value="<?php echo $m; ?>" <?php echo $m == $selectedMonth ? 'selected' : ''; ?>>
                            <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                        </option>
                        <?php endfor; ?>
                    </select>
                </div>
                
                <!-- Year -->
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span style="font-weight: 600; font-size: 13px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">📆 Year</span>
                    <input type="number" id="filter_year" value="<?php echo $selectedYear; ?>" 
                           min="2020" max="2100" onchange="filterByMonthYear()" 
                           style="width: 90px; border: 2px solid #e2e8f0; font-size: 13px; text-align: center; background: #fff; font-weight: 500; color: #1e293b; padding: 8px; border-radius: 8px;">
                </div>
                
                <!-- Cylinder Rate -->
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span style="font-weight: 600; font-size: 13px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">⛽ Cylinder Rate</span>
                    <div style="position: relative; display: inline-block;">
                        <input type="number" id="master_cylinder_rate" value="<?php echo number_format($cylinderRate, 2, '.', ''); ?>" 
                               step="0.01" style="width: 100px; border: 2px solid #e2e8f0; font-size: 13px; text-align: center; background: #fff; font-weight: 500; color: #1e293b; padding: 8px; padding-right: 35px; border-radius: 8px;">
                        <button type="button" onclick="saveCylinderRate()" title="Save Cylinder Rate" 
                                style="position: absolute; right: 5px; top: 50%; transform: translateY(-50%); background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border: none; border-radius: 6px; padding: 6px 8px; cursor: pointer; font-size: 11px; line-height: 1; transition: all 0.3s; box-shadow: 0 2px 6px rgba(16, 185, 129, 0.3);">
                            💾
                        </button>
                    </div>
                </div>
                
                <!-- Benchmark % -->
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span style="font-weight: 600; font-size: 13px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">📊 Benchmark %</span>
                    <input type="number" id="master_benchmark_percent" value="<?php echo number_format($benchmarkPercent, 2, '.', ''); ?>" 
                           step="0.01" style="width: 90px; border: 2px solid #e2e8f0; font-size: 13px; text-align: center; background: #fff; font-weight: 500; color: #1e293b; padding: 8px; border-radius: 8px;">
                </div>
                
                <!-- View Report Button -->
                <a href="<?php echo BASE_URL; ?>/modules/dfc/report.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                   style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 12px 24px; text-decoration: none; border-radius: 10px; font-size: 13px; font-weight: 600; box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3); transition: all 0.3s ease; display: inline-flex; align-items: center; gap: 8px; margin-left: auto;">
                    📊 View Report
                </a>
                
                <!-- To Name Field -->
                <div style="display: flex; align-items: center; gap: 8px; margin-left: 15px;">
                    <span style="font-weight: 600; font-size: 13px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">📝 To</span>
                    <div style="position: relative; display: inline-flex; align-items: center;">
                        <input type="text" id="to_name_input" value="<?php echo htmlspecialchars($toName); ?>" 
                               placeholder="Enter name..." 
                               style="width: 140px; padding: 8px 35px 8px 12px; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 13px; transition: all 0.3s ease;">
                        <button type="button" onclick="saveToName()" title="Save Name" 
                                style="position: absolute; right: 5px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border: none; border-radius: 6px; padding: 5px 7px; cursor: pointer; font-size: 11px; line-height: 1; transition: all 0.3s; box-shadow: 0 2px 6px rgba(16, 185, 129, 0.3);">
                            ✓
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Period List - Enhanced -->
    <?php if (!empty($periods)): ?>
    <div style="margin-bottom: 25px; padding: 20px; background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%); border-radius: 16px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08); border-left: 5px solid #8b5cf6;">
        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
            <span style="font-size: 20px;">📋</span>
            <strong style="color: #1e293b; font-size: 16px; font-weight: 600;">Existing Periods</strong>
            <span style="background: linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%); color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600;"><?php echo count($periods); ?></span>
        </div>
        <div class="period-list" style="display: flex; flex-wrap: wrap; gap: 10px;">
        <?php foreach ($periods as $p): ?>
        <a href="?period_id=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
           style="margin: 0; padding: 10px 20px; font-size: 13px; background: linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%); color: white; text-decoration: none; border-radius: 10px; font-weight: 500; transition: all 0.3s ease; box-shadow: 0 3px 10px rgba(139, 92, 246, 0.3); display: inline-flex; align-items: center; gap: 8px;">
            <span>📄</span>
            <?php echo strtoupper(htmlspecialchars($p['period_name'] ?: date('d M', strtotime($p['start_date'])) . ' - ' . date('d M', strtotime($p['end_date'])))); ?>
        </a>
        <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Period Form -->
    <form method="POST" id="dfcForm">
        <input type="hidden" name="save_dfc" value="1">
        <?php if ($period && $periodId > 0): ?>
        <input type="hidden" name="period_id" value="<?php echo $periodId; ?>">
        <?php endif; ?>
        
        <div class="period-form" style="background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%); padding: 20px; margin-bottom: 20px; border: 2px solid #e0e0e0; border-radius: 8px; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);">
            <div style="display: inline-block; margin-right: 15px; vertical-align: top;">
                <label style="display: block; font-weight: 600; color: #2d3748; margin-bottom: 5px; font-size: 12px;">From Date:</label>
                <input type="date" name="from_date" id="from_date" 
                       value="<?php echo $period ? htmlspecialchars($period['start_date']) : ''; ?>" required
                       style="padding: 8px 12px; border: 2px solid #e0e0e0; border-radius: 6px; font-size: 13px; transition: all 0.3s ease; width: 160px;">
        </div>
            
            <div style="display: inline-block; margin-right: 15px; vertical-align: top;">
                <label style="display: block; font-weight: 600; color: #2d3748; margin-bottom: 5px; font-size: 12px;">To Date:</label>
                <input type="date" name="to_date" id="to_date" 
                       value="<?php echo $period ? htmlspecialchars($period['end_date']) : ''; ?>" required
                       style="padding: 8px 12px; border: 2px solid #e0e0e0; border-radius: 6px; font-size: 13px; transition: all 0.3s ease; width: 160px;">
        </div>
            
            <div style="display: inline-block; margin-right: 15px; vertical-align: top;">
                <label style="display: block; font-weight: 600; color: #2d3748; margin-bottom: 5px; font-size: 12px;">Period Name:</label>
                <input type="text" name="period_name" 
                       value="<?php echo $period ? htmlspecialchars($period['period_name']) : ''; ?>" 
                       placeholder="e.g., January 2026"
                       style="padding: 8px 12px; border: 2px solid #e0e0e0; border-radius: 6px; font-size: 13px; transition: all 0.3s ease; width: 180px;">
        </div>
            
            <div style="display: inline-block; margin-right: 15px; vertical-align: top; position: relative;">
                <label style="display: block; font-weight: 600; color: #2d3748; margin-bottom: 5px; font-size: 12px;">Cylinder Rate:</label>
                <div style="position: relative; display: inline-block;">
                    <input type="number" step="0.01" name="cylinder_rate" id="cylinder_rate" 
                           value="<?php echo $period ? number_format($period['cylinder_rate'], 2, '.', '') : number_format($cylinderRate, 2, '.', ''); ?>" 
                           style="width: 140px; padding: 8px 40px 8px 12px; border: 2px solid #e0e0e0; border-radius: 6px; font-size: 13px; transition: all 0.3s ease;">
                    <button type="button" onclick="saveCylinderRateSetting()" title="Save Cylinder Rate Setting" 
                            style="position: absolute; right: 4px; top: 50%; transform: translateY(-50%); background: #006699; color: white; border: none; border-radius: 4px; padding: 4px 8px; cursor: pointer; font-size: 12px; line-height: 1; transition: all 0.3s; height: 28px; width: 32px; display: flex; align-items: center; justify-content: center;">
                        💾
                    </button>
                </div>
        </div>
            
            <div style="display: inline-block; margin-right: 15px; vertical-align: top;">
                <label style="display: block; font-weight: 600; color: #2d3748; margin-bottom: 5px; font-size: 12px;">Benchmark %:</label>
                <input type="number" step="0.01" name="benchmark_percent" id="benchmark_percent" 
                       value="<?php echo $period ? number_format($period['benchmark_percent'], 2, '.', '') : number_format($benchmarkPercent, 2, '.', ''); ?>" 
                       style="width: 140px; padding: 8px 12px; border: 2px solid #e0e0e0; border-radius: 6px; font-size: 13px; transition: all 0.3s ease;">
        </div>
    </div>
    
        <!-- Main DFC Table (Excel Structure) -->
        <div style="overflow-x: auto; width: 100%; max-width: 100%; box-sizing: border-box; margin-top: 20px;">
            <table id="dfcTable" style="width: 100%; max-width: 100%; box-sizing: border-box;">
                <thead>
                    <!-- Row 4: Main Headers -->
                    <tr>
                        <th rowspan="2" style="width: 80px;">DATE</th>
                        <th rowspan="2" style="width: 100px;">CASH SALE NET</th>
                        <th colspan="2" class="header-blue">CATERING BTC SALE DETAILS</th>
                        <th rowspan="2" style="width: 120px;">TOTAL FOOD SALE (CASH + CREDIT)</th>
                        <th rowspan="2" style="width: 120px;">HOUSEKEEPING / LUMPSUM</th>
                        <th rowspan="2" style="width: 100px;">LAUNDRY</th>
                        <th rowspan="2" style="width: 120px;">TOTAL SALE</th>
                        <th rowspan="2" style="width: 100px;">CASH PURCHASE</th>
                        <th rowspan="2" style="width: 100px;">CATERING COST</th>
                        <th rowspan="2" style="width: 120px;">TOTAL FOOD COST</th>
                        <th rowspan="2" style="width: 100px;">FOOD COST %</th>
                        <th rowspan="2" style="width: 120px;">HOUSE KEEPING COST</th>
                        <th rowspan="2" style="width: 120px;">HOUSE KEEPING COST %</th>
                        <th colspan="2" class="header-yellow">MANPOWER</th>
                        <th rowspan="2" style="width: 100px;">ODC</th>
                        <th rowspan="2" style="width: 120px;">MANPOWER COST</th>
                        <th rowspan="2" style="width: 100px;">ODC COST</th>
                        <th rowspan="2" style="width: 100px;">INPUT CYLINDER QUANTITY</th>
                        <th rowspan="2" style="width: 100px;">PER CYLINDER RATE</th>
                        <th rowspan="2" style="width: 120px;">TOTAL CYLINDER AMOUNT</th>
                        <th rowspan="2" style="width: 100px;">FUEL COST %</th>
                        <th rowspan="2" style="width: 120px;">VARIATION AMOUNT</th>
                        <th rowspan="2" style="width: 80px;">Action</th>
                    </tr>
                    <!-- Row 5: Sub Headers -->
                    <tr>
                        <th class="header-blue" style="width: 100px;">Regular BTC Sale</th>
                        <th class="header-blue" style="width: 100px;">Extra BTC Sale</th>
                        <th class="header-yellow" style="width: 100px;">NO OF MANPOWER</th>
                        <th class="header-yellow" style="width: 120px;">MANPOWER COST</th>
                    </tr>
                </thead>
                <tbody id="entriesBody">
                    <?php 
                    $rowIndex = 0;
                    foreach ($entries as $entry): 
                    ?>
                    <tr class="data-row" data-row-index="<?php echo $rowIndex; ?>">
                        <td>
                            <input type="date" name="entries[<?php echo $rowIndex; ?>][entry_date]" 
                                   value="<?php echo htmlspecialchars($entry['entry_date'] ?? ''); ?>" 
                                   class="entry-date" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][cash_sale_net]" 
                                   value="<?php echo number_format($entry['cash_sale_net'] ?? 0, 2, '.', ''); ?>" 
                                   class="cash-sale-net text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][catering_btc_regular]" 
                                   value="<?php echo number_format($entry['catering_btc_regular'] ?? 0, 2, '.', ''); ?>" 
                                   class="catering-btc-regular text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][catering_btc_extra]" 
                                   value="<?php echo number_format($entry['catering_btc_extra'] ?? 0, 2, '.', ''); ?>" 
                                   class="catering-btc-extra text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td class="calculated total-food-sale text-right">
                            <?php echo number_format($entry['total_food_sale'] ?? 0, 2); ?>
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][housekeeping_lumpsum]" 
                                   value="<?php echo number_format($entry['housekeeping_lumpsum'] ?? 0, 2, '.', ''); ?>" 
                                   class="housekeeping-lumpsum text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][laundry]" 
                                   value="<?php echo number_format($entry['laundry'] ?? 0, 2, '.', ''); ?>" 
                                   class="laundry text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td class="calculated total-sale text-right">
                            <?php echo number_format($entry['total_sale'] ?? 0, 2); ?>
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][cash_purchase]" 
                                   value="<?php echo number_format($entry['cash_purchase'] ?? 0, 2, '.', ''); ?>" 
                                   class="cash-purchase text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][catering_cost]" 
                                   value="<?php echo number_format($entry['catering_cost'] ?? 0, 2, '.', ''); ?>" 
                                   class="catering-cost text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td class="calculated total-food-cost text-right">
                            <?php echo number_format($entry['total_food_cost'] ?? 0, 2); ?>
                        </td>
                        <td class="calculated food-cost-percent text-right">
                            <?php echo number_format($entry['food_cost_percent'] ?? 0, 2); ?>%
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][housekeeping_cost]" 
                                   value="<?php echo number_format($entry['housekeeping_cost'] ?? 0, 2, '.', ''); ?>" 
                                   class="housekeeping-cost text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td class="calculated housekeeping-cost-percent text-right">
                            <?php echo number_format($entry['housekeeping_cost_percent'] ?? 0, 2); ?>%
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][manpower_days]" 
                                   value="<?php echo number_format($entry['manpower_days'] ?? 0, 2, '.', ''); ?>" 
                                   class="manpower-days text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td class="calculated manpower-cost text-right">
                            <?php echo number_format($entry['manpower_cost'] ?? 0, 2); ?>
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][odc_cost]" 
                                   value="<?php echo number_format($entry['odc_cost'] ?? 0, 2, '.', ''); ?>" 
                                   class="odc-cost text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td class="calculated manpower-cost-after-odc text-right">
                            <?php echo number_format($entry['manpower_cost'] ?? 0, 2); ?>
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][odc_cost_2]" 
                                   value="<?php echo number_format($entry['odc_cost_2'] ?? 0, 2, '.', ''); ?>" 
                                   class="odc-cost-2 text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][cylinder_quantity]" 
                                   value="<?php echo number_format($entry['cylinder_quantity'] ?? 0, 2, '.', ''); ?>" 
                                   class="cylinder-quantity text-right" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)"
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)"
                                   style="width: 100%; border: none; padding: 4px;">
                        </td>
                        <td class="calculated cylinder-rate text-right">
                            <?php echo number_format($entry['cylinder_rate'] ?? $cylinderRate, 2); ?>
                        </td>
                        <td class="calculated total-cylinder-cost text-right">
                            <?php echo number_format($entry['total_cylinder_cost'] ?? 0, 2); ?>
                        </td>
                        <td class="calculated cylinder-cost-percent text-right">
                            <?php echo number_format($entry['cylinder_cost_percent'] ?? 0, 2); ?>%
                            <input type="hidden" name="entries[<?php echo $rowIndex; ?>][additional_cost]" 
                                   value="<?php echo number_format($entry['additional_cost'] ?? 0, 2, '.', ''); ?>" 
                                   class="additional-cost">
                        </td>
                        <td class="calculated variation-amount text-right <?php echo ($entry['variation_type'] ?? 'positive') === 'positive' ? 'variation-positive' : 'variation-negative'; ?>">
                            <?php echo ($entry['variation_type'] ?? 'positive') === 'positive' ? '+' : '-'; ?><?php echo number_format($entry['variation_amount'] ?? 0, 2); ?>
                        </td>
                        <td>
                            <button type="button" class="btn-action btn-success" onclick="insertRowAfter(this)" title="Insert Row After" style="padding: 4px 8px; font-size: 12px; margin: 2px;">+</button>
                            <button type="button" class="btn-action btn-danger" onclick="removeRow(this)" title="Remove Row" style="padding: 4px 8px; font-size: 12px; margin: 2px;">×</button>
                        </td>
                    </tr>
                    <?php $rowIndex++; ?>
                    <?php endforeach; ?>
                </tbody>
                <!-- Calculation/TOTAL Row -->
                <tfoot>
                    <tr class="calculation-row summary-row">
                        <td><strong>TOTAL:</strong></td>
                        <td class="calculated text-right" id="calc-cash-sale-net">0.00</td>
                        <td class="calculated text-right" id="calc-catering-btc-regular">0.00</td>
                        <td class="calculated text-right" id="calc-catering-btc-extra">0.00</td>
                        <td class="calculated text-right" id="calc-total-food-sale">0.00</td>
                        <td class="calculated text-right" id="calc-housekeeping-lumpsum">0.00</td>
                        <td class="calculated text-right" id="calc-laundry">0.00</td>
                        <td class="calculated text-right" id="calc-total-sale">0.00</td>
                        <td class="calculated text-right" id="calc-cash-purchase">0.00</td>
                        <td class="calculated text-right" id="calc-catering-cost">0.00</td>
                        <td class="calculated text-right" id="calc-total-food-cost">0.00</td>
                        <td class="calculated text-right" id="calc-food-cost-percent">0.00%</td>
                        <td class="calculated text-right" id="calc-housekeeping-cost">0.00</td>
                        <td class="calculated text-right" id="calc-housekeeping-cost-percent">0.00%</td>
                        <td class="calculated text-right" id="calc-manpower-days">0.00</td>
                        <td class="calculated text-right" id="calc-manpower-cost">0.00</td>
                        <td class="calculated text-right" id="calc-odc-cost">0.00</td>
                        <td class="calculated text-right" id="calc-manpower-cost-after-odc">0.00</td>
                        <td class="calculated text-right" id="calc-odc-cost-2">0.00</td>
                        <td class="calculated text-right" id="calc-cylinder-quantity">0.00</td>
                        <td class="calculated text-right" id="calc-cylinder-rate">0.00</td>
                        <td class="calculated text-right" id="calc-total-cylinder-cost">0.00</td>
                        <td class="calculated text-right" id="calc-cylinder-cost-percent">0.00%</td>
                        <td class="calculated text-right" id="calc-variation-amount">0.00</td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
        
        <!-- Action Buttons -->
        <div style="margin: 25px 0; text-align: center; padding: 20px; background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%); border: 2px solid #e0e0e0; border-radius: 8px; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);">
            <button type="button" class="btn-action btn-success" onclick="addRow()">+ Add Row</button>
            <button type="button" class="btn-action btn-info" onclick="recalculateAllRows()" style="background: linear-gradient(135deg, #f6d365 0%, #fda085 100%); color: #000; font-weight: 600;">🔄 Calculate All</button>
            <button type="submit" class="btn-action btn-primary">💾 Save Data</button>
            <a href="<?php echo BASE_URL; ?>/modules/dfc/report.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="btn-action btn-info" 
               style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; text-decoration: none; padding: 10px 20px; display: inline-block; border-radius: 6px; font-weight: 600; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);">📊 View Report List</a>
        </div>
    </form>
</div>

<script>
// Master rates - Initialize after DOM is ready
let masterCylinderRate = 1900.00;
let masterBenchmarkPercent = 74.00;

// Initialize master rates when DOM is ready
function initializeMasterRates() {
    const cylinderRateEl = document.getElementById('master_cylinder_rate');
    const benchmarkEl = document.getElementById('master_benchmark_percent');
    
    if (cylinderRateEl) {
        masterCylinderRate = parseFloat(cylinderRateEl.value) || 0.00;
        cylinderRateEl.addEventListener('change', function() {
            masterCylinderRate = parseFloat(this.value) || 0.00;
            recalculateAllRows();
        });
    }
    
    if (benchmarkEl) {
        masterBenchmarkPercent = parseFloat(benchmarkEl.value) || 74.00;
        benchmarkEl.addEventListener('change', function() {
            masterBenchmarkPercent = parseFloat(this.value) || 74.00;
            recalculateAllRows();
        });
    }
}

// Calculate row - EXACT EXCEL FORMULAS
function calculateRow(rowIndex) {
    const row = document.querySelector(`tr[data-row-index="${rowIndex}"]`);
    if (!row) return;
    
    // Get input values
    const cashSaleNet = parseFloat(row.querySelector('.cash-sale-net').value) || 0;
    const cateringBtcRegular = parseFloat(row.querySelector('.catering-btc-regular').value) || 0;
    const cateringBtcExtra = parseFloat(row.querySelector('.catering-btc-extra').value) || 0;
    const housekeepingLumpsum = parseFloat(row.querySelector('.housekeeping-lumpsum').value) || 0;
    const laundry = parseFloat(row.querySelector('.laundry').value) || 0;
    const cashPurchase = parseFloat(row.querySelector('.cash-purchase').value) || 0;
    const cateringCost = parseFloat(row.querySelector('.catering-cost').value) || 0;
    const housekeepingCost = parseFloat(row.querySelector('.housekeeping-cost').value) || 0;
    const manpowerDays = parseFloat(row.querySelector('.manpower-days').value) || 0;
    const odcCost = parseFloat(row.querySelector('.odc-cost').value) || 0;
    const cylinderQuantity = parseFloat(row.querySelector('.cylinder-quantity').value) || 0;
    const additionalCost = parseFloat(row.querySelector('.additional-cost')?.value) || 0;
    
    // Excel Formula: I = F + G (Total Food Sale - Cash Sale Net + Catering BTC Regular + Extra)
    const totalFoodSale = round(cashSaleNet + cateringBtcRegular + cateringBtcExtra, 2);
    row.querySelector('.total-food-sale').textContent = totalFoodSale.toFixed(2);
    
    // Excel Formula: L = I + J + K (Total Sale)
    const totalSale = round(totalFoodSale + housekeepingLumpsum + laundry, 2);
    row.querySelector('.total-sale').textContent = totalSale.toFixed(2);
    
    // Excel Formula: O = M + N (Total Food Cost)
    const totalFoodCost = round(cashPurchase + cateringCost, 2);
    row.querySelector('.total-food-cost').textContent = totalFoodCost.toFixed(2);
    
    // Excel Formula: P = (M+N)/I*(100)% (Food Cost %)
    const foodCostPercent = totalFoodSale > 0 ? round((totalFoodCost / totalFoodSale) * 100, 2) : 0;
    row.querySelector('.food-cost-percent').textContent = foodCostPercent.toFixed(2) + '%';
    row.querySelector('.food-cost-percent').style.color = foodCostPercent > masterBenchmarkPercent ? '#ef4444' : '#10b981';
    
    // Excel Formula: R = Q/(F+G) (Housekeeping Cost %)
    const housekeepingCostPercent = (cashSaleNet + cateringBtcRegular + cateringBtcExtra) > 0 
        ? round((housekeepingCost / (cashSaleNet + cateringBtcRegular + cateringBtcExtra)) * 100, 2) 
        : 0;
    row.querySelector('.housekeeping-cost-percent').textContent = housekeepingCostPercent.toFixed(2) + '%';
    
    // Excel Formula: T = 11000/26*S (Manpower Cost)
    const manpowerCost = round((11000 / 26) * manpowerDays, 2);
    row.querySelector('.manpower-cost').textContent = manpowerCost.toFixed(2);
    // Also update the after-ODC manpower cost cell
    const manpowerCostAfterOdcCell = row.querySelector('.manpower-cost-after-odc');
    if (manpowerCostAfterOdcCell) {
        manpowerCostAfterOdcCell.textContent = manpowerCost.toFixed(2);
    }
    
    // Excel Formula: Y = Z*X (Total Cylinder Cost)
    const totalCylinderCost = round(masterCylinderRate * cylinderQuantity, 2);
    row.querySelector('.total-cylinder-cost').textContent = totalCylinderCost.toFixed(2);
    row.querySelector('.cylinder-rate').textContent = masterCylinderRate.toFixed(2);
    
    // Excel Formula: AA = Y/L (Cylinder Cost %)
    const cylinderCostPercent = totalSale > 0 ? round((totalCylinderCost / totalSale) * 100, 2) : 0;
    row.querySelector('.cylinder-cost-percent').textContent = cylinderCostPercent.toFixed(2) + '%';
    
    // Excel Formula: AB = N*AF (Expected Food Cost)
    const expectedFoodCost = round(cateringCost * (masterBenchmarkPercent / 100), 2);
    
    // Excel Formula: AC = AB-(M+N+Q) (Variation) - additionalCost already defined above at line 861
    const variationAmount = round(expectedFoodCost - (cashPurchase + cateringCost + additionalCost), 2);
    const variationType = variationAmount >= 0 ? 'positive' : 'negative';
    const variationCell = row.querySelector('.variation-amount');
    variationCell.textContent = (variationAmount >= 0 ? '+' : '-') + Math.abs(variationAmount).toFixed(2);
    variationCell.className = 'calculated variation-amount text-right variation-' + variationType;
    
    // Recalculate totals
    recalculateCalculationRow();
}

// Recalculate all rows
function recalculateAllRows() {
    const rows = document.querySelectorAll('tr.data-row');
    rows.forEach((row, index) => {
        const rowIndex = row.getAttribute('data-row-index');
        calculateRow(rowIndex);
    });
}

// Recalculate calculation row (TOTAL)
function recalculateCalculationRow() {
    const rows = document.querySelectorAll('tr.data-row');
    const calcRow = document.querySelector('.calculation-row');
    if (!calcRow) return;
    
    let totalCashSaleNet = 0, totalCateringBtcRegular = 0, totalCateringBtcExtra = 0;
    let totalHousekeepingLumpsum = 0, totalLaundry = 0, totalCashPurchase = 0, totalCateringCost = 0;
    let totalHousekeepingCost = 0, totalManpowerDays = 0, totalOdcCost = 0, totalOdcCost2 = 0, totalCylinderQuantity = 0;
    let totalTotalFoodSale = 0, totalTotalSale = 0, totalTotalFoodCost = 0, totalVariation = 0;
    
    rows.forEach(row => {
        totalCashSaleNet += parseFloat(row.querySelector('.cash-sale-net').value) || 0;
        totalCateringBtcRegular += parseFloat(row.querySelector('.catering-btc-regular').value) || 0;
        totalCateringBtcExtra += parseFloat(row.querySelector('.catering-btc-extra').value) || 0;
        totalHousekeepingLumpsum += parseFloat(row.querySelector('.housekeeping-lumpsum').value) || 0;
        totalLaundry += parseFloat(row.querySelector('.laundry').value) || 0;
        totalCashPurchase += parseFloat(row.querySelector('.cash-purchase').value) || 0;
        totalCateringCost += parseFloat(row.querySelector('.catering-cost').value) || 0;
        totalHousekeepingCost += parseFloat(row.querySelector('.housekeeping-cost').value) || 0;
        totalManpowerDays += parseFloat(row.querySelector('.manpower-days').value) || 0;
        totalOdcCost += parseFloat(row.querySelector('.odc-cost').value) || 0;
        // Manpower cost is already calculated, get from the existing manpower-cost cell
        const manpowerCostCell = row.querySelector('.manpower-cost');
        const manpowerCostValue = manpowerCostCell ? parseFloat(manpowerCostCell.textContent.replace(/[^\d.-]/g, '')) || 0 : 0;
        // Update the after-ODC manpower cost cell
        const manpowerCostAfterOdcCell = row.querySelector('.manpower-cost-after-odc');
        if (manpowerCostAfterOdcCell) {
            manpowerCostAfterOdcCell.textContent = manpowerCostValue.toFixed(2);
        }
        // ODC COST 2 (second ODC after MANPOWER COST)
        totalOdcCost2 += parseFloat(row.querySelector('.odc-cost-2')?.value) || 0;
        totalCylinderQuantity += parseFloat(row.querySelector('.cylinder-quantity').value) || 0;
        totalTotalFoodSale += parseFloat(row.querySelector('.total-food-sale').textContent) || 0;
        totalTotalSale += parseFloat(row.querySelector('.total-sale').textContent) || 0;
        totalTotalFoodCost += parseFloat(row.querySelector('.total-food-cost').textContent) || 0;
        
        const variationText = row.querySelector('.variation-amount').textContent;
        const variationValue = parseFloat(variationText.replace(/[+\-]/g, '')) || 0;
        totalVariation += (variationText.startsWith('-') ? -variationValue : variationValue);
    });
    
    calcRow.querySelector('#calc-cash-sale-net').textContent = round(totalCashSaleNet, 2).toFixed(2);
    calcRow.querySelector('#calc-catering-btc-regular').textContent = round(totalCateringBtcRegular, 2).toFixed(2);
    calcRow.querySelector('#calc-catering-btc-extra').textContent = round(totalCateringBtcExtra, 2).toFixed(2);
    calcRow.querySelector('#calc-total-food-sale').textContent = round(totalTotalFoodSale, 2).toFixed(2);
    calcRow.querySelector('#calc-housekeeping-lumpsum').textContent = round(totalHousekeepingLumpsum, 2).toFixed(2);
    calcRow.querySelector('#calc-laundry').textContent = round(totalLaundry, 2).toFixed(2);
    calcRow.querySelector('#calc-total-sale').textContent = round(totalTotalSale, 2).toFixed(2);
    calcRow.querySelector('#calc-cash-purchase').textContent = round(totalCashPurchase, 2).toFixed(2);
    calcRow.querySelector('#calc-catering-cost').textContent = round(totalCateringCost, 2).toFixed(2);
    calcRow.querySelector('#calc-total-food-cost').textContent = round(totalTotalFoodCost, 2).toFixed(2);
    
    const avgFoodCostPercent = totalTotalFoodSale > 0 ? round((totalTotalFoodCost / totalTotalFoodSale) * 100, 2) : 0;
    calcRow.querySelector('#calc-food-cost-percent').textContent = avgFoodCostPercent.toFixed(2) + '%';
    
    calcRow.querySelector('#calc-housekeeping-cost').textContent = round(totalHousekeepingCost, 2).toFixed(2);
    const avgHousekeepingCostPercent = (totalCashSaleNet + totalCateringBtcRegular + totalCateringBtcExtra) > 0 
        ? round((totalHousekeepingCost / (totalCashSaleNet + totalCateringBtcRegular + totalCateringBtcExtra)) * 100, 2) 
        : 0;
    calcRow.querySelector('#calc-housekeeping-cost-percent').textContent = avgHousekeepingCostPercent.toFixed(2) + '%';
    
    calcRow.querySelector('#calc-manpower-days').textContent = round(totalManpowerDays, 2).toFixed(2);
    const totalManpowerCost = round((11000 / 26) * totalManpowerDays, 2);
    calcRow.querySelector('#calc-manpower-cost').textContent = totalManpowerCost.toFixed(2);
    
    calcRow.querySelector('#calc-odc-cost').textContent = round(totalOdcCost, 2).toFixed(2);
    // Calculate total manpower cost for after-ODC column
    let totalManpowerCostAfterOdc = 0;
    rows.forEach(row => {
        const manpowerCostCell = row.querySelector('.manpower-cost');
        if (manpowerCostCell) {
            totalManpowerCostAfterOdc += parseFloat(manpowerCostCell.textContent.replace(/[^\d.-]/g, '')) || 0;
        }
    });
    calcRow.querySelector('#calc-manpower-cost-after-odc').textContent = round(totalManpowerCostAfterOdc, 2).toFixed(2);
    calcRow.querySelector('#calc-odc-cost-2').textContent = round(totalOdcCost2, 2).toFixed(2);
    calcRow.querySelector('#calc-cylinder-quantity').textContent = round(totalCylinderQuantity, 2).toFixed(2);
    calcRow.querySelector('#calc-cylinder-rate').textContent = (masterCylinderRate || 0).toFixed(2);
    const totalCylinderCost = round((masterCylinderRate || 0) * totalCylinderQuantity, 2);
    calcRow.querySelector('#calc-total-cylinder-cost').textContent = totalCylinderCost.toFixed(2);
    const avgCylinderCostPercent = totalTotalSale > 0 ? round((totalCylinderCost / totalTotalSale) * 100, 2) : 0;
    calcRow.querySelector('#calc-cylinder-cost-percent').textContent = avgCylinderCostPercent.toFixed(2) + '%';
    
    const variationCell = calcRow.querySelector('#calc-variation-amount');
    variationCell.textContent = (totalVariation >= 0 ? '+' : '-') + Math.abs(round(totalVariation, 2)).toFixed(2);
    variationCell.className = 'calculated text-right variation-' + (totalVariation >= 0 ? 'positive' : 'negative');
}

// Get default entry date from form
function getDefaultEntryDate() {
    const fromDateEl = document.getElementById('from_date');
    if (fromDateEl && fromDateEl.value) {
        return fromDateEl.value;
    }
    // Fallback to today's date
    const today = new Date();
    return today.toISOString().split('T')[0];
}

// Add row
function addRow() {
    const tbody = document.getElementById('entriesBody');
    const rowCount = tbody.querySelectorAll('tr.data-row').length;
    const defaultDate = getDefaultEntryDate();
    const newRow = document.createElement('tr');
    newRow.className = 'data-row';
    newRow.setAttribute('data-row-index', rowCount);
    newRow.innerHTML = `
        <td><input type="date" name="entries[${rowCount}][entry_date]" value="${defaultDate}" class="entry-date" onchange="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][cash_sale_net]" value="0.00" class="cash-sale-net text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][catering_btc_regular]" value="0.00" class="catering-btc-regular text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][catering_btc_extra]" value="0.00" class="catering-btc-extra text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated total-food-sale text-right">0.00</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][housekeeping_lumpsum]" value="0.00" class="housekeeping-lumpsum text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][laundry]" value="0.00" class="laundry text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated total-sale text-right">0.00</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][cash_purchase]" value="0.00" class="cash-purchase text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][catering_cost]" value="0.00" class="catering-cost text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated total-food-cost text-right">0.00</td>
        <td class="calculated food-cost-percent text-right">0.00%</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][housekeeping_cost]" value="0.00" class="housekeeping-cost text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated housekeeping-cost-percent text-right">0.00%</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][manpower_days]" value="0.00" class="manpower-days text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated manpower-cost text-right">0.00</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][odc_cost]" value="0.00" class="odc-cost text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated manpower-cost-after-odc text-right">0.00</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][odc_cost_2]" value="0.00" class="odc-cost-2 text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][cylinder_quantity]" value="0.00" class="cylinder-quantity text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated cylinder-rate text-right">${masterCylinderRate.toFixed(2)}</td>
        <td class="calculated total-cylinder-cost text-right">0.00</td>
        <td class="calculated cylinder-cost-percent text-right">0.00%<input type="hidden" name="entries[${rowCount}][additional_cost]" value="0.00" class="additional-cost"></td>
        <td class="calculated variation-amount text-right variation-positive">0.00</td>
        <td><button type="button" class="btn-action btn-success" onclick="insertRowAfter(this)" style="padding: 4px 8px; font-size: 12px; margin: 2px;">+</button><button type="button" class="btn-action btn-danger" onclick="removeRow(this)" style="padding: 4px 8px; font-size: 12px; margin: 2px;">×</button></td>
    `;
    tbody.appendChild(newRow);
    calculateRow(rowCount);
}

// Insert row after
function insertRowAfter(btn) {
    const currentRow = btn.closest('tr');
    const tbody = document.getElementById('entriesBody');
    const rowCount = tbody.querySelectorAll('tr.data-row').length;
    const defaultDate = getDefaultEntryDate();
    const newRow = document.createElement('tr');
    newRow.className = 'data-row';
    newRow.setAttribute('data-row-index', rowCount);
    newRow.innerHTML = `
        <td><input type="date" name="entries[${rowCount}][entry_date]" value="${defaultDate}" class="entry-date" onchange="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][cash_sale_net]" value="0.00" class="cash-sale-net text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][catering_btc_regular]" value="0.00" class="catering-btc-regular text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][catering_btc_extra]" value="0.00" class="catering-btc-extra text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated total-food-sale text-right">0.00</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][housekeeping_lumpsum]" value="0.00" class="housekeeping-lumpsum text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][laundry]" value="0.00" class="laundry text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated total-sale text-right">0.00</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][cash_purchase]" value="0.00" class="cash-purchase text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][catering_cost]" value="0.00" class="catering-cost text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated total-food-cost text-right">0.00</td>
        <td class="calculated food-cost-percent text-right">0.00%</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][housekeeping_cost]" value="0.00" class="housekeeping-cost text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated housekeeping-cost-percent text-right">0.00%</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][manpower_days]" value="0.00" class="manpower-days text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated manpower-cost text-right">0.00</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][odc_cost]" value="0.00" class="odc-cost text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated manpower-cost-after-odc text-right">0.00</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][odc_cost_2]" value="0.00" class="odc-cost-2 text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][cylinder_quantity]" value="0.00" class="cylinder-quantity text-right" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})" style="width: 100%; border: none; padding: 4px;"></td>
        <td class="calculated cylinder-rate text-right">${masterCylinderRate.toFixed(2)}</td>
        <td class="calculated total-cylinder-cost text-right">0.00</td>
        <td class="calculated cylinder-cost-percent text-right">0.00%<input type="hidden" name="entries[${rowCount}][additional_cost]" value="0.00" class="additional-cost"></td>
        <td class="calculated variation-amount text-right variation-positive">0.00</td>
        <td><button type="button" class="btn-action btn-success" onclick="insertRowAfter(this)" style="padding: 4px 8px; font-size: 12px; margin: 2px;">+</button><button type="button" class="btn-action btn-danger" onclick="removeRow(this)" style="padding: 4px 8px; font-size: 12px; margin: 2px;">×</button></td>
    `;
    currentRow.insertAdjacentElement('afterend', newRow);
    // Update all row indices
    updateRowIndices();
    calculateRow(rowCount);
}

// Remove row
function removeRow(btn) {
    const row = btn.closest('tr');
    if (confirm('Are you sure you want to remove this row?')) {
        row.remove();
        updateRowIndices();
        recalculateCalculationRow();
    }
}

// Update row indices
function updateRowIndices() {
    const rows = document.querySelectorAll('tr.data-row');
    rows.forEach((row, index) => {
        row.setAttribute('data-row-index', index);
        row.querySelectorAll('input, select').forEach(input => {
            const name = input.getAttribute('name');
            if (name) {
                const newName = name.replace(/entries\[\d+\]/, `entries[${index}]`);
                input.setAttribute('name', newName);
                const onchange = input.getAttribute('onchange');
                if (onchange) {
                    input.setAttribute('onchange', onchange.replace(/\d+/, index));
                }
                const oninput = input.getAttribute('oninput');
                if (oninput) {
                    input.setAttribute('oninput', oninput.replace(/\d+/, index));
                }
            }
        });
    });
}

// Round function
function round(value, decimals) {
    return Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals);
}

// Auto-select all text in number inputs on focus for easy replacement
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('input[type="number"]').forEach(function(input) {
        input.addEventListener('focus', function() {
            this.select();
        });
    });
    
    // Also handle dynamically added inputs
    document.getElementById('entriesBody').addEventListener('focusin', function(e) {
        if (e.target && e.target.type === 'number') {
            e.target.select();
        }
    });
});

// Filter by month/year
function filterByMonthYear() {
    const month = document.getElementById('filter_month').value;
    const year = document.getElementById('filter_year').value;
    window.location.href = '?month=' + month + '&year=' + year;
}

// Save cylinder rate (for master rate in header)
function saveCylinderRate() {
    const rate = parseFloat(document.getElementById('master_cylinder_rate').value) || 0;
    masterCylinderRate = rate;
    recalculateAllRows();
    
    // Show success message
    const btn = event.target;
    const originalText = btn.innerHTML;
    btn.innerHTML = '✓';
    btn.style.background = '#28a745';
    setTimeout(() => {
        btn.innerHTML = originalText;
        btn.style.background = '#006699';
    }, 1500);
}

// Save "To" name
function saveToName() {
    const toName = document.getElementById('to_name_input').value;
    const btn = event.target;
    
    fetch(window.location.pathname, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'save_to_name=1&to_name=' + encodeURIComponent(toName)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success
            const originalBg = btn.style.background;
            btn.innerHTML = '✓';
            btn.style.background = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';
            setTimeout(() => {
                btn.innerHTML = '✓';
                btn.style.background = originalBg || 'linear-gradient(135deg, #10b981 0%, #059669 100%)';
            }, 1500);
        } else {
            alert('Error saving name: ' + data.message);
        }
    })
    .catch(error => {
        alert('Error saving name');
        console.error(error);
    });
}

// Save cylinder rate setting (for period form)
function saveCylinderRateSetting() {
    const rate = parseFloat(document.getElementById('cylinder_rate').value) || 0;
    document.getElementById('master_cylinder_rate').value = rate.toFixed(2);
    masterCylinderRate = rate;
    recalculateAllRows();
    
    // Show success message
    const btn = event.target;
    const originalText = btn.innerHTML;
    btn.innerHTML = '✓';
    btn.style.background = '#28a745';
    setTimeout(() => {
        btn.innerHTML = originalText;
        btn.style.background = '#006699';
    }, 1500);
}

// Initialize calculations
document.addEventListener('DOMContentLoaded', function() {
    // Initialize master rates first
    initializeMasterRates();
    
    // Recalculate all rows
    setTimeout(() => {
        recalculateAllRows();
    }, 100);
    
    // Add global event listeners for auto-calculation
    const entriesBody = document.getElementById('entriesBody');
    if (entriesBody) {
        entriesBody.addEventListener('input', function(e) {
            if (e.target.matches('input[type="number"], input[type="date"]')) {
                const row = e.target.closest('tr.data-row');
                if (row) {
                    const rowIndex = row.getAttribute('data-row-index');
                    setTimeout(() => calculateRow(rowIndex), 100);
                }
            }
        });
    }
});
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
