<?php
/**
 * Enterprise HRM ERP System - MIS Report View
 * Excel-like format matching the provided Excel template
 */

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

$pageTitle = 'MIS Report View';
$currentModule = 'mis';

$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();

// Check permissions
$roleCode = strtolower($_SESSION['role_code'] ?? '');
$canEdit = hasPermission('MIS_EDIT') || in_array($roleCode, ['super_admin', 'hr_admin']);
if (!hasPermission('MIS_VIEW') && !in_array($roleCode, ['super_admin', 'hr_admin'])) {
    $_SESSION['error'] = 'You do not have permission to view 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;
$errors = [];

try {
    $db = getDB();
    
    // Ensure tables exist (create if not)
    try {
        $db->exec("CREATE TABLE IF NOT EXISTS `mis_reports` (
          `mis_id` int(11) NOT NULL AUTO_INCREMENT,
          `site_id` int(11) NOT NULL,
          `report_month` int(11) NOT NULL,
          `report_year` int(11) NOT NULL,
          `entity` varchar(255) DEFAULT 'Divine Food Cravers',
          `segment` varchar(100) DEFAULT 'Industry',
          `location` varchar(100),
          `hm_manager_name` varchar(255),
          `site_accountant_name` varchar(255),
          `operation_head` varchar(255),
          `report_status` enum('draft','final','locked') DEFAULT 'draft',
          `is_locked` tinyint(1) DEFAULT 0,
          `locked_at` datetime,
          `locked_by` int(11),
          `created_by` int(11),
          `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
          `updated_by` int(11),
          `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`mis_id`),
          UNIQUE KEY `unique_site_month_year` (`site_id`, `report_month`, `report_year`),
          KEY `fk_mis_site` (`site_id`),
          KEY `fk_mis_created_by` (`created_by`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    } catch (Exception $e) {
        // Table might already exist, continue
    }
    
    // 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 not in database
    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 view error: " . $e->getMessage());
    $errors[] = 'Error loading MIS report: ' . $e->getMessage();
}

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

<style>
/* Excel-like MIS Report Styles */
.mis-excel-wrapper {
    background: #fff;
    padding: 15px;
    font-family: Arial, sans-serif;
    font-size: 11px;
    overflow-x: auto;
}

.mis-excel-title {
    text-align: center;
    font-size: 16px;
    font-weight: bold;
    padding: 10px;
    background: #f0f0f0;
    border: 1px solid #000;
    margin-bottom: 10px;
}

/* Header Info Table */
.mis-header-table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 10px;
}
.mis-header-table td {
    border: 1px solid #a0a0a0;
    padding: 3px 6px;
    vertical-align: top;
}
.mis-header-table .label-cell {
    background: #d4e6f1;
    font-weight: bold;
    width: 120px;
}
.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: 11px;
}
.mis-excel-table th,
.mis-excel-table td {
    border: 1px solid #808080;
    padding: 3px 5px;
    vertical-align: middle;
}

/* Header cells - Dark teal */
.mis-excel-table .header-cell {
    background: #1a5276;
    color: #fff;
    font-weight: bold;
    text-align: center;
}

/* Section header - Lighter teal */
.mis-excel-table .section-header {
    background: #2980b9;
    color: #fff;
    font-weight: bold;
}

/* Sub-header cells */
.mis-excel-table .sub-header {
    background: #d4e6f1;
    font-weight: bold;
}

/* Total row - Light blue */
.mis-excel-table .total-row {
    background: #aed6f1;
    font-weight: bold;
}

/* Highlight row - Light cyan */
.mis-excel-table .highlight-cyan {
    background: #d1f2eb;
}

/* Green highlight */
.mis-excel-table .highlight-green {
    background: #82e0aa;
}

/* Yellow highlight */
.mis-excel-table .highlight-yellow {
    background: #f9e79f;
}

/* Orange highlight */
.mis-excel-table .highlight-orange {
    background: #f5b041;
}

/* Red for negative values */
.mis-excel-table .negative-value {
    color: #c0392b;
    font-weight: bold;
}

/* Green for positive values */
.mis-excel-table .positive-value {
    color: #196f3d;
    font-weight: bold;
}

/* Right align for amounts */
.mis-excel-table .text-right {
    text-align: right;
}

/* Center align */
.mis-excel-table .text-center {
    text-align: center;
}

/* Two column layout */
.mis-two-col {
    display: flex;
    gap: 10px;
}
.mis-two-col .mis-col {
    flex: 1;
}

/* Small fuel table */
.fuel-table {
    width: 250px;
    font-size: 10px;
}
.fuel-table td {
    padding: 2px 4px;
}
.fuel-table .fuel-header {
    background: #d4e6f1;
    font-weight: bold;
}
.fuel-table .fuel-value {
    background: #fff;
    text-align: right;
}
.fuel-table .fuel-total {
    background: #aed6f1;
    font-weight: bold;
}

/* Print styles */
@media print {
    .card-header { display: none; }
    .btn { display: none !important; }
    .mis-excel-wrapper { padding: 0; }
    body { font-size: 10px; }
}

/* Responsive scroll */
.table-scroll-wrapper {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}
</style>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">MIS Report - <?php echo date('F Y', mktime(0, 0, 0, $misData['report_month'], 1, $misData['report_year'])); ?></h2>
        <div style="display: flex; gap: 10px;">
            <?php if ($canEdit): ?>
            <a href="<?php echo BASE_URL; ?>/modules/mis/edit.php?id=<?php echo $misId; ?>" class="btn btn-secondary">Edit</a>
            <?php endif; ?>
            <a href="<?php echo BASE_URL; ?>/modules/mis/export.php?id=<?php echo $misId; ?>&format=excel" class="btn btn-success">📊 Export Excel</a>
            <a href="<?php echo BASE_URL; ?>/modules/mis/export_pdf.php?id=<?php echo $misId; ?>" target="_blank" class="btn btn-danger" style="background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);">📄 Download PDF</a>
            <a href="<?php echo BASE_URL; ?>/modules/mis/index.php" class="btn btn-secondary">← Back</a>
        </div>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-top: 20px;">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <?php if ($misData): ?>
    <div class="table-scroll-wrapper">
    <div class="mis-excel-wrapper">
        
        <!-- MIS REPORT Title -->
        <div class="mis-excel-title">MIS REPORT</div>
        
        <!-- Header Information Section -->
        <table class="mis-header-table" style="margin-bottom: 15px;">
            <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: 10px;">
                    <thead>
                        <tr>
                            <th class="header-cell" style="width: 200px;">SALES</th>
                            <th class="header-cell" style="width: 120px;">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: 10px;">
                    <thead>
                        <tr>
                            <th class="header-cell" style="width: 150px;">PURCHASE</th>
                            <th class="header-cell" style="width: 80px;">CATERING</th>
                            <th class="header-cell" style="width: 90px;">HK & LAUNDRY</th>
                            <th class="header-cell" style="width: 70px;">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: 10px;">
                    <thead>
                        <tr>
                            <th class="header-cell" colspan="2">LABOUR</th>
                        </tr>
                        <tr>
                            <th class="sub-header" style="width: 250px;"></th>
                            <th class="sub-header text-center" style="width: 100px;">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: 10px;">
                    <tbody>
                        <tr class="total-row">
                            <td style="width: 250px;" class="highlight-cyan"><strong>Total Other Direct Expenses</strong></td>
                            <td class="text-right" style="width: 100px;"><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: 10px;">
                    <thead>
                        <tr>
                            <th class="header-cell" style="width: 140px;">Segment wise purchase Details</th>
                            <th class="header-cell" style="width: 100px;">(Vendor Name)</th>
                            <th class="header-cell" style="width: 100px;">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: 10px;">
                    <thead>
                        <tr>
                            <th class="header-cell" style="width: 180px;">ODC BREAKUP</th>
                            <th class="header-cell" style="width: 80px;">DFC Credit</th>
                            <th class="header-cell" style="width: 80px;">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: 10px;">
                    <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 style="margin-top: 20px; padding: 10px; font-size: 10px; color: #666; border-top: 1px solid #ccc;">
            * Description to be mentioned on the Back page
        </div>
        
        <!-- Signature Section -->
        <table style="width: 100%; margin-top: 20px; border-collapse: collapse;">
            <tr>
                <td style="width: 33%; text-align: center; padding: 10px; border-top: 1px solid #000;">
                    <strong><?php echo htmlspecialchars($misData['hm_manager_name'] ?? ''); ?></strong>
                </td>
                <td style="width: 33%; text-align: center; padding: 10px; border-top: 1px solid #000;">
                    <strong><?php echo htmlspecialchars($misData['site_accountant_name'] ?? ''); ?></strong>
                </td>
                <td style="width: 33%; text-align: center; padding: 10px; border-top: 1px solid #000;">
                    <strong><?php echo htmlspecialchars($misData['operation_head'] ?? ''); ?></strong>
                </td>
            </tr>
        </table>
        
    </div>
    </div>
    <?php else: ?>
    <div class="table-empty" style="margin-top: 30px;">
        <div class="table-empty-icon">📈</div>
        <div class="table-empty-message">MIS report not found</div>
    </div>
    <?php endif; ?>
</div>

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