<?php
/**
 * Enterprise HRM ERP System - DFC Report View
 * Date/Month/Year wise report viewing with individual submission reports
 */

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

$pageTitle = 'SSA Report';
$currentModule = 'dfc';

$siteId = getCurrentSiteId();
$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'] : '';
$viewPeriodId = isset($_GET['view']) ? (int)$_GET['view'] : 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 = '';
}

// Handle Excel Export
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    try {
        $db = getDB();
        
        // Get site name
        $siteStmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
        $siteStmt->execute([$siteId]);
        $siteData = $siteStmt->fetch();
        $exportSiteName = $siteData['site_name'] ?? '';
        
        // Get "To" name for this site
        $toName = '';
        try {
            $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
        }
        
        // Build filename
        if (!empty($selectedDate)) {
            $exportFilename = 'SSA_Report_' . date('d_M_Y', strtotime($selectedDate)) . '_' . date('Ymd_His');
        } else {
            $exportFilename = 'SSA_Report_' . date('M_Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)) . '_' . date('Ymd_His');
        }
        
        // Build WHERE clause based on filters
        $whereConditions = ["p.site_id = ?"];
        $params = [$siteId];
        
        if (!empty($selectedDate)) {
            $whereConditions[] = "DATE(p.start_date) = ?";
            $params[] = $selectedDate;
        } else {
            $whereConditions[] = "p.month = ?";
            $whereConditions[] = "p.year = ?";
            $params[] = $selectedMonth;
            $params[] = $selectedYear;
        }
        
        $whereClause = implode(' AND ', $whereConditions);
        
        // Get all periods
        $stmt = $db->prepare("
            SELECT p.* FROM dfc_periods p
            WHERE {$whereClause}
            ORDER BY p.start_date DESC, p.period_id DESC
        ");
        $stmt->execute($params);
        $exportPeriods = $stmt->fetchAll();
        
        // Output Excel (HTML format)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="' . $exportFilename . '.xls"');
        header('Cache-Control: max-age=0');
        
        echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
        echo '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
        echo '<style>
            table { border-collapse: collapse; width: 100%; font-family: Arial, sans-serif; font-size: 10pt; }
            th { background-color: #1e3c72; color: white; font-weight: bold; padding: 8px; text-align: center; border: 1px solid #000; }
            td { padding: 5px; border: 1px solid #ccc; text-align: left; }
            .text-right { text-align: right !important; }
            .site-info { font-weight: bold; font-size: 12pt; padding: 10px; border: none; }
            .period-header { background-color: #2a5298 !important; color: white !important; font-weight: bold; }
            .total-row { background-color: #1e3c72 !important; color: white !important; font-weight: bold; }
            .calculated { background-color: #dcfce7 !important; font-weight: bold; }
            .variation-positive { background-color: #fee2e2 !important; color: #991b1b !important; }
            .variation-negative { background-color: #dcfce7 !important; color: #166534 !important; }
        </style></head><body>';
        
        // Add site info
        echo '<table style="margin-bottom: 10px; border: none;">';
        echo '<tr><td class="site-info" style="border: none;">Site: ' . htmlspecialchars($exportSiteName) . '</td></tr>';
        if (!empty($toName)) {
            echo '<tr><td style="border: none; font-weight: bold;">To: ' . htmlspecialchars($toName) . '</td></tr>';
        }
        if (!empty($selectedDate)) {
            echo '<tr><td style="border: none; font-weight: bold;">Date: ' . date('d M Y', strtotime($selectedDate)) . '</td></tr>';
        } else {
            echo '<tr><td style="border: none; font-weight: bold;">Period: ' . date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)) . '</td></tr>';
        }
        echo '<tr><td style="border: none;">Export Date: ' . date('d-m-Y H:i') . '</td></tr>';
        echo '</table>';
        
        // Export each period with its entries
        foreach ($exportPeriods as $period) {
            // Get entries for this period
            $entryStmt = $db->prepare("SELECT * FROM dfc_entries WHERE period_id = ? ORDER BY entry_date, sr_no, entry_id");
            $entryStmt->execute([$period['period_id']]);
            $entries = $entryStmt->fetchAll();
            
            echo '<table style="margin-top: 20px;">';
            
            // Period header
            echo '<tr class="period-header">';
            echo '<td colspan="23" style="background-color: #2a5298; color: white; font-weight: bold; padding: 10px;">';
            echo htmlspecialchars($period['period_name']) . ' | ';
            echo date('d M Y', strtotime($period['start_date'])) . ' to ' . date('d M Y', strtotime($period['end_date']));
            echo ' | Cylinder Rate: ' . number_format($period['cylinder_rate'], 2);
            echo ' | Benchmark: ' . number_format($period['benchmark_percent'], 2) . '%';
            echo '</td></tr>';
            
            // Column headers
            echo '<tr>';
            echo '<th>Date</th>';
            echo '<th>Cash Sale Net</th>';
            echo '<th>Regular BTC</th>';
            echo '<th>Extra BTC</th>';
            echo '<th>Total Food Sale</th>';
            echo '<th>Housekeeping</th>';
            echo '<th>Laundry</th>';
            echo '<th>Total Sale</th>';
            echo '<th>Cash Purchase</th>';
            echo '<th>Catering Cost</th>';
            echo '<th>Total Food Cost</th>';
            echo '<th>Food Cost %</th>';
            echo '<th>HK Cost</th>';
            echo '<th>HK Cost %</th>';
            echo '<th>Manpower Days</th>';
            echo '<th>Manpower Cost</th>';
            echo '<th>ODC</th>';
            echo '<th>ODC Cost</th>';
            echo '<th>Cylinder Qty</th>';
            echo '<th>Cylinder Rate</th>';
            echo '<th>Total Cylinder</th>';
            echo '<th>Fuel Cost %</th>';
            echo '<th>Variation</th>';
            echo '</tr>';
            
            // Data rows
            foreach ($entries as $entry) {
                $variationType = ($entry['variation_type'] ?? 'positive') === 'positive' ? 'variation-positive' : 'variation-negative';
                $variationSign = ($entry['variation_type'] ?? 'positive') === 'positive' ? '+' : '-';
                
                echo '<tr>';
                echo '<td>' . date('d-m-Y', strtotime($entry['entry_date'])) . '</td>';
                echo '<td class="text-right">' . number_format($entry['cash_sale_net'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['catering_btc_regular'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['catering_btc_extra'] ?? 0, 2) . '</td>';
                echo '<td class="text-right calculated">' . number_format($entry['total_food_sale'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['housekeeping_lumpsum'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['laundry'] ?? 0, 2) . '</td>';
                echo '<td class="text-right calculated">' . number_format($entry['total_sale'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['cash_purchase'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['catering_cost'] ?? 0, 2) . '</td>';
                echo '<td class="text-right calculated">' . number_format($entry['total_food_cost'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['food_cost_percent'] ?? 0, 2) . '%</td>';
                echo '<td class="text-right">' . number_format($entry['housekeeping_cost'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['housekeeping_cost_percent'] ?? 0, 2) . '%</td>';
                echo '<td class="text-right">' . number_format($entry['manpower_days'] ?? 0, 2) . '</td>';
                echo '<td class="text-right calculated">' . number_format($entry['manpower_cost'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['odc_cost'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['odc_cost_2'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['cylinder_quantity'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['cylinder_rate'] ?? 0, 2) . '</td>';
                echo '<td class="text-right calculated">' . number_format($entry['total_cylinder_cost'] ?? 0, 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['cylinder_cost_percent'] ?? 0, 2) . '%</td>';
                echo '<td class="text-right ' . $variationType . '">' . $variationSign . number_format($entry['variation_amount'] ?? 0, 2) . '</td>';
                echo '</tr>';
            }
            
            // Total row
            $totalFoodSale = array_sum(array_column($entries, 'total_food_sale'));
            $totalFoodCost = array_sum(array_column($entries, 'total_food_cost'));
            $avgFoodCostPercent = $totalFoodSale > 0 ? ($totalFoodCost / $totalFoodSale) * 100 : 0;
            
            $totalCashSale = array_sum(array_column($entries, 'cash_sale_net'));
            $totalCateringBtc = array_sum(array_column($entries, 'catering_btc_regular')) + array_sum(array_column($entries, 'catering_btc_extra'));
            $totalHKCost = array_sum(array_column($entries, 'housekeeping_cost'));
            $avgHKCostPercent = ($totalCashSale + $totalCateringBtc) > 0 ? ($totalHKCost / ($totalCashSale + $totalCateringBtc)) * 100 : 0;
            
            $totalSale = array_sum(array_column($entries, 'total_sale'));
            $totalCylinder = array_sum(array_column($entries, 'total_cylinder_cost'));
            $avgCylinderPercent = $totalSale > 0 ? ($totalCylinder / $totalSale) * 100 : 0;
            
            $totalVariation = 0;
            foreach ($entries as $e) {
                $var = (($e['variation_type'] ?? 'positive') === 'positive' ? 1 : -1) * ($e['variation_amount'] ?? 0);
                $totalVariation += $var;
            }
            
            echo '<tr class="total-row">';
            echo '<td style="background-color: #1e3c72; color: white;"><strong>TOTAL</strong></td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'cash_sale_net')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'catering_btc_regular')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'catering_btc_extra')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format($totalFoodSale, 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'housekeeping_lumpsum')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'laundry')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format($totalSale, 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'cash_purchase')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'catering_cost')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format($totalFoodCost, 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format($avgFoodCostPercent, 2) . '%</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format($totalHKCost, 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format($avgHKCostPercent, 2) . '%</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'manpower_days')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'manpower_cost')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'odc_cost')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'odc_cost_2') ?: [0]), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format(array_sum(array_column($entries, 'cylinder_quantity')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format($period['cylinder_rate'] ?? 0, 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format($totalCylinder, 2) . '</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . number_format($avgCylinderPercent, 2) . '%</td>';
            echo '<td class="text-right" style="background-color: #1e3c72; color: white;">' . ($totalVariation >= 0 ? '+' : '-') . number_format(abs($totalVariation), 2) . '</td>';
            echo '</tr>';
            
            echo '</table>';
        }
        
        if (empty($exportPeriods)) {
            echo '<table><tr><td style="text-align: center; padding: 20px;">No data found for the selected period.</td></tr></table>';
        }
        
        echo '</body></html>';
        exit;
        
    } catch (Exception $e) {
        error_log("SSA export error: " . $e->getMessage());
        $_SESSION['error'] = 'Error exporting data: ' . $e->getMessage();
    }
}

// Handle delete request
if (isset($_GET['delete']) && $_GET['delete'] > 0) {
    $deletePeriodId = (int)$_GET['delete'];
    
    try {
        $db = getDB();
        $db->beginTransaction();
        
        // Verify period exists and belongs to this site
        $stmt = $db->prepare("SELECT period_id, period_name FROM dfc_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$deletePeriodId, $siteId]);
        $periodToDelete = $stmt->fetch();
        
        if (!$periodToDelete) {
            throw new Exception('Period not found or you do not have permission to delete it.');
        }
        
        // Delete all entries for this period
        $stmt = $db->prepare("DELETE FROM dfc_entries WHERE period_id = ?");
        $stmt->execute([$deletePeriodId]);
        
        // Delete the period
        $stmt = $db->prepare("DELETE FROM dfc_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$deletePeriodId, $siteId]);
        
        $db->commit();
        
        $_SESSION['success'] = 'Report deleted successfully.';
        
        if (function_exists('logAudit')) {
            logAudit('DELETE', 'dfc_periods', $deletePeriodId, "Deleted period: {$periodToDelete['period_name']}");
        }
        
        // Preserve filter in redirect
        $redirectUrl = $_SERVER['PHP_SELF'];
        if (!empty($selectedDate)) {
            $redirectUrl .= '?date=' . urlencode($selectedDate);
        } else {
            $redirectUrl .= '?month=' . $selectedMonth . '&year=' . $selectedYear;
        }
        header('Location: ' . $redirectUrl);
        exit;
        
    } catch (Exception $e) {
        if (isset($db) && $db->inTransaction()) {
            $db->rollBack();
        }
        $_SESSION['error'] = 'Error deleting report: ' . $e->getMessage();
        // Preserve filter in redirect
        $redirectUrl = $_SERVER['PHP_SELF'];
        if (!empty($selectedDate)) {
            $redirectUrl .= '?date=' . urlencode($selectedDate);
        } else {
            $redirectUrl .= '?month=' . $selectedMonth . '&year=' . $selectedYear;
        }
        header('Location: ' . $redirectUrl);
        exit;
    }
}

try {
    $db = getDB();
    
    // Build WHERE clause based on filters
    $whereConditions = ["p.site_id = ?"];
    $params = [$siteId];
    
    // Date filter (if provided)
    if (!empty($selectedDate)) {
        $whereConditions[] = "DATE(p.start_date) = ?";
        $params[] = $selectedDate;
    } else {
        // Month/Year filter (if date not provided)
        $whereConditions[] = "p.month = ?";
        $whereConditions[] = "p.year = ?";
        $params[] = $selectedMonth;
        $params[] = $selectedYear;
    }
    
    $whereClause = implode(' AND ', $whereConditions);
    
    // Get all periods with filters (Date OR Month/Year)
    $stmt = $db->prepare("
        SELECT DISTINCT p.period_id, p.period_name, p.start_date, p.end_date,
               p.month, p.year, p.cylinder_rate, p.benchmark_percent,
               COUNT(DISTINCT pe.entry_id) as entry_count,
               COALESCE(SUM(pe.total_sale), 0) as total_sale,
               COALESCE(SUM(pe.total_food_cost), 0) as total_food_cost,
               COALESCE(SUM(pe.manpower_cost), 0) as total_manpower_cost,
               COALESCE(SUM(pe.total_cylinder_cost), 0) as total_cylinder_cost,
               COALESCE(SUM(pe.variation_amount), 0) as total_variation
        FROM dfc_periods p
        LEFT JOIN dfc_entries pe ON p.period_id = pe.period_id
        WHERE {$whereClause}
        GROUP BY p.period_id
        ORDER BY p.start_date DESC, p.period_id DESC
    ");
    $stmt->execute($params);
    $periods = $stmt->fetchAll();
    
    // Group periods by date for better display
    $periodsByDate = [];
    foreach ($periods as $p) {
        $dateKey = date('Y-m-d', strtotime($p['start_date']));
        if (!isset($periodsByDate[$dateKey])) {
            $periodsByDate[$dateKey] = [];
        }
        $periodsByDate[$dateKey][] = $p;
    }
    
    // Load specific period details if viewing
    $period = null;
    $entries = [];
    
    if ($viewPeriodId > 0) {
        $stmt = $db->prepare("SELECT * FROM dfc_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$viewPeriodId, $siteId]);
        $period = $stmt->fetch();
        
        if ($period) {
            $stmt = $db->prepare("
                SELECT * FROM dfc_entries 
                WHERE period_id = ? 
                ORDER BY entry_date, sr_no, entry_id
            ");
            $stmt->execute([$viewPeriodId]);
            $entries = $stmt->fetchAll();
        }
    }
    
} catch (Exception $e) {
    error_log("DFC report error: " . $e->getMessage());
    $periods = [];
    $periodsByDate = [];
    $entries = [];
}

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

// Show 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 (isset($_SESSION['error'])) {
    echo '<div class="alert alert-danger" style="background: #f8d7da; color: #721c24; padding: 12px; margin: 10px 0; border: 1px solid #f5c6cb; border-radius: 4px;">';
    echo htmlspecialchars($_SESSION['error']);
    echo '</div>';
    unset($_SESSION['error']);
}
?>

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

/* Main Container */
.report-container {
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e8ec 100%);
    padding: 25px;
    font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
    min-height: 100vh;
}

/* Page Title */
.report-container h2 {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
    color: #fff;
    padding: 20px 25px;
    margin: -25px -25px 25px -25px;
    font-size: 22px;
    font-weight: 600;
    letter-spacing: 0.5px;
    display: flex;
    align-items: center;
    gap: 12px;
    box-shadow: 0 4px 15px rgba(30, 60, 114, 0.3);
}

.report-container h2::before {
    content: '📊';
    font-size: 24px;
}

/* Filter Section */
.filter-section {
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    padding: 20px 25px;
    margin-bottom: 25px;
    border: none;
    border-radius: 12px;
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border-left: 4px solid #2a5298;
}

.filter-section label {
    font-weight: 600;
    color: #334155;
    font-size: 13px;
}

.filter-section input[type="date"],
.filter-section input[type="number"],
.filter-section select {
    padding: 10px 14px;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    font-size: 13px;
    background: #fff;
    transition: all 0.3s ease;
    min-width: 140px;
}

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

.filter-section button {
    padding: 10px 18px;
    background: linear-gradient(135deg, #64748b 0%, #475569 100%);
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-weight: 500;
    transition: all 0.3s ease;
}

.filter-section button:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(71, 85, 105, 0.3);
}

/* Report Table */
.report-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    margin-top: 20px;
    font-size: 13px;
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.report-table th {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
    color: #fff;
    padding: 14px 12px;
    text-align: left;
    border: none;
    font-weight: 600;
    text-transform: uppercase;
    font-size: 11px;
    letter-spacing: 0.5px;
}

.report-table td {
    padding: 12px;
    border-bottom: 1px solid #e2e8f0;
    vertical-align: middle;
}

.report-table tbody tr {
    transition: all 0.2s ease;
}

.report-table tbody tr:hover {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
}

.report-table tbody tr:last-child td {
    border-bottom: none;
}

/* Action Buttons */
.btn-view, .btn-edit, .btn-delete {
    padding: 8px 14px;
    color: #fff;
    text-decoration: none;
    border-radius: 6px;
    font-size: 12px;
    margin: 3px;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-weight: 500;
    transition: all 0.3s ease;
    border: none;
    cursor: pointer;
}

.btn-view {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
}

.btn-view:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
}

.btn-edit {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: #fff;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3);
}

.btn-edit:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4);
}

.btn-delete {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
}

.btn-delete:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
}

/* Back Button */
.btn-back {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    color: white;
    text-decoration: none;
    border-radius: 8px;
    font-weight: 600;
    font-size: 13px;
    transition: all 0.3s ease;
    box-shadow: 0 2px 10px rgba(59, 130, 246, 0.3);
}

.btn-back:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);
}

/* Excel-like Table */
.excel-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    margin: 25px 0;
    font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
    font-size: 12px;
    background: #fff;
    min-width: 2400px;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
    border-radius: 12px;
    overflow: hidden;
}

.excel-table thead {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
    color: #fff;
}

.excel-table thead th {
    padding: 14px 8px;
    text-align: center;
    border: none;
    border-right: 1px solid rgba(255, 255, 255, 0.1);
    font-weight: 600;
    background: transparent !important;
    color: #fff !important;
    white-space: nowrap;
    text-transform: uppercase;
    font-size: 10px;
    letter-spacing: 0.8px;
}

.excel-table thead th:last-child {
    border-right: none;
}

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

.excel-table tbody td:last-child {
    border-right: none;
}

.excel-table tbody tr:nth-child(even) td {
    background: #f8fafc;
}

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

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

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

.excel-table .text-right {
    text-align: right !important;
}

.excel-table .calculated {
    background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%) !important;
    font-weight: 600;
    text-align: right !important;
    color: #166534;
}

.excel-table .total-row {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%) !important;
    color: #fff !important;
    font-weight: bold;
}

.excel-table .total-row td {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%) !important;
    border: none !important;
    border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
    color: #fff !important;
    font-size: 13px;
    padding: 14px 8px;
    font-weight: 700;
}

.excel-table .total-row td:last-child {
    border-right: none !important;
}

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

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

/* Summary Cards - Enhanced */
.summary-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin: 25px 0;
}

.summary-card {
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    padding: 20px;
    border-radius: 12px;
    border-left: 5px solid;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.summary-card::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 60px;
    height: 60px;
    background: linear-gradient(135deg, rgba(0, 0, 0, 0.02) 0%, rgba(0, 0, 0, 0.05) 100%);
    border-radius: 0 0 0 60px;
}

.summary-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.summary-card:nth-child(1) { border-left-color: #10b981; }
.summary-card:nth-child(2) { border-left-color: #f59e0b; }
.summary-card:nth-child(3) { border-left-color: #3b82f6; }
.summary-card:nth-child(4) { border-left-color: #ef4444; }

.summary-card-label {
    font-size: 12px;
    color: #64748b;
    margin-bottom: 8px;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.summary-card-value {
    font-size: 26px;
    font-weight: 700;
    color: #1e293b;
    line-height: 1.2;
}

.summary-card-value.positive {
    color: #10b981;
}

.summary-card-value.negative {
    color: #ef4444;
}

/* Export Button */
.btn-export {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    border: none;
    padding: 10px 18px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    white-space: nowrap;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
}

.btn-export:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
}

.btn-export:disabled {
    background: #6c757d;
    cursor: not-allowed;
    opacity: 0.6;
    transform: none;
    box-shadow: none;
}
</style>

<div class="report-container">
    <h2>SSA (Staff Strength & Attendance) - Reports</h2>
    
    <!-- Filter Section -->
    <div class="filter-section">
        <div>
            <label><strong>Filter By:</strong></label>
        </div>
        
        <div>
            <label>Date:</label>
            <input type="date" id="filter_date" value="<?php echo htmlspecialchars($selectedDate); ?>" 
                   onchange="filterByDate()" style="padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
            <button onclick="clearDateFilter()" style="padding: 5px 10px; margin-left: 5px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer;">Clear</button>
        </div>
        
        <div style="margin-left: 20px;">
            <label>OR Month:</label>
            <select id="filter_month" onchange="filterReport()" style="padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                <?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>
        
        <div>
            <label>Year:</label>
            <input type="number" id="filter_year" value="<?php echo $selectedYear; ?>" 
                   min="2020" max="2100" onchange="filterReport()" 
                   style="width: 100px; padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
        </div>
        
        <div style="margin-left: auto; display: flex; gap: 10px; align-items: center;">
            <button type="button" class="btn-export" onclick="exportToExcel()" title="Export to Excel">
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                Export
            </button>
            <a href="<?php echo BASE_URL; ?>/modules/dfc/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="btn-view" style="text-decoration: none; padding: 8px 15px;">← Back to Entry</a>
        </div>
    </div>
    
    <?php if ($viewPeriodId > 0 && $period): ?>
    <!-- Detailed View for Single Period (Individual Report) -->
    <div style="margin-bottom: 20px; display: flex; align-items: center; gap: 15px;">
        <a href="?<?php 
            if (!empty($selectedDate)) {
                echo 'date=' . urlencode($selectedDate);
            } else {
                echo 'month=' . $selectedMonth . '&year=' . $selectedYear;
            }
        ?>" 
           class="btn-view" style="text-decoration: none; padding: 8px 15px; background: #28a745; border-radius: 4px; color: white; font-weight: bold;">← Back to Reports List</a>
        <span style="color: #666; font-size: 14px;">
            Viewing: <strong><?php echo htmlspecialchars($period['period_name']); ?></strong>
        </span>
    </div>
    
    <div class="detailed-report-section">
        <h3><?php echo htmlspecialchars($period['period_name']); ?></h3>
        <p><strong>Period:</strong> <?php echo date('d M Y', strtotime($period['start_date'])); ?> to <?php echo date('d M Y', strtotime($period['end_date'])); ?></p>
        <p><strong>Cylinder Rate:</strong> ₹<?php echo number_format($period['cylinder_rate'], 2); ?> | <strong>Benchmark %:</strong> <?php echo number_format($period['benchmark_percent'], 2); ?>%</p>
        
        <!-- Summary Cards -->
        <div class="summary-cards">
            <div class="summary-card" style="border-left-color: #1e40af;">
                <div class="summary-card-label">Total Sale</div>
                <div class="summary-card-value">₹<?php echo number_format(array_sum(array_column($entries, 'total_sale')), 2); ?></div>
            </div>
            <div class="summary-card" style="border-left-color: #991b1b;">
                <div class="summary-card-label">Total Food Cost</div>
                <div class="summary-card-value">₹<?php echo number_format(array_sum(array_column($entries, 'total_food_cost')), 2); ?></div>
            </div>
            <div class="summary-card" style="border-left-color: #065f46;">
                <div class="summary-card-label">Total Manpower Cost</div>
                <div class="summary-card-value">₹<?php echo number_format(array_sum(array_column($entries, 'manpower_cost')), 2); ?></div>
            </div>
            <div class="summary-card" style="border-left-color: #92400e;">
                <div class="summary-card-label">Total Variation</div>
                <div class="summary-card-value" style="color: <?php echo array_sum(array_column($entries, 'variation_amount')) >= 0 ? '#ef4444' : '#10b981'; ?>">
                    <?php 
                    $totalVariation = 0;
                    foreach ($entries as $e) {
                        $var = ($e['variation_type'] === 'positive' ? 1 : -1) * ($e['variation_amount'] ?? 0);
                        $totalVariation += $var;
                    }
                    echo ($totalVariation >= 0 ? '+' : '-') . '₹' . number_format(abs($totalVariation), 2); 
                    ?>
                </div>
            </div>
        </div>
        
        <!-- Detailed Table -->
        <div style="overflow-x: auto; margin-top: 20px; width: 100%; border: 1px solid #ddd; border-radius: 4px;">
            <table class="excel-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Cash Sale Net</th>
                        <th>Regular BTC</th>
                        <th>Extra BTC</th>
                        <th>Total Food Sale</th>
                        <th>Housekeeping</th>
                        <th>Laundry</th>
                        <th>Total Sale</th>
                        <th>Cash Purchase</th>
                        <th>Catering Cost</th>
                        <th>Total Food Cost</th>
                        <th>Food Cost %</th>
                        <th>HK Cost</th>
                        <th>HK Cost %</th>
                        <th>Manpower Days</th>
                        <th>Manpower Cost</th>
                        <th>ODC</th>
                        <th>ODC Cost</th>
                        <th>Cylinder Qty</th>
                        <th>Cylinder Rate</th>
                        <th>Total Cylinder</th>
                        <th>Fuel Cost %</th>
                        <th>Variation</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($entries as $entry): ?>
                    <tr>
                        <td><?php echo date('d M Y', strtotime($entry['entry_date'])); ?></td>
                        <td class="text-right"><?php echo number_format($entry['cash_sale_net'] ?? 0, 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['catering_btc_regular'] ?? 0, 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['catering_btc_extra'] ?? 0, 2); ?></td>
                        <td class="text-right calculated"><?php echo number_format($entry['total_food_sale'] ?? 0, 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['housekeeping_lumpsum'] ?? 0, 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['laundry'] ?? 0, 2); ?></td>
                        <td class="text-right calculated"><?php echo number_format($entry['total_sale'] ?? 0, 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['cash_purchase'] ?? 0, 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['catering_cost'] ?? 0, 2); ?></td>
                        <td class="text-right calculated"><?php echo number_format($entry['total_food_cost'] ?? 0, 2); ?></td>
                        <td class="text-right calculated" style="color: <?php echo ($entry['food_cost_percent'] ?? 0) > $period['benchmark_percent'] ? '#ef4444' : '#10b981'; ?>;">
                            <?php echo number_format($entry['food_cost_percent'] ?? 0, 2); ?>%
                        </td>
                        <td class="text-right"><?php echo number_format($entry['housekeeping_cost'] ?? 0, 2); ?></td>
                        <td class="text-right calculated"><?php echo number_format($entry['housekeeping_cost_percent'] ?? 0, 2); ?>%</td>
                        <td class="text-right"><?php echo number_format($entry['manpower_days'] ?? 0, 2); ?></td>
                        <td class="text-right calculated"><?php echo number_format($entry['manpower_cost'] ?? 0, 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['odc_cost'] ?? 0, 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['odc_cost_2'] ?? 0, 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['cylinder_quantity'] ?? 0, 2); ?></td>
                        <td class="text-right calculated"><?php echo number_format($entry['cylinder_rate'] ?? 0, 2); ?></td>
                        <td class="text-right calculated"><?php echo number_format($entry['total_cylinder_cost'] ?? 0, 2); ?></td>
                        <td class="text-right calculated"><?php echo number_format($entry['cylinder_cost_percent'] ?? 0, 2); ?>%</td>
                        <td class="text-right calculated <?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>
                    </tr>
                    <?php endforeach; ?>
                    
                    <!-- TOTAL Row -->
                    <tr class="total-row">
                        <td><strong>TOTAL:</strong></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'cash_sale_net')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'catering_btc_regular')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'catering_btc_extra')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'total_food_sale')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'housekeeping_lumpsum')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'laundry')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'total_sale')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'cash_purchase')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'catering_cost')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'total_food_cost')), 2); ?></td>
                        <td class="text-right">
                            <?php 
                            $totalFoodSale = array_sum(array_column($entries, 'total_food_sale'));
                            $totalFoodCost = array_sum(array_column($entries, 'total_food_cost'));
                            $avgFoodCostPercent = $totalFoodSale > 0 ? ($totalFoodCost / $totalFoodSale) * 100 : 0;
                            echo number_format($avgFoodCostPercent, 2); ?>%
                        </td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'housekeeping_cost')), 2); ?></td>
                        <td class="text-right">
                            <?php 
                            $totalCashSale = array_sum(array_column($entries, 'cash_sale_net'));
                            $totalCateringBtc = array_sum(array_column($entries, 'catering_btc_regular')) + array_sum(array_column($entries, 'catering_btc_extra'));
                            $totalHKCost = array_sum(array_column($entries, 'housekeeping_cost'));
                            $avgHKCostPercent = ($totalCashSale + $totalCateringBtc) > 0 ? ($totalHKCost / ($totalCashSale + $totalCateringBtc)) * 100 : 0;
                            echo number_format($avgHKCostPercent, 2); ?>%
                        </td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'manpower_days')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'manpower_cost')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'odc_cost')), 2); ?></td>
                        <td class="text-right"><?php 
                            $odcCost2Values = array_column($entries, 'odc_cost_2');
                            echo number_format(array_sum($odcCost2Values ?: [0]), 2); 
                        ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'cylinder_quantity')), 2); ?></td>
                        <td class="text-right"><?php echo number_format($period['cylinder_rate'] ?? 0, 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'total_cylinder_cost')), 2); ?></td>
                        <td class="text-right">
                            <?php 
                            $totalSale = array_sum(array_column($entries, 'total_sale'));
                            $totalCylinder = array_sum(array_column($entries, 'total_cylinder_cost'));
                            $avgCylinderPercent = $totalSale > 0 ? ($totalCylinder / $totalSale) * 100 : 0;
                            echo number_format($avgCylinderPercent, 2); ?>%
                        </td>
                        <td class="text-right">
                            <?php 
                            $totalVariation = 0;
                            foreach ($entries as $e) {
                                $var = (($e['variation_type'] ?? 'positive') === 'positive' ? 1 : -1) * ($e['variation_amount'] ?? 0);
                                $totalVariation += $var;
                            }
                            echo ($totalVariation >= 0 ? '+' : '-') . number_format(abs($totalVariation), 2); 
                            ?>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    
    <?php else: ?>
    <!-- Summary Table - All Reports List -->
    <?php if (empty($periods)): ?>
    <div class="alert alert-info" style="background: #d1ecf1; color: #0c5460; padding: 15px; border: 1px solid #bee5eb; border-radius: 4px; margin: 20px 0;">
        <strong>No reports found</strong>
        <?php if (!empty($selectedDate)): ?>
            for date <?php echo date('d M Y', strtotime($selectedDate)); ?>.
        <?php else: ?>
            for <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?>.
        <?php endif; ?>
        <br>
        <a href="<?php echo BASE_URL; ?>/modules/dfc/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
           style="color: #0c5460; text-decoration: underline;">
            Create a new period
        </a>
    </div>
    <?php else: ?>
    
    <h3>
        Reports 
        <?php if (!empty($selectedDate)): ?>
            for Date: <?php echo date('d M Y', strtotime($selectedDate)); ?>
        <?php else: ?>
            for <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?>
        <?php endif; ?>
        (<?php echo count($periods); ?> submission<?php echo count($periods) > 1 ? 's' : ''; ?>)
    </h3>
    
    <!-- Group by Date if multiple submissions -->
    <?php if (count($periods) > 1 && empty($selectedDate)): ?>
        <?php foreach ($periodsByDate as $dateKey => $datePeriods): ?>
        <div style="margin-bottom: 30px;">
            <h4 style="background: #e9ecef; padding: 10px; margin: 0 0 10px 0; border-left: 4px solid #006699;">
                📅 Date: <?php echo date('d M Y', strtotime($dateKey)); ?> 
                (<?php echo count($datePeriods); ?> submission<?php echo count($datePeriods) > 1 ? 's' : ''; ?>)
            </h4>
            
            <table class="report-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Period Name</th>
                        <th>From Date</th>
                        <th>To Date</th>
                        <th>Total Sale</th>
                        <th>Total Food Cost</th>
                        <th>Total Manpower</th>
                        <th>Total Cylinder</th>
                        <th>Total Variation</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($datePeriods as $index => $p): ?>
                    <tr>
                        <td style="text-align: center; font-weight: bold;"><?php echo $index + 1; ?></td>
                        <td><strong><?php echo htmlspecialchars($p['period_name'] ?: 'N/A'); ?></strong></td>
                        <td><?php echo date('d M Y', strtotime($p['start_date'])); ?></td>
                        <td><?php echo date('d M Y', strtotime($p['end_date'])); ?></td>
                        <td class="text-right">₹<?php echo number_format($p['total_sale'], 2); ?></td>
                        <td class="text-right">₹<?php echo number_format($p['total_food_cost'], 2); ?></td>
                        <td class="text-right">₹<?php echo number_format($p['total_manpower_cost'], 2); ?></td>
                        <td class="text-right">₹<?php echo number_format($p['total_cylinder_cost'], 2); ?></td>
                        <td class="text-right"><strong>₹<?php echo number_format($p['total_variation'], 2); ?></strong></td>
                        <td>
                            <a href="?view=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?><?php echo !empty($selectedDate) ? '&date=' . urlencode($selectedDate) : ''; ?>" 
                               class="btn-view" style="background: #28a745; padding: 6px 12px; border-radius: 4px;">✓ View Details</a>
                            <a href="<?php echo BASE_URL; ?>/modules/dfc/list.php?period_id=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                               class="btn-edit" style="background: #ffc107; color: #000; padding: 6px 12px; border-radius: 4px; text-decoration: none; font-weight: bold;">✏️ Edit</a>
                            <a href="?delete=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?><?php echo !empty($selectedDate) ? '&date=' . urlencode($selectedDate) : ''; ?>" 
                               class="btn-delete" 
                               onclick="return confirm('Are you sure you want to delete this report?\n\nPeriod: <?php echo addslashes($p['period_name']); ?>\n\nThis action cannot be undone!');"
                               style="background: #dc3545; padding: 6px 12px; border-radius: 4px; text-decoration: none;">🗑️ Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endforeach; ?>
    <?php else: ?>
    <!-- Single submission or date filter active -->
    <table class="report-table">
        <thead>
            <tr>
                <th>#</th>
                <th>Period Name</th>
                <th>From Date</th>
                <th>To Date</th>
                <th>Total Sale</th>
                <th>Total Food Cost</th>
                <th>Total Manpower</th>
                <th>Total Cylinder</th>
                <th>Total Variation</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($periods as $index => $p): ?>
            <tr>
                <td style="text-align: center; font-weight: bold;"><?php echo $index + 1; ?></td>
                <td><strong><?php echo htmlspecialchars($p['period_name'] ?: 'N/A'); ?></strong></td>
                <td><?php echo date('d M Y', strtotime($p['start_date'])); ?></td>
                <td><?php echo date('d M Y', strtotime($p['end_date'])); ?></td>
                <td class="text-right">₹<?php echo number_format($p['total_sale'], 2); ?></td>
                <td class="text-right">₹<?php echo number_format($p['total_food_cost'], 2); ?></td>
                <td class="text-right">₹<?php echo number_format($p['total_manpower_cost'], 2); ?></td>
                <td class="text-right">₹<?php echo number_format($p['total_cylinder_cost'], 2); ?></td>
                <td class="text-right"><strong>₹<?php echo number_format($p['total_variation'], 2); ?></strong></td>
                <td>
                    <a href="?view=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?><?php echo !empty($selectedDate) ? '&date=' . urlencode($selectedDate) : ''; ?>" 
                       class="btn-view" style="background: #28a745; padding: 6px 12px; border-radius: 4px;">✓ View Details</a>
                    <a href="<?php echo BASE_URL; ?>/modules/dfc/list.php?period_id=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                       class="btn-edit" style="background: #ffc107; color: #000; padding: 6px 12px; border-radius: 4px; text-decoration: none; font-weight: bold;">✏️ Edit</a>
                    <a href="?delete=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?><?php echo !empty($selectedDate) ? '&date=' . urlencode($selectedDate) : ''; ?>" 
                       class="btn-delete" 
                       onclick="return confirm('Are you sure you want to delete this report?\n\nPeriod: <?php echo addslashes($p['period_name']); ?>\n\nThis action cannot be undone!');"
                       style="background: #dc3545; padding: 6px 12px; border-radius: 4px; text-decoration: none;">🗑️ Delete</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
    <?php endif; ?>
    <?php endif; ?>
</div>

<script>
function filterReport() {
    const month = document.getElementById('filter_month').value;
    const year = document.getElementById('filter_year').value;
    window.location.href = '?month=' + month + '&year=' + year;
}

function filterByDate() {
    const date = document.getElementById('filter_date').value;
    if (date) {
        window.location.href = '?date=' + date;
    } else {
        filterReport();
    }
}

function clearDateFilter() {
    document.getElementById('filter_date').value = '';
    filterReport();
}

function exportToExcel() {
    const date = document.getElementById('filter_date').value;
    const month = document.getElementById('filter_month').value;
    const year = document.getElementById('filter_year').value;
    
    let url = '?export=excel';
    if (date) {
        url += '&date=' + encodeURIComponent(date);
    } else {
        url += '&month=' + month + '&year=' + year;
    }
    
    window.location.href = url;
}
</script>

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

