<?php
/**
 * Enterprise HRM ERP System - Comprehensive MIS Report
 * Excel-like format with all sections
 */

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

// Check permissions
if (!hasPermission('REPORTS_VIEW') && !hasAdminAccess()) {
    $_SESSION['error'] = 'You do not have permission to view MIS reports.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'MIS Report - Comprehensive';
$currentModule = 'mis';

$siteId = getCurrentSiteId();
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Validate
if ($selectedMonth < 1 || $selectedMonth > 12) $selectedMonth = (int)date('m');
if ($selectedYear < 2020 || $selectedYear > 2100) $selectedYear = (int)date('Y');

$errors = [];
$success = false;
$misHeader = null;
$misSales = null;
$misSegmentPurchases = [];
$misPurchases = null;
$misOdc = [];
$misLabour = null;
$misBudget = [];
$misFuel = null;
$misSummary = null;

// Handle form submission (Create/Update MIS Report)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && hasPermission('REPORTS_CREATE')) {
    try {
        $db = getDB();
        $db->beginTransaction();
        
        // Get or create header
        $stmt = $db->prepare("
            SELECT header_id FROM mis_report_headers 
            WHERE site_id = ? AND report_month = ? AND report_year = ?
        ");
        $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
        $existingHeader = $stmt->fetch();
        
        if ($existingHeader) {
            $headerId = $existingHeader['header_id'];
            // Update header
            $stmt = $db->prepare("
                UPDATE mis_report_headers SET
                    entity_name = ?, segment = ?, location = ?,
                    hm_manager_name = ?, site_accountant_name = ?, operation_head = ?,
                    updated_at = NOW()
                WHERE header_id = ?
            ");
            $stmt->execute([
                sanitize($_POST['entity_name'] ?? ''),
                sanitize($_POST['segment'] ?? ''),
                sanitize($_POST['location'] ?? ''),
                sanitize($_POST['hm_manager_name'] ?? ''),
                sanitize($_POST['site_accountant_name'] ?? ''),
                sanitize($_POST['operation_head'] ?? ''),
                $headerId
            ]);
        } else {
            // Create header
            $stmt = $db->prepare("
                INSERT INTO mis_report_headers 
                (site_id, report_month, report_year, entity_name, segment, location,
                 hm_manager_name, site_accountant_name, operation_head, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $siteId, $selectedMonth, $selectedYear,
                sanitize($_POST['entity_name'] ?? ''),
                sanitize($_POST['segment'] ?? ''),
                sanitize($_POST['location'] ?? ''),
                sanitize($_POST['hm_manager_name'] ?? ''),
                sanitize($_POST['site_accountant_name'] ?? ''),
                sanitize($_POST['operation_head'] ?? ''),
                getCurrentUserId()
            ]);
            $headerId = $db->lastInsertId();
        }
        
        // Save Sales
        $stmt = $db->prepare("
            INSERT INTO mis_sales 
            (header_id, variable_sales, catering_sales_bill_to_company, laundry_sales_bill_to_company,
             catering_sales_cash, laundry_sales_cash, saloon_sale_cash, lumsump,
             fixed_revenue_onetime, reimbursement, other_income)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                variable_sales = VALUES(variable_sales),
                catering_sales_bill_to_company = VALUES(catering_sales_bill_to_company),
                laundry_sales_bill_to_company = VALUES(laundry_sales_bill_to_company),
                catering_sales_cash = VALUES(catering_sales_cash),
                laundry_sales_cash = VALUES(laundry_sales_cash),
                saloon_sale_cash = VALUES(saloon_sale_cash),
                lumsump = VALUES(lumsump),
                fixed_revenue_onetime = VALUES(fixed_revenue_onetime),
                reimbursement = VALUES(reimbursement),
                other_income = VALUES(other_income),
                updated_at = NOW()
        ");
        $stmt->execute([
            $headerId,
            (float)($_POST['variable_sales'] ?? 0),
            (float)($_POST['catering_sales_bill_to_company'] ?? 0),
            (float)($_POST['laundry_sales_bill_to_company'] ?? 0),
            (float)($_POST['catering_sales_cash'] ?? 0),
            (float)($_POST['laundry_sales_cash'] ?? 0),
            (float)($_POST['saloon_sale_cash'] ?? 0),
            (float)($_POST['lumsump'] ?? 0),
            (float)($_POST['fixed_revenue_onetime'] ?? 0),
            (float)($_POST['reimbursement'] ?? 0),
            (float)($_POST['other_income'] ?? 0)
        ]);
        
        // Calculate and update sales totals
        $stmt = $db->prepare("
            UPDATE mis_sales SET
                total_sales_subtotal = variable_sales + catering_sales_bill_to_company + 
                    laundry_sales_bill_to_company + catering_sales_cash + 
                    laundry_sales_cash + saloon_sale_cash,
                total_sales = variable_sales + catering_sales_bill_to_company + 
                    laundry_sales_bill_to_company + catering_sales_cash + 
                    laundry_sales_cash + saloon_sale_cash + lumsump + 
                    fixed_revenue_onetime + reimbursement + other_income
            WHERE header_id = ?
        ");
        $stmt->execute([$headerId]);
        
        // Save Purchases
        $stmt = $db->prepare("
            INSERT INTO mis_purchases 
            (header_id, opening_stock_catering, opening_stock_hk_laundry, opening_stock_other,
             purchase_credit_catering, purchase_credit_hk_laundry, purchase_credit_other,
             purchase_dairy_catering, purchase_dairy_hk_laundry, purchase_dairy_other,
             purchase_provision_catering, purchase_provision_hk_laundry, purchase_provision_other,
             material_in_attach_format_catering, material_in_attach_format_hk_laundry, material_in_attach_format_other,
             material_out_attach_format_catering, material_out_attach_format_hk_laundry, material_out_attach_format_other,
             closing_stock_catering, closing_stock_hk_laundry, closing_stock_other,
             total_purchase_fuel)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                opening_stock_catering = VALUES(opening_stock_catering),
                opening_stock_hk_laundry = VALUES(opening_stock_hk_laundry),
                opening_stock_other = VALUES(opening_stock_other),
                purchase_credit_catering = VALUES(purchase_credit_catering),
                purchase_credit_hk_laundry = VALUES(purchase_credit_hk_laundry),
                purchase_credit_other = VALUES(purchase_credit_other),
                purchase_dairy_catering = VALUES(purchase_dairy_catering),
                purchase_dairy_hk_laundry = VALUES(purchase_dairy_hk_laundry),
                purchase_dairy_other = VALUES(purchase_dairy_other),
                purchase_provision_catering = VALUES(purchase_provision_catering),
                purchase_provision_hk_laundry = VALUES(purchase_provision_hk_laundry),
                purchase_provision_other = VALUES(purchase_provision_other),
                material_in_attach_format_catering = VALUES(material_in_attach_format_catering),
                material_in_attach_format_hk_laundry = VALUES(material_in_attach_format_hk_laundry),
                material_in_attach_format_other = VALUES(material_in_attach_format_other),
                material_out_attach_format_catering = VALUES(material_out_attach_format_catering),
                material_out_attach_format_hk_laundry = VALUES(material_out_attach_format_hk_laundry),
                material_out_attach_format_other = VALUES(material_out_attach_format_other),
                closing_stock_catering = VALUES(closing_stock_catering),
                closing_stock_hk_laundry = VALUES(closing_stock_hk_laundry),
                closing_stock_other = VALUES(closing_stock_other),
                total_purchase_fuel = VALUES(total_purchase_fuel),
                updated_at = NOW()
        ");
        $stmt->execute([
            $headerId,
            (float)($_POST['opening_stock_catering'] ?? 0),
            (float)($_POST['opening_stock_hk_laundry'] ?? 0),
            (float)($_POST['opening_stock_other'] ?? 0),
            (float)($_POST['purchase_credit_catering'] ?? 0),
            (float)($_POST['purchase_credit_hk_laundry'] ?? 0),
            (float)($_POST['purchase_credit_other'] ?? 0),
            (float)($_POST['purchase_dairy_catering'] ?? 0),
            (float)($_POST['purchase_dairy_hk_laundry'] ?? 0),
            (float)($_POST['purchase_dairy_other'] ?? 0),
            (float)($_POST['purchase_provision_catering'] ?? 0),
            (float)($_POST['purchase_provision_hk_laundry'] ?? 0),
            (float)($_POST['purchase_provision_other'] ?? 0),
            (float)($_POST['material_in_attach_format_catering'] ?? 0),
            (float)($_POST['material_in_attach_format_hk_laundry'] ?? 0),
            (float)($_POST['material_in_attach_format_other'] ?? 0),
            (float)($_POST['material_out_attach_format_catering'] ?? 0),
            (float)($_POST['material_out_attach_format_hk_laundry'] ?? 0),
            (float)($_POST['material_out_attach_format_other'] ?? 0),
            (float)($_POST['closing_stock_catering'] ?? 0),
            (float)($_POST['closing_stock_hk_laundry'] ?? 0),
            (float)($_POST['closing_stock_other'] ?? 0),
            (float)($_POST['total_purchase_fuel'] ?? 0)
        ]);
        
        // Calculate consumption and cost %
        $stmt = $db->prepare("
            UPDATE mis_purchases SET
                consumption_catering = opening_stock_catering + purchase_credit_catering + 
                    purchase_dairy_catering + purchase_provision_catering + 
                    material_in_attach_format_catering - material_out_attach_format_catering - 
                    closing_stock_catering,
                consumption_hk_laundry = opening_stock_hk_laundry + purchase_credit_hk_laundry + 
                    purchase_dairy_hk_laundry + purchase_provision_hk_laundry + 
                    material_in_attach_format_hk_laundry - material_out_attach_format_hk_laundry - 
                    closing_stock_hk_laundry,
                consumption_other = opening_stock_other + purchase_credit_other + 
                    purchase_dairy_other + purchase_provision_other + 
                    material_in_attach_format_other - material_out_attach_format_other - 
                    closing_stock_other,
                total_purchase_food = purchase_credit_catering + purchase_dairy_catering + purchase_provision_catering,
                total_consumption = (opening_stock_catering + purchase_credit_catering + 
                    purchase_dairy_catering + purchase_provision_catering + 
                    material_in_attach_format_catering - material_out_attach_format_catering - 
                    closing_stock_catering)
            WHERE header_id = ?
        ");
        $stmt->execute([$headerId]);
        
        // Update cost % (will be calculated based on sales)
        $stmt = $db->prepare("
            UPDATE mis_purchases p
            INNER JOIN mis_sales s ON p.header_id = s.header_id
            SET p.cost_percent_catering = CASE 
                WHEN s.total_sales > 0 THEN (p.consumption_catering / s.total_sales) * 100 
                ELSE 0 
            END
            WHERE p.header_id = ?
        ");
        $stmt->execute([$headerId]);
        
        // Save Labour
        $stmt = $db->prepare("
            INSERT INTO mis_labour 
            (header_id, gross_salary, no_of_crew, laundry_allowance, provision_for_bonus,
             provision_for_leave_salary, employee_statutory_contribution, staff_welfare_expenses,
             dist_head_cost, overtime)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                gross_salary = VALUES(gross_salary),
                no_of_crew = VALUES(no_of_crew),
                laundry_allowance = VALUES(laundry_allowance),
                provision_for_bonus = VALUES(provision_for_bonus),
                provision_for_leave_salary = VALUES(provision_for_leave_salary),
                employee_statutory_contribution = VALUES(employee_statutory_contribution),
                staff_welfare_expenses = VALUES(staff_welfare_expenses),
                dist_head_cost = VALUES(dist_head_cost),
                overtime = VALUES(overtime),
                updated_at = NOW()
        ");
        $stmt->execute([
            $headerId,
            (float)($_POST['gross_salary'] ?? 0),
            (int)($_POST['no_of_crew'] ?? 0),
            (float)($_POST['laundry_allowance'] ?? 0),
            (float)($_POST['provision_for_bonus'] ?? 0),
            (float)($_POST['provision_for_leave_salary'] ?? 0),
            (float)($_POST['employee_statutory_contribution'] ?? 0),
            (float)($_POST['staff_welfare_expenses'] ?? 0),
            (float)($_POST['dist_head_cost'] ?? 0),
            (float)($_POST['overtime'] ?? 0)
        ]);
        
        // Calculate total labour cost
        $stmt = $db->prepare("
            UPDATE mis_labour SET
                total_labour_cost = gross_salary + laundry_allowance + provision_for_bonus +
                    provision_for_leave_salary + employee_statutory_contribution +
                    staff_welfare_expenses + dist_head_cost + overtime
            WHERE header_id = ?
        ");
        $stmt->execute([$headerId]);
        
        // Save ODC Breakup
        $odcItems = [
            'Traveling & Conveyance Exp. Total',
            'Commission on Sales @',
            'Purchase catering',
            'Courier Charges',
            'Telphone & Internet Charges',
            'Decoration Charges',
            'Housekeeping',
            'Electricity Client',
            'Water Charges',
            'Fuel & Gas',
            'Repair & Maint.- Gas Line & others',
            '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'
        ];
        
        // Delete existing ODC items
        $stmt = $db->prepare("DELETE FROM mis_odc_breakup WHERE header_id = ?");
        $stmt->execute([$headerId]);
        
        // Insert ODC items
        $stmt = $db->prepare("
            INSERT INTO mis_odc_breakup (header_id, expense_name, dfc_credit, petty_cash, display_order)
            VALUES (?, ?, ?, ?, ?)
        ");
        $order = 1;
        foreach ($odcItems as $item) {
            $dfcCredit = (float)($_POST['odc_dfc_' . md5($item)] ?? 0);
            $pettyCash = (float)($_POST['odc_petty_' . md5($item)] ?? 0);
            $stmt->execute([$headerId, $item, $dfcCredit, $pettyCash, $order++]);
        }
        
        // Calculate total ODC
        $stmt = $db->prepare("
            UPDATE mis_summary SET
                total_other_direct_expenses = (
                    SELECT COALESCE(SUM(dfc_credit + petty_cash), 0) 
                    FROM mis_odc_breakup 
                    WHERE header_id = ?
                )
            WHERE header_id = ?
        ");
        $stmt->execute([$headerId, $headerId]);
        
        // Save Fuel Consumption
        $stmt = $db->prepare("
            INSERT INTO mis_fuel_consumption 
            (header_id, no_of_cylinders, credit_purchases, bio_gas_purchase, consumption)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                no_of_cylinders = VALUES(no_of_cylinders),
                credit_purchases = VALUES(credit_purchases),
                bio_gas_purchase = VALUES(bio_gas_purchase),
                consumption = VALUES(consumption),
                updated_at = NOW()
        ");
        $stmt->execute([
            $headerId,
            (int)($_POST['no_of_cylinders'] ?? 0),
            (float)($_POST['fuel_credit_purchases'] ?? 0),
            (float)($_POST['bio_gas_purchase'] ?? 0),
            (float)($_POST['fuel_consumption'] ?? 0)
        ]);
        
        // Calculate and save Summary
        $stmt = $db->prepare("
            INSERT INTO mis_summary 
            (header_id, petty_cash_closing_balance, sales_cash_closing_balance, total_credit_procurement)
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                petty_cash_closing_balance = VALUES(petty_cash_closing_balance),
                sales_cash_closing_balance = VALUES(sales_cash_closing_balance),
                total_credit_procurement = VALUES(total_credit_procurement),
                updated_at = NOW()
        ");
        $stmt->execute([
            $headerId,
            (float)($_POST['petty_cash_closing_balance'] ?? 0),
            (float)($_POST['sales_cash_closing_balance'] ?? 0),
            (float)($_POST['total_credit_procurement'] ?? 0)
        ]);
        
        // Calculate GOP and GOP%
        $stmt = $db->prepare("
            UPDATE mis_summary s
            INNER JOIN mis_sales sales ON s.header_id = sales.header_id
            INNER JOIN mis_purchases p ON s.header_id = p.header_id
            INNER JOIN mis_labour l ON s.header_id = l.header_id
            SET 
                s.gop = sales.total_sales - p.total_consumption - l.total_labour_cost - s.total_other_direct_expenses,
                s.gop_percent = CASE 
                    WHEN sales.total_sales > 0 THEN 
                        ((sales.total_sales - p.total_consumption - l.total_labour_cost - s.total_other_direct_expenses) / sales.total_sales) * 100
                    ELSE 0
                END
            WHERE s.header_id = ?
        ");
        $stmt->execute([$headerId]);
        
        $db->commit();
        $success = true;
        logAudit('CREATE', 'mis_report_headers', $headerId);
        
    } catch (Exception $e) {
        if (isset($db) && $db->inTransaction()) {
            $db->rollBack();
        }
        error_log("MIS save error: " . $e->getMessage());
        $errors[] = 'Error saving MIS report: ' . $e->getMessage();
    }
}

// Load existing MIS data
try {
    $db = getDB();
    
    $stmt = $db->prepare("
        SELECT h.*, s.site_name, s.site_code
        FROM mis_report_headers h
        INNER JOIN sites s ON h.site_id = s.site_id
        WHERE h.site_id = ? AND h.report_month = ? AND h.report_year = ?
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $misHeader = $stmt->fetch();
    
    if ($misHeader) {
        $headerId = $misHeader['header_id'];
        
        // Load Sales
        $stmt = $db->prepare("SELECT * FROM mis_sales WHERE header_id = ?");
        $stmt->execute([$headerId]);
        $misSales = $stmt->fetch();
        
        // Load Segment Purchases
        $stmt = $db->prepare("SELECT * FROM mis_segment_purchases WHERE header_id = ? ORDER BY display_order");
        $stmt->execute([$headerId]);
        $misSegmentPurchases = $stmt->fetchAll();
        
        // Load Purchases
        $stmt = $db->prepare("SELECT * FROM mis_purchases WHERE header_id = ?");
        $stmt->execute([$headerId]);
        $misPurchases = $stmt->fetch();
        
        // Load ODC
        $stmt = $db->prepare("SELECT * FROM mis_odc_breakup WHERE header_id = ? ORDER BY display_order");
        $stmt->execute([$headerId]);
        $misOdc = $stmt->fetchAll();
        
        // Load Labour
        $stmt = $db->prepare("SELECT * FROM mis_labour WHERE header_id = ?");
        $stmt->execute([$headerId]);
        $misLabour = $stmt->fetch();
        
        // Load Budget vs Actual
        $stmt = $db->prepare("SELECT * FROM mis_budget_vs_actual WHERE header_id = ? ORDER BY display_order");
        $stmt->execute([$headerId]);
        $misBudget = $stmt->fetchAll();
        
        // Load Fuel
        $stmt = $db->prepare("SELECT * FROM mis_fuel_consumption WHERE header_id = ?");
        $stmt->execute([$headerId]);
        $misFuel = $stmt->fetch();
        
        // Load Summary
        $stmt = $db->prepare("SELECT * FROM mis_summary WHERE header_id = ?");
        $stmt->execute([$headerId]);
        $misSummary = $stmt->fetch();
    }
    
} catch (Exception $e) {
    error_log("MIS load error: " . $e->getMessage());
    $errors[] = 'Error loading MIS report.';
}

// Get site info
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT site_name, site_code FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $siteInfo = $stmt->fetch();
} catch (Exception $e) {
    $siteInfo = ['site_name' => 'N/A', 'site_code' => 'N/A'];
}

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

<style>
.mis-container {
    background: #fff;
    padding: 20px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.mis-header {
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
    padding: 10px;
    background: #f0f0f0;
}

.mis-section {
    margin-bottom: 20px;
}

.mis-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
}

.mis-table th,
.mis-table td {
    border: 1px solid #ddd;
    padding: 6px 8px;
    text-align: left;
}

.mis-table th {
    background: #e8e8e8;
    font-weight: bold;
    text-align: center;
}

.mis-table .total-row {
    background: #d0e8f0;
    font-weight: bold;
}

.mis-table .highlight-row {
    background: #fff4e6;
}

.mis-table input[type="text"],
.mis-table input[type="number"] {
    width: 100%;
    border: none;
    padding: 4px;
    background: transparent;
}

.mis-table input:focus {
    background: #fff;
    outline: 1px solid #4a90e2;
}

.mis-two-column {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}

.mis-three-column {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 20px;
}

.mis-header-info {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 20px;
}

.mis-header-info .left,
.mis-header-info .right {
    background: #f9fafb;
    padding: 10px;
    border: 1px solid #ddd;
}

.mis-header-info label {
    display: inline-block;
    width: 150px;
    font-weight: bold;
}

.mis-header-info input,
.mis-header-info select {
    width: calc(100% - 160px);
    padding: 4px;
    border: 1px solid #ddd;
}

.form-actions {
    margin-top: 20px;
    text-align: right;
    padding-top: 20px;
    border-top: 2px solid #ddd;
}

.btn-excel {
    background: #217346;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

.btn-excel:hover {
    background: #1a5a35;
}
</style>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">MIS Report - Comprehensive (Excel Format)</h2>
        <div style="display: flex; gap: 10px; align-items: center;">
            <select id="monthSelect" class="form-control" style="width: 120px;" onchange="updateMonthYear()">
                <?php for ($m = 1; $m <= 12; $m++): ?>
                <option value="<?php echo $m; ?>" <?php echo $selectedMonth == $m ? 'selected' : ''; ?>>
                    <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                </option>
                <?php endfor; ?>
            </select>
            <select id="yearSelect" class="form-control" style="width: 100px;" onchange="updateMonthYear()">
                <?php for ($y = date('Y') - 2; $y <= date('Y') + 1; $y++): ?>
                <option value="<?php echo $y; ?>" <?php echo $selectedYear == $y ? 'selected' : ''; ?>>
                    <?php echo $y; ?>
                </option>
                <?php endfor; ?>
            </select>
            <?php if ($misHeader && hasPermission('REPORTS_EXPORT')): ?>
            <a href="<?php echo BASE_URL; ?>/modules/mis/export_comprehensive.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="btn-excel">📊 Export to Excel</a>
            <?php endif; ?>
        </div>
    </div>
    
    <?php if ($success): ?>
    <div class="alert alert-success">
        MIS Report saved successfully!
    </div>
    <?php endif; ?>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <div class="mis-container">
        <form method="POST" id="misForm">
            <!-- Header Section -->
            <div class="mis-header">MIS REPORT</div>
            
            <div class="mis-header-info">
                <div class="left">
                    <div style="margin-bottom: 8px;">
                        <label>Year:</label>
                        <input type="text" value="<?php echo date('M/Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?>" readonly>
                    </div>
                    <div style="margin-bottom: 8px;">
                        <label>Site Name:</label>
                        <input type="text" value="<?php echo htmlspecialchars($siteInfo['site_name'] ?? ''); ?>" readonly>
                    </div>
                    <div style="margin-bottom: 8px;">
                        <label>Entity:</label>
                        <input type="text" name="entity_name" value="<?php echo htmlspecialchars($misHeader['entity_name'] ?? ''); ?>">
                    </div>
                    <div style="margin-bottom: 8px;">
                        <label>Segment:</label>
                        <select name="segment">
                            <option value="Hotel" <?php echo ($misHeader['segment'] ?? '') == 'Hotel' ? 'selected' : ''; ?>>Hotel</option>
                            <option value="Industry" <?php echo ($misHeader['segment'] ?? '') == 'Industry' ? 'selected' : ''; ?>>Industry</option>
                            <option value="Education" <?php echo ($misHeader['segment'] ?? '') == 'Education' ? 'selected' : ''; ?>>Education</option>
                            <option value="Healthcare" <?php echo ($misHeader['segment'] ?? '') == 'Healthcare' ? 'selected' : ''; ?>>Healthcare</option>
                            <option value="Corporate" <?php echo ($misHeader['segment'] ?? '') == 'Corporate' ? 'selected' : ''; ?>>Corporate</option>
                            <option value="Guest House" <?php echo ($misHeader['segment'] ?? '') == 'Guest House' ? 'selected' : ''; ?>>Guest House</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 8px;">
                        <label>Site Code:</label>
                        <input type="text" value="<?php echo htmlspecialchars($siteInfo['site_code'] ?? ''); ?>" readonly>
                    </div>
                    <div style="margin-bottom: 8px;">
                        <label>Location:</label>
                        <input type="text" name="location" value="<?php echo htmlspecialchars($misHeader['location'] ?? ''); ?>">
                    </div>
                </div>
                <div class="right">
                    <div style="margin-bottom: 8px;">
                        <label>HM Manager name:</label>
                        <input type="text" name="hm_manager_name" value="<?php echo htmlspecialchars($misHeader['hm_manager_name'] ?? ''); ?>">
                    </div>
                    <div style="margin-bottom: 8px;">
                        <label>Site Accountant Name:</label>
                        <input type="text" name="site_accountant_name" value="<?php echo htmlspecialchars($misHeader['site_accountant_name'] ?? ''); ?>">
                    </div>
                    <div style="margin-bottom: 8px;">
                        <label>Operation Head:</label>
                        <input type="text" name="operation_head" value="<?php echo htmlspecialchars($misHeader['operation_head'] ?? ''); ?>">
                    </div>
                </div>
            </div>
            
            <!-- SALES Section -->
            <div class="mis-section">
                <h3 style="margin-bottom: 10px;">SALES</h3>
                <table class="mis-table">
                    <thead>
                        <tr>
                            <th style="width: 40%;">SALES</th>
                            <th style="width: 20%;">Amount in Net</th>
                            <th style="width: 40%;">Segment wise purchase Details</th>
                            <th style="width: 20%;">Vendor Name</th>
                            <th style="width: 20%;">Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Variable Sales</td>
                            <td><input type="number" name="variable_sales" step="0.01" value="<?php echo $misSales['variable_sales'] ?? 0; ?>"></td>
                            <td>Provision and Dry</td>
                            <td><input type="text" name="segment_vendor_1" value=""></td>
                            <td><input type="number" name="segment_amount_1" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td>Catering Sales - Bill to Company</td>
                            <td><input type="number" name="catering_sales_bill_to_company" step="0.01" value="<?php echo $misSales['catering_sales_bill_to_company'] ?? 0; ?>"></td>
                            <td>Bakes</td>
                            <td><input type="text" name="segment_vendor_2" value=""></td>
                            <td><input type="number" name="segment_amount_2" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td>Laundry Sales-Bill to Company</td>
                            <td><input type="number" name="laundry_sales_bill_to_company" step="0.01" value="<?php echo $misSales['laundry_sales_bill_to_company'] ?? 0; ?>"></td>
                            <td>Dairy</td>
                            <td><input type="text" name="segment_vendor_3" value=""></td>
                            <td><input type="number" name="segment_amount_3" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td>Catering Sales -Cash</td>
                            <td><input type="number" name="catering_sales_cash" step="0.01" value="<?php echo $misSales['catering_sales_cash'] ?? 0; ?>"></td>
                            <td>Sweets</td>
                            <td><input type="text" name="segment_vendor_4" value=""></td>
                            <td><input type="number" name="segment_amount_4" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td>Laundry Sales-Cash</td>
                            <td><input type="number" name="laundry_sales_cash" step="0.01" value="<?php echo $misSales['laundry_sales_cash'] ?? 0; ?>"></td>
                            <td>Soft Drinks</td>
                            <td><input type="text" name="segment_vendor_5" value=""></td>
                            <td><input type="number" name="segment_amount_5" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td>Saloon Sale Cash</td>
                            <td><input type="number" name="saloon_sale_cash" step="0.01" value="<?php echo $misSales['saloon_sale_cash'] ?? 0; ?>"></td>
                            <td>Ice Cream</td>
                            <td><input type="text" name="segment_vendor_6" value=""></td>
                            <td><input type="number" name="segment_amount_6" step="0.01" value=""></td>
                        </tr>
                        <tr class="total-row">
                            <td><strong>Total</strong></td>
                            <td id="total_sales_subtotal"><?php echo number_format($misSales['total_sales_subtotal'] ?? 0, 2); ?></td>
                            <td>Non Vegitable</td>
                            <td><input type="text" name="segment_vendor_7" value=""></td>
                            <td><input type="number" name="segment_amount_7" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td>Lumsump</td>
                            <td><input type="number" name="lumsump" step="0.01" value="<?php echo $misSales['lumsump'] ?? 0; ?>"></td>
                            <td>Vegitable</td>
                            <td><input type="text" name="segment_vendor_8" value=""></td>
                            <td><input type="number" name="segment_amount_8" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td>Fixed Revenue Onetime</td>
                            <td><input type="number" name="fixed_revenue_onetime" step="0.01" value="<?php echo $misSales['fixed_revenue_onetime'] ?? 0; ?>"></td>
                            <td>Angul Vegetables</td>
                            <td><input type="text" name="segment_vendor_9" value=""></td>
                            <td><input type="number" name="segment_amount_9" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td>Reimbursement</td>
                            <td><input type="number" name="reimbursement" step="0.01" value="<?php echo $misSales['reimbursement'] ?? 0; ?>"></td>
                            <td>Dispossible</td>
                            <td><input type="text" name="segment_vendor_10" value=""></td>
                            <td><input type="number" name="segment_amount_10" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td>Other Income</td>
                            <td><input type="number" name="other_income" step="0.01" value="<?php echo $misSales['other_income'] ?? 0; ?>"></td>
                            <td>Housekeeping</td>
                            <td><input type="text" name="segment_vendor_11" value=""></td>
                            <td><input type="number" name="segment_amount_11" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td>Total</td>
                            <td></td>
                            <td>Fuel & Gas</td>
                            <td><input type="text" name="segment_vendor_12" value=""></td>
                            <td><input type="number" name="segment_amount_12" step="0.01" value=""></td>
                        </tr>
                        <tr class="total-row highlight-row">
                            <td><strong>Total Sales</strong></td>
                            <td id="total_sales"><?php echo number_format($misSales['total_sales'] ?? 0, 2); ?></td>
                            <td>Bio Gas</td>
                            <td><input type="text" name="segment_vendor_13" value=""></td>
                            <td><input type="number" name="segment_amount_13" step="0.01" value=""></td>
                        </tr>
                        <tr>
                            <td colspan="2"></td>
                            <td class="total-row"><strong>Total Credit Procurement</strong></td>
                            <td colspan="2" id="total_credit_procurement"><?php echo number_format($misSummary['total_credit_procurement'] ?? 0, 2); ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- Continue with other sections... Due to length, I'll create separate files for the rest -->
            
            <?php if (hasPermission('REPORTS_CREATE') || hasAdminAccess()): ?>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">Save MIS Report</button>
                <a href="<?php echo BASE_URL; ?>/modules/mis/index.php" class="btn btn-secondary">Cancel</a>
            </div>
            <?php endif; ?>
        </form>
    </div>
</div>

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

// Auto-calculate totals
document.addEventListener('DOMContentLoaded', function() {
    const salesInputs = ['variable_sales', 'catering_sales_bill_to_company', 'laundry_sales_bill_to_company', 
                        'catering_sales_cash', 'laundry_sales_cash', 'saloon_sale_cash'];
    
    salesInputs.forEach(inputName => {
        const input = document.querySelector(`input[name="${inputName}"]`);
        if (input) {
            input.addEventListener('input', calculateSalesTotal);
        }
    });
    
    const additionalSales = ['lumsump', 'fixed_revenue_onetime', 'reimbursement', 'other_income'];
    additionalSales.forEach(inputName => {
        const input = document.querySelector(`input[name="${inputName}"]`);
        if (input) {
            input.addEventListener('input', calculateTotalSales);
        }
    });
});

function calculateSalesTotal() {
    const inputs = ['variable_sales', 'catering_sales_bill_to_company', 'laundry_sales_bill_to_company', 
                    'catering_sales_cash', 'laundry_sales_cash', 'saloon_sale_cash'];
    let total = 0;
    inputs.forEach(name => {
        const val = parseFloat(document.querySelector(`input[name="${name}"]`)?.value || 0);
        total += val;
    });
    document.getElementById('total_sales_subtotal').textContent = total.toFixed(2);
    calculateTotalSales();
}

function calculateTotalSales() {
    const subtotal = parseFloat(document.getElementById('total_sales_subtotal').textContent || 0);
    const additional = ['lumsump', 'fixed_revenue_onetime', 'reimbursement', 'other_income'];
    let addTotal = 0;
    additional.forEach(name => {
        const val = parseFloat(document.querySelector(`input[name="${name}"]`)?.value || 0);
        addTotal += val;
    });
    const grandTotal = subtotal + addTotal;
    document.getElementById('total_sales').textContent = grandTotal.toFixed(2);
}
</script>

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

