<?php
/**
 * Enterprise HRM ERP System - MIS Report PDF Export
 * Full Width A4 Size PDF Download
 */

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

$misId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$siteId = getCurrentSiteId();

if ($misId <= 0) {
    $_SESSION['error'] = 'Invalid MIS report ID.';
    header('Location: ' . BASE_URL . '/modules/mis/index.php');
    exit;
}

// Ensure permissions
ensureMisPermissions();
if (!hasPermission('MIS_EXPORT') && !in_array(strtolower($_SESSION['role_code'] ?? ''), ['super_admin', 'hr_admin'])) {
    $_SESSION['error'] = 'You do not have permission to export MIS reports.';
    header('Location: ' . BASE_URL . '/modules/mis/index.php');
    exit;
}

$misData = null;
$salesData = null;
$segmentPurchases = [];
$purchaseData = null;
$odcData = [];
$labourData = null;
$budgetData = [];
$fuelData = null;
$summaryData = null;
$site = null;

try {
    $db = getDB();
    
    // Get MIS report
    $stmt = $db->prepare("SELECT * FROM mis_reports WHERE mis_id = ? AND site_id = ?");
    $stmt->execute([$misId, $siteId]);
    $misData = $stmt->fetch();
    
    if (!$misData) {
        $_SESSION['error'] = 'MIS report not found or you do not have access.';
        header('Location: ' . BASE_URL . '/modules/mis/index.php');
        exit;
    }
    
    // Get site details
    $stmt = $db->prepare("SELECT * FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $site = $stmt->fetch();
    
    // Get sales data
    $stmt = $db->prepare("SELECT * FROM mis_sales WHERE mis_id = ?");
    $stmt->execute([$misId]);
    $salesData = $stmt->fetch();
    
    // Get segment purchases
    $stmt = $db->prepare("SELECT * FROM mis_segment_purchases WHERE mis_id = ? ORDER BY segment_id");
    $stmt->execute([$misId]);
    $segmentPurchases = $stmt->fetchAll();
    
    // Get purchase data
    $stmt = $db->prepare("SELECT * FROM mis_purchases WHERE mis_id = ?");
    $stmt->execute([$misId]);
    $purchaseData = $stmt->fetch();
    
    // Get ODC breakup
    $stmt = $db->prepare("SELECT * FROM mis_odc_breakup WHERE mis_id = ? ORDER BY odc_id");
    $stmt->execute([$misId]);
    $odcData = $stmt->fetchAll();
    
    // Get labour data
    $stmt = $db->prepare("SELECT * FROM mis_labour WHERE mis_id = ?");
    $stmt->execute([$misId]);
    $labourData = $stmt->fetch();
    
    // Get budget vs actual
    $stmt = $db->prepare("SELECT * FROM mis_budget_vs_actual WHERE mis_id = ? ORDER BY budget_id");
    $stmt->execute([$misId]);
    $budgetData = $stmt->fetchAll();
    
    // Get fuel consumption
    $stmt = $db->prepare("SELECT * FROM mis_fuel_consumption WHERE mis_id = ?");
    $stmt->execute([$misId]);
    $fuelData = $stmt->fetch();
    
    // Get summary
    $stmt = $db->prepare("SELECT * FROM mis_summary WHERE mis_id = ?");
    $stmt->execute([$misId]);
    $summaryData = $stmt->fetch();
    
    // Calculate totals
    if ($salesData) {
        $totalSalesSubtotal = ($salesData['variable_sales'] ?? 0) + 
                              ($salesData['catering_sales_bill_to_company'] ?? 0) +
                              ($salesData['laundry_sales_bill_to_company'] ?? 0) +
                              ($salesData['catering_sales_cash'] ?? 0) +
                              ($salesData['laundry_sales_cash'] ?? 0) +
                              ($salesData['saloon_sale_cash'] ?? 0);
        $grandTotalSales = $totalSalesSubtotal + 
                          ($salesData['lumsump'] ?? 0) +
                          ($salesData['fixed_revenue_onetime'] ?? 0) +
                          ($salesData['reimbursement'] ?? 0) +
                          ($salesData['other_income'] ?? 0);
    }
    
    // Calculate segment total
    $totalCreditProcurement = 0;
    foreach ($segmentPurchases as $seg) {
        $totalCreditProcurement += (float)($seg['amount'] ?? 0);
    }
    
    // Calculate ODC totals
    $totalODC_DFC = 0;
    $totalODC_PC = 0;
    foreach ($odcData as $odc) {
        $totalODC_DFC += (float)($odc['dfc_credit'] ?? 0);
        $totalODC_PC += (float)($odc['petty_cash'] ?? 0);
    }
    $totalODC = $totalODC_DFC + $totalODC_PC;
    
    // Calculate consumption
    if ($purchaseData) {
        $consumptionCatering = ($purchaseData['opening_stock_catering'] ?? 0) + 
                              ($purchaseData['purchase_credit_catering'] ?? 0) -
                              ($purchaseData['closing_stock_catering'] ?? 0);
        $costPercentCatering = ($grandTotalSales ?? 0) > 0 ? 
                              ($consumptionCatering / $grandTotalSales * 100) : 0;
    }
    
    // Calculate Labour Total
    $totalLabourCost = ($labourData['gross_salary'] ?? 0) + 
                       ($labourData['laundry_allowance'] ?? 0) +
                       ($labourData['provision_for_bonus'] ?? 0) +
                       ($labourData['provision_for_leave_salary'] ?? 0) +
                       ($labourData['employee_statutory_contribution'] ?? 0) +
                       ($labourData['staff_welfare_expenses'] ?? 0) +
                       ($labourData['dist_head_cost'] ?? 0) +
                       ($labourData['overtime'] ?? 0);
    
    // Calculate GOP
    $gop = ($grandTotalSales ?? 0) - ($consumptionCatering ?? 0) - $totalLabourCost - $totalODC;
    $gopPercent = ($grandTotalSales ?? 0) > 0 ? ($gop / $grandTotalSales * 100) : 0;
    
} catch (Exception $e) {
    error_log("MIS PDF export error: " . $e->getMessage());
    $_SESSION['error'] = 'Error loading MIS report: ' . $e->getMessage();
    header('Location: ' . BASE_URL . '/modules/mis/index.php');
    exit;
}

$monthName = date('F', mktime(0, 0, 0, $misData['report_month'], 1));
$reportTitle = "MIS_Report_{$monthName}_{$misData['report_year']}";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MIS Report - <?php echo $monthName . ' ' . $misData['report_year']; ?></title>
    <style>
        /* Reset and Base Styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        /* A4 Page Setup for Print */
        @page {
            size: A4 landscape;
            margin: 8mm;
        }
        
        @media print {
            html, body {
                width: 297mm;
                height: 210mm;
                margin: 0;
                padding: 0;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                color-adjust: exact !important;
            }
            
            .no-print {
                display: none !important;
            }
            
            .pdf-container {
                width: 100% !important;
                max-width: none !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            
            .mis-excel-wrapper {
                padding: 5mm !important;
                page-break-inside: avoid;
            }
            
            .mis-two-col {
                display: flex !important;
                flex-direction: row !important;
            }
            
            .mis-col {
                flex: 1 !important;
                min-width: 0 !important;
            }
        }
        
        body {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 9px;
            line-height: 1.2;
            background: #f5f5f5;
            color: #000;
        }
        
        /* Download Button */
        .no-print {
            position: fixed;
            top: 10px;
            right: 10px;
            z-index: 1000;
            display: flex;
            gap: 10px;
        }
        
        .btn-download {
            background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(220, 38, 38, 0.4);
            transition: all 0.3s ease;
        }
        
        .btn-download:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(220, 38, 38, 0.5);
        }
        
        .btn-back {
            background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
        }
        
        /* PDF Container */
        .pdf-container {
            width: 297mm;
            max-width: 100%;
            margin: 0 auto;
            background: white;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        
        /* Excel-like MIS Report Styles */
        .mis-excel-wrapper {
            background: #fff;
            padding: 10px;
            font-family: Arial, sans-serif;
            font-size: 9px;
        }
        
        .mis-excel-title {
            text-align: center;
            font-size: 14px;
            font-weight: bold;
            padding: 8px;
            background: #e8e8e8;
            border: 1px solid #000;
            margin-bottom: 8px;
        }
        
        /* Header Info Table */
        .mis-header-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 8px;
        }
        .mis-header-table td {
            border: 1px solid #808080;
            padding: 2px 4px;
            vertical-align: top;
            font-size: 8px;
        }
        .mis-header-table .label-cell {
            background: #d4e6f1;
            font-weight: bold;
            width: 100px;
        }
        .mis-header-table .value-cell {
            background: #fff;
        }
        .mis-header-table .value-cell.highlight {
            background: #c8e6c9;
        }
        
        /* Main Excel Table */
        .mis-excel-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 8px;
        }
        .mis-excel-table th,
        .mis-excel-table td {
            border: 1px solid #808080;
            padding: 2px 3px;
            vertical-align: middle;
        }
        
        /* Header cells - Dark teal */
        .mis-excel-table .header-cell {
            background: #1a5276 !important;
            color: #fff !important;
            font-weight: bold;
            text-align: center;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        /* Section header - Lighter teal */
        .mis-excel-table .section-header {
            background: #2980b9 !important;
            color: #fff !important;
            font-weight: bold;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        /* Sub-header cells */
        .mis-excel-table .sub-header {
            background: #d4e6f1 !important;
            font-weight: bold;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        /* Total row - Light blue */
        .mis-excel-table .total-row {
            background: #aed6f1 !important;
            font-weight: bold;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        /* Highlight row - Light cyan */
        .mis-excel-table .highlight-cyan {
            background: #d1f2eb !important;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        /* Green highlight */
        .mis-excel-table .highlight-green {
            background: #82e0aa !important;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        /* Yellow highlight */
        .mis-excel-table .highlight-yellow {
            background: #f9e79f !important;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        /* Orange highlight */
        .mis-excel-table .highlight-orange {
            background: #f5b041 !important;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        /* Red for negative values */
        .negative-value {
            color: #c0392b !important;
            font-weight: bold;
        }
        
        /* Green for positive values */
        .positive-value {
            color: #196f3d !important;
            font-weight: bold;
        }
        
        /* Right align for amounts */
        .text-right {
            text-align: right;
        }
        
        /* Center align */
        .text-center {
            text-align: center;
        }
        
        /* Two column layout */
        .mis-two-col {
            display: flex;
            gap: 8px;
            width: 100%;
        }
        .mis-two-col .mis-col {
            flex: 1;
            min-width: 0;
        }
        
        /* Small fuel table */
        .fuel-table {
            width: 200px;
            font-size: 8px;
        }
        .fuel-table td {
            padding: 2px 3px;
        }
        .fuel-table .fuel-header {
            background: #d4e6f1 !important;
            font-weight: bold;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        .fuel-table .fuel-value {
            background: #fff;
            text-align: right;
        }
        .fuel-table .fuel-total {
            background: #aed6f1 !important;
            font-weight: bold;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        /* Signature Section */
        .signature-section {
            width: 100%;
            margin-top: 15px;
            border-collapse: collapse;
        }
        .signature-section td {
            width: 33%;
            text-align: center;
            padding: 8px;
            border-top: 1px solid #000;
            font-size: 9px;
        }
        
        /* Footer */
        .footer-note {
            margin-top: 10px;
            padding: 5px;
            font-size: 8px;
            color: #666;
            border-top: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <!-- Download Button (Hidden in Print) -->
    <div class="no-print">
        <button class="btn-download" onclick="downloadPDF()">📄 Download PDF</button>
        <a href="<?php echo BASE_URL; ?>/modules/mis/view.php?id=<?php echo $misId; ?>" class="btn-back">← Back</a>
    </div>
    
    <div class="pdf-container">
        <div class="mis-excel-wrapper">
            
            <!-- MIS REPORT Title -->
            <div class="mis-excel-title">MIS REPORT</div>
            
            <!-- Header Information Section -->
            <table class="mis-header-table">
                <tr>
                    <td class="label-cell">Year</td>
                    <td class="value-cell"><?php echo date('M/y', mktime(0, 0, 0, $misData['report_month'], 1, $misData['report_year'])); ?></td>
                    <td class="label-cell">HM Manager name:</td>
                    <td class="value-cell highlight"><?php echo htmlspecialchars($misData['hm_manager_name'] ?? 'N/A'); ?></td>
                </tr>
                <tr>
                    <td class="label-cell">Site Name</td>
                    <td class="value-cell" style="font-weight: bold;"><?php echo htmlspecialchars($site['site_name'] ?? 'N/A'); ?></td>
                    <td class="label-cell">Site Accountant Name</td>
                    <td class="value-cell highlight"><?php echo htmlspecialchars($misData['site_accountant_name'] ?? 'N/A'); ?></td>
                </tr>
                <tr>
                    <td class="label-cell">Entity</td>
                    <td class="value-cell" style="font-weight: bold; color: #1a5276;"><?php echo htmlspecialchars($misData['entity'] ?? 'Divine Food Cravers'); ?></td>
                    <td class="label-cell">Operation Head</td>
                    <td class="value-cell"><?php echo htmlspecialchars($misData['operation_head'] ?? 'N/A'); ?></td>
                </tr>
                <tr>
                    <td class="label-cell">Segment</td>
                    <td class="value-cell"><?php echo htmlspecialchars($misData['segment'] ?? 'Industry'); ?></td>
                    <td colspan="2" rowspan="3"></td>
                </tr>
                <tr>
                    <td class="label-cell">Site Code</td>
                    <td class="value-cell"><?php echo htmlspecialchars($site['site_code'] ?? 'N/A'); ?></td>
                </tr>
                <tr>
                    <td class="label-cell">Location</td>
                    <td class="value-cell"><?php echo htmlspecialchars($misData['location'] ?? 'N/A'); ?></td>
                </tr>
            </table>
            
            <!-- Main Two Column Layout -->
            <div class="mis-two-col">
                
                <!-- LEFT COLUMN -->
                <div class="mis-col">
                    
                    <!-- SALES Section -->
                    <table class="mis-excel-table" style="margin-bottom: 6px;">
                        <thead>
                            <tr>
                                <th class="header-cell" style="width: 180px;">SALES</th>
                                <th class="header-cell" style="width: 100px;">Amount in Net</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Variable Sales</td>
                                <td class="text-right"><?php echo number_format($salesData['variable_sales'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Catering Sales - Bill to Company</td>
                                <td class="text-right highlight-orange"><?php echo number_format($salesData['catering_sales_bill_to_company'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Laundry Sales-Bill to Company</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Catering Sales -Cash</td>
                                <td class="text-right highlight-orange"><?php echo number_format($salesData['catering_sales_cash'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Laundry Sales-Cash</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Saloon Sale Cash</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr class="total-row">
                                <td><strong>Total</strong></td>
                                <td class="text-right"><strong><?php echo number_format($totalSalesSubtotal ?? 0, 2); ?></strong></td>
                            </tr>
                            <tr>
                                <td>Lumsump</td>
                                <td class="text-right highlight-orange"><?php echo number_format($salesData['lumsump'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Fixed Revenue Onetime</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td class="highlight-cyan">Reimbursement</td>
                                <td class="text-right highlight-green"><?php echo number_format($salesData['reimbursement'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td class="highlight-cyan">Other Income</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Total</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr class="total-row">
                                <td><strong>Total Sales</strong></td>
                                <td class="text-right"><strong><?php echo number_format($grandTotalSales ?? 0, 2); ?></strong></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- PURCHASE Section -->
                    <table class="mis-excel-table" style="margin-bottom: 6px;">
                        <thead>
                            <tr>
                                <th class="header-cell" style="width: 120px;">PURCHASE</th>
                                <th class="header-cell" style="width: 70px;">CATERING</th>
                                <th class="header-cell" style="width: 70px;">HK & LAUNDRY</th>
                                <th class="header-cell" style="width: 60px;">Other</th>
                            </tr>
                            <tr>
                                <th class="sub-header"></th>
                                <th class="sub-header text-center">Amount</th>
                                <th class="sub-header text-center">Amount</th>
                                <th class="sub-header text-center">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Opening Stock</td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Purchase Credit</td>
                                <td class="text-right highlight-orange"><?php echo number_format($purchaseData['purchase_credit_catering'] ?? 0, 2); ?></td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Purchase Dairy</td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Purchase Provision</td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Material In Attach Format</td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Material Out Attach Format</td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td class="highlight-cyan">Closing Stock</td>
                                <td class="text-right highlight-green"><?php echo number_format($purchaseData['closing_stock_catering'] ?? 0, 2); ?></td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr class="total-row">
                                <td><strong>Consumption</strong></td>
                                <td class="text-right"><strong><?php echo number_format($consumptionCatering ?? 0, 2); ?></strong></td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr class="total-row">
                                <td><strong>Cost %</strong></td>
                                <td class="text-right"><strong><?php echo number_format($costPercentCatering ?? 0, 0); ?>%</strong></td>
                                <td class="text-right">%</td>
                                <td class="text-right">%</td>
                            </tr>
                            <tr>
                                <td>Total Purchase Fuel</td>
                                <td class="text-right" colspan="3">-</td>
                            </tr>
                            <tr>
                                <td>Total Purchase Food</td>
                                <td class="text-right" colspan="3"><?php echo number_format($purchaseData['purchase_credit_catering'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Total Consumption</td>
                                <td class="text-right" colspan="3"><?php echo number_format($consumptionCatering ?? 0, 2); ?></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- LABOUR Section -->
                    <table class="mis-excel-table" style="margin-bottom: 6px;">
                        <thead>
                            <tr>
                                <th class="header-cell" colspan="2">LABOUR</th>
                            </tr>
                            <tr>
                                <th class="sub-header" style="width: 200px;"></th>
                                <th class="sub-header text-center" style="width: 80px;">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Gross Salary</td>
                                <td class="text-right highlight-orange"><?php echo number_format($labourData['gross_salary'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>No. of Crew</td>
                                <td class="text-right"><?php echo $labourData['no_of_crew'] ?? 0; ?></td>
                            </tr>
                            <tr>
                                <td>Laundry Allowance</td>
                                <td class="text-right"><?php echo number_format($labourData['laundry_allowance'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Provision for Bonus</td>
                                <td class="text-right"><?php echo number_format($labourData['provision_for_bonus'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Provision for Leave Salary</td>
                                <td class="text-right"><?php echo number_format($labourData['provision_for_leave_salary'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Employee Sat. Contribution (ESI & EPF)</td>
                                <td class="text-right highlight-orange"><?php echo number_format($labourData['employee_statutory_contribution'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Staff Welfare Expenses</td>
                                <td class="text-right"><?php echo number_format($labourData['staff_welfare_expenses'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>DIST HEAD COST</td>
                                <td class="text-right"><?php echo number_format($labourData['dist_head_cost'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td>Overtime</td>
                                <td class="text-right"><?php echo number_format($labourData['overtime'] ?? 0, 2); ?></td>
                            </tr>
                            <tr class="total-row">
                                <td class="highlight-cyan"><strong>Total Labour Cost</strong></td>
                                <td class="text-right"><strong><?php echo number_format($totalLabourCost ?? 0, 2); ?></strong></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- Summary Section -->
                    <table class="mis-excel-table" style="margin-bottom: 6px;">
                        <tbody>
                            <tr class="total-row">
                                <td style="width: 200px;" class="highlight-cyan"><strong>Total Other Direct Expenses</strong></td>
                                <td class="text-right" style="width: 80px;"><strong><?php echo number_format($totalODC ?? 0, 2); ?></strong></td>
                            </tr>
                            <tr>
                                <td colspan="2"></td>
                            </tr>
                            <tr>
                                <td><strong>GOP</strong></td>
                                <td class="text-right <?php echo $gop < 0 ? 'negative-value' : 'positive-value'; ?>">
                                    <strong><?php echo $gop < 0 ? '(' . number_format(abs($gop), 2) . ')' : number_format($gop, 2); ?></strong>
                                </td>
                            </tr>
                            <tr>
                                <td><strong>GOP%</strong></td>
                                <td class="text-right <?php echo $gopPercent < 0 ? 'negative-value' : 'positive-value'; ?>">
                                    <strong><?php echo number_format($gopPercent, 2); ?>%</strong>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2"></td>
                            </tr>
                            <tr>
                                <td class="highlight-yellow">Petty Cash Closing Balance Rs</td>
                                <td class="text-right highlight-green"><?php echo number_format($summaryData['petty_cash_closing_balance'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td class="highlight-yellow">Sales Cash Closing Balance Rs</td>
                                <td class="text-right"></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- Fuel Consumption Report -->
                    <table class="mis-excel-table fuel-table">
                        <thead>
                            <tr>
                                <th class="header-cell" colspan="2">Fuel Consumption Report</th>
                            </tr>
                            <tr>
                                <th class="sub-header"></th>
                                <th class="sub-header text-center">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>No of Cylinder</td>
                                <td class="text-right"><?php echo $fuelData['no_of_cylinders'] ?? 0; ?> Nos</td>
                            </tr>
                            <tr>
                                <td>Credit Purchases</td>
                                <td class="text-right">INR -</td>
                            </tr>
                            <tr>
                                <td>Bio - Gas Purchase</td>
                                <td class="text-right"><?php echo number_format($fuelData['bio_gas_purchase'] ?? 0, 2); ?></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td class="highlight-cyan">Consumption</td>
                                <td class="text-right">INR -</td>
                            </tr>
                            <tr class="total-row">
                                <td>COST %</td>
                                <td class="text-right"><?php echo number_format($fuelData['cost_percent'] ?? 0, 2); ?>%</td>
                            </tr>
                        </tbody>
                    </table>
                    
                </div>
                
                <!-- RIGHT COLUMN -->
                <div class="mis-col">
                    
                    <!-- Segment wise purchase Details -->
                    <table class="mis-excel-table" style="margin-bottom: 6px;">
                        <thead>
                            <tr>
                                <th class="header-cell" style="width: 120px;">Segment wise purchase Details</th>
                                <th class="header-cell" style="width: 80px;">(Vendor Name)</th>
                                <th class="header-cell" style="width: 80px;">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $defaultSegments = [
                                'Provision and Dry', 'Bakes', 'Dairy', 'Sweets', 'Soft Drinks',
                                'Ice Cream', 'Non Vegitable', 'Vegitable', 'Angul Vegetables',
                                'Dispossible', 'Housekeeping', 'Fuel & Gas', 'Bio Gas'
                            ];
                            foreach ($defaultSegments as $segName):
                                $found = false;
                                $vendor = '';
                                $amount = 0;
                                foreach ($segmentPurchases as $seg) {
                                    if (strtolower($seg['segment_name']) === strtolower($segName)) {
                                        $found = true;
                                        $vendor = $seg['vendor_name'] ?? '';
                                        $amount = $seg['amount'] ?? 0;
                                        break;
                                    }
                                }
                            ?>
                            <tr>
                                <td><?php echo htmlspecialchars($segName); ?></td>
                                <td class="highlight-orange"><?php echo htmlspecialchars($vendor); ?></td>
                                <td class="text-right highlight-orange"><?php echo $amount > 0 ? number_format($amount, 2) : '-'; ?></td>
                            </tr>
                            <?php endforeach; ?>
                            <tr class="total-row">
                                <td colspan="2"><strong>Total Credit Procurement</strong></td>
                                <td class="text-right"><strong><?php echo number_format($totalCreditProcurement, 2); ?></strong></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- ODC BREAKUP Section -->
                    <table class="mis-excel-table" style="margin-bottom: 6px;">
                        <thead>
                            <tr>
                                <th class="header-cell" style="width: 150px;">ODC BREAKUP</th>
                                <th class="header-cell" style="width: 70px;">DFC Credit</th>
                                <th class="header-cell" style="width: 70px;">Petty Cash</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $defaultODC = [
                                'Traveling & Conveyance Exp. To',
                                'Commission on Sales @',
                                'Purchase catering',
                                'Courier Charges',
                                'Telphone & Internet Charges',
                                'Decoration Charges',
                                'Housekeeping',
                                'Electricity Client',
                                'Water Charges',
                                'Fuel & Gas',
                                'Repair & Maint.- Gas Line & othe',
                                'Printing & Stationery Materials',
                                'Staff & Welfare',
                                'Staff Accomodation & Electricity',
                                'AMC-Charges',
                                'Depreciation',
                                'Dispossibale Exp.',
                                'Books & Periodicals',
                                'Crockery & Cuttlery',
                                'Other Direct Expenses',
                                'Garbage Dispose',
                                'Impres Money Commision',
                                'Uniform',
                                'Festival Expenses'
                            ];
                            foreach ($defaultODC as $odcName):
                                $found = false;
                                $dfcCredit = 0;
                                $pettyCash = 0;
                                foreach ($odcData as $odc) {
                                    if (stripos($odc['expense_category'], $odcName) !== false || 
                                        stripos($odcName, $odc['expense_category']) !== false) {
                                        $found = true;
                                        $dfcCredit = $odc['dfc_credit'] ?? 0;
                                        $pettyCash = $odc['petty_cash'] ?? 0;
                                        break;
                                    }
                                }
                            ?>
                            <tr>
                                <td><?php echo htmlspecialchars($odcName); ?></td>
                                <td class="text-right"><?php echo $dfcCredit > 0 ? number_format($dfcCredit, 2) : '0.00'; ?></td>
                                <td class="text-right highlight-orange"><?php echo $pettyCash > 0 ? number_format($pettyCash, 2) : '0.00'; ?></td>
                            </tr>
                            <?php endforeach; ?>
                            <tr class="total-row">
                                <td><strong>Total Expenses Amount</strong></td>
                                <td class="text-right"><strong><?php echo number_format($totalODC_DFC, 2); ?></strong></td>
                                <td class="text-right"><strong><?php echo number_format($totalODC_PC, 2); ?></strong></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- Budget Vs DBR Section -->
                    <table class="mis-excel-table" style="margin-bottom: 6px;">
                        <thead>
                            <tr>
                                <th class="header-cell" colspan="3">Budget Vs DBR</th>
                            </tr>
                            <tr>
                                <th class="sub-header"></th>
                                <th class="sub-header text-center">Budget</th>
                                <th class="sub-header text-center">Actual</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $budgetCategories = [
                                'sales' => ['label' => 'Sales', 'actual' => $grandTotalSales ?? 0, 'color' => '#f5b041'],
                                'consumption' => ['label' => 'Consumption', 'actual' => $consumptionCatering ?? 0, 'color' => '#f5b041'],
                                'labour_cost' => ['label' => 'Labour Cost', 'actual' => $totalLabourCost ?? 0, 'color' => '#f5b041'],
                                'other_expenses' => ['label' => 'Other Expenses', 'actual' => $totalODC ?? 0, 'color' => '#f5b041'],
                                'depreciation' => ['label' => 'Depreciation', 'actual' => 0, 'color' => ''],
                                'ce' => ['label' => 'CE', 'actual' => $gop ?? 0, 'color' => $gop < 0 ? '#c0392b' : '#27ae60']
                            ];
                            foreach ($budgetCategories as $key => $cat):
                                $budgetVal = 'FALSE';
                                foreach ($budgetData as $bud) {
                                    if (strtolower($bud['category']) === $key) {
                                        $budgetVal = $bud['budget_amount'] > 0 ? number_format($bud['budget_amount'], 2) : 'FALSE';
                                        break;
                                    }
                                }
                            ?>
                            <tr>
                                <td class="<?php echo $cat['color'] == '#f5b041' ? 'highlight-orange' : ($cat['color'] == '#c0392b' ? 'negative-value' : ($cat['color'] == '#27ae60' ? 'positive-value' : '')); ?>"><?php echo $cat['label']; ?></td>
                                <td class="text-center highlight-yellow"><?php echo $budgetVal; ?></td>
                                <td class="text-right">INR <?php echo number_format($cat['actual'], 2); ?></td>
                            </tr>
                            <?php endforeach; ?>
                            <tr>
                                <td></td>
                                <td class="text-center highlight-yellow">#DIV/0!</td>
                                <td class="text-right negative-value"><?php echo number_format($gopPercent, 0); ?>%</td>
                            </tr>
                        </tbody>
                    </table>
                    
                </div>
            </div>
            
            <!-- Footer Note -->
            <div class="footer-note">
                * Description to be mentioned on the Back page
            </div>
            
            <!-- Signature Section -->
            <table class="signature-section">
                <tr>
                    <td>
                        <strong><?php echo htmlspecialchars($misData['hm_manager_name'] ?? ''); ?></strong><br>
                        <small>HM Manager</small>
                    </td>
                    <td>
                        <strong><?php echo htmlspecialchars($misData['site_accountant_name'] ?? ''); ?></strong><br>
                        <small>Site Accountant</small>
                    </td>
                    <td>
                        <strong><?php echo htmlspecialchars($misData['operation_head'] ?? ''); ?></strong><br>
                        <small>Operation Head</small>
                    </td>
                </tr>
            </table>
            
        </div>
    </div>
    
    <script>
        function downloadPDF() {
            // Set document title for PDF filename
            var originalTitle = document.title;
            document.title = '<?php echo $reportTitle; ?>';
            
            // Trigger browser print dialog (user can save as PDF)
            window.print();
            
            // Restore original title
            setTimeout(function() {
                document.title = originalTitle;
            }, 1000);
        }
        
        // Auto-trigger download on page load if requested
        window.onload = function() {
            // Check if auto-download is requested
            var urlParams = new URLSearchParams(window.location.search);
            if (urlParams.get('auto') === '1') {
                setTimeout(downloadPDF, 500);
            }
        };
    </script>
</body>
</html>

