<?php
/**
 * Enterprise HRM ERP System - MIS Report Create/Edit
 * Excel-like format with all sections, auto-calculations matching the Excel template
 */

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

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

$pageTitle = 'Create/Edit MIS Report';
$currentModule = 'mis';

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

$errors = [];
$success = false;

// Get site details and ensure tables exist
try {
    $db = getDB();
    
    // Create mis_reports table if it doesn't exist (without foreign keys)
    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) {
        error_log("MIS table creation note: " . $e->getMessage());
    }
    
    // Create all MIS related tables if they don't exist
    $tables = [
        "CREATE TABLE IF NOT EXISTS `mis_sales` (
          `sales_id` int(11) NOT NULL AUTO_INCREMENT,
          `mis_id` int(11) NOT NULL,
          `variable_sales` decimal(15,2) DEFAULT 0.00,
          `catering_sales_bill_to_company` decimal(15,2) DEFAULT 0.00,
          `laundry_sales_bill_to_company` decimal(15,2) DEFAULT 0.00,
          `catering_sales_cash` decimal(15,2) DEFAULT 0.00,
          `laundry_sales_cash` decimal(15,2) DEFAULT 0.00,
          `saloon_sale_cash` decimal(15,2) DEFAULT 0.00,
          `lumsump` decimal(15,2) DEFAULT 0.00,
          `fixed_revenue_onetime` decimal(15,2) DEFAULT 0.00,
          `reimbursement` decimal(15,2) DEFAULT 0.00,
          `other_income` decimal(15,2) DEFAULT 0.00,
          `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
          `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`sales_id`),
          UNIQUE KEY `unique_mis_sales` (`mis_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
        
        "CREATE TABLE IF NOT EXISTS `mis_segment_purchases` (
          `segment_id` int(11) NOT NULL AUTO_INCREMENT,
          `mis_id` int(11) NOT NULL,
          `segment_name` varchar(255) NOT NULL,
          `vendor_name` varchar(255),
          `amount` decimal(15,2) DEFAULT 0.00,
          `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
          `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`segment_id`),
          KEY `fk_segment_mis` (`mis_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
        
        "CREATE TABLE IF NOT EXISTS `mis_purchases` (
          `purchase_id` int(11) NOT NULL AUTO_INCREMENT,
          `mis_id` int(11) NOT NULL,
          `opening_stock_catering` decimal(15,2) DEFAULT 0.00,
          `purchase_credit_catering` decimal(15,2) DEFAULT 0.00,
          `purchase_dairy_catering` decimal(15,2) DEFAULT 0.00,
          `purchase_provision_catering` decimal(15,2) DEFAULT 0.00,
          `material_in_attach_format_catering` decimal(15,2) DEFAULT 0.00,
          `material_out_attach_format_catering` decimal(15,2) DEFAULT 0.00,
          `closing_stock_catering` decimal(15,2) DEFAULT 0.00,
          `total_purchase_fuel` decimal(15,2) DEFAULT 0.00,
          `total_purchase_food` decimal(15,2) DEFAULT 0.00,
          `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
          `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`purchase_id`),
          UNIQUE KEY `unique_mis_purchase` (`mis_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
        
        "CREATE TABLE IF NOT EXISTS `mis_odc_breakup` (
          `odc_id` int(11) NOT NULL AUTO_INCREMENT,
          `mis_id` int(11) NOT NULL,
          `expense_category` varchar(255) NOT NULL,
          `dfc_credit` decimal(15,2) DEFAULT 0.00,
          `petty_cash` decimal(15,2) DEFAULT 0.00,
          `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
          `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`odc_id`),
          KEY `fk_odc_mis` (`mis_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
        
        "CREATE TABLE IF NOT EXISTS `mis_labour` (
          `labour_id` int(11) NOT NULL AUTO_INCREMENT,
          `mis_id` int(11) NOT NULL,
          `gross_salary` decimal(15,2) DEFAULT 0.00,
          `no_of_crew` int(11) DEFAULT 0,
          `laundry_allowance` decimal(15,2) DEFAULT 0.00,
          `provision_for_bonus` decimal(15,2) DEFAULT 0.00,
          `provision_for_leave_salary` decimal(15,2) DEFAULT 0.00,
          `employee_statutory_contribution` decimal(15,2) DEFAULT 0.00,
          `staff_welfare_expenses` decimal(15,2) DEFAULT 0.00,
          `dist_head_cost` decimal(15,2) DEFAULT 0.00,
          `overtime` decimal(15,2) DEFAULT 0.00,
          `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
          `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`labour_id`),
          UNIQUE KEY `unique_mis_labour` (`mis_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
        
        "CREATE TABLE IF NOT EXISTS `mis_budget_vs_actual` (
          `budget_id` int(11) NOT NULL AUTO_INCREMENT,
          `mis_id` int(11) NOT NULL,
          `category` varchar(100) NOT NULL,
          `budget_amount` decimal(15,2) DEFAULT 0.00,
          `actual_amount` decimal(15,2) DEFAULT 0.00,
          `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
          `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`budget_id`),
          KEY `fk_budget_mis` (`mis_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
        
        "CREATE TABLE IF NOT EXISTS `mis_fuel_consumption` (
          `fuel_id` int(11) NOT NULL AUTO_INCREMENT,
          `mis_id` int(11) NOT NULL,
          `no_of_cylinders` int(11) DEFAULT 0,
          `credit_purchases` decimal(15,2) DEFAULT 0.00,
          `bio_gas_purchase` decimal(15,2) DEFAULT 0.00,
          `consumption` decimal(15,2) DEFAULT 0.00,
          `cost_percent` decimal(5,2) DEFAULT 0.00,
          `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
          `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`fuel_id`),
          UNIQUE KEY `unique_mis_fuel` (`mis_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
        
        "CREATE TABLE IF NOT EXISTS `mis_summary` (
          `summary_id` int(11) NOT NULL AUTO_INCREMENT,
          `mis_id` int(11) NOT NULL,
          `total_sales` decimal(15,2) DEFAULT 0.00,
          `total_purchase` decimal(15,2) DEFAULT 0.00,
          `total_labour_cost` decimal(15,2) DEFAULT 0.00,
          `total_other_direct_expenses` decimal(15,2) DEFAULT 0.00,
          `gop` decimal(15,2) DEFAULT 0.00,
          `gop_percent` decimal(5,2) DEFAULT 0.00,
          `petty_cash_closing_balance` decimal(15,2) DEFAULT 0.00,
          `sales_cash_closing_balance` decimal(15,2) DEFAULT 0.00,
          `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
          `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`summary_id`),
          UNIQUE KEY `unique_mis_summary` (`mis_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
    ];
    
    foreach ($tables as $sql) {
        try {
            $db->exec($sql);
        } catch (Exception $e) {
            error_log("MIS table creation note: " . $e->getMessage());
        }
    }
    
    $stmt = $db->prepare("SELECT * FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $site = $stmt->fetch();
    
    if (!$site) {
        $_SESSION['error'] = 'Site not found.';
        header('Location: ' . BASE_URL . '/modules/mis/index.php');
        exit;
    }
} catch (Exception $e) {
    error_log("MIS create error: " . $e->getMessage());
    $_SESSION['error'] = 'Error loading site details: ' . $e->getMessage();
    header('Location: ' . BASE_URL . '/modules/mis/index.php');
    exit;
}

// Load existing data if editing
$misData = null;
$salesData = null;
$segmentPurchases = [];
$purchaseData = null;
$odcData = [];
$labourData = null;
$budgetData = [];
$fuelData = null;
$summaryData = null;

if ($isEdit) {
    try {
        $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.';
            header('Location: ' . BASE_URL . '/modules/mis/index.php');
            exit;
        }
        
        if ($misData['is_locked']) {
            $_SESSION['error'] = 'This MIS report is locked and cannot be edited.';
            header('Location: ' . BASE_URL . '/modules/mis/view.php?id=' . $misId);
            exit;
        }
        
        // Load all related data
        $stmt = $db->prepare("SELECT * FROM mis_sales WHERE mis_id = ?");
        $stmt->execute([$misId]);
        $salesData = $stmt->fetch();
        
        $stmt = $db->prepare("SELECT * FROM mis_segment_purchases WHERE mis_id = ?");
        $stmt->execute([$misId]);
        $segmentPurchases = $stmt->fetchAll();
        
        $stmt = $db->prepare("SELECT * FROM mis_purchases WHERE mis_id = ?");
        $stmt->execute([$misId]);
        $purchaseData = $stmt->fetch();
        
        $stmt = $db->prepare("SELECT * FROM mis_odc_breakup WHERE mis_id = ?");
        $stmt->execute([$misId]);
        $odcData = $stmt->fetchAll();
        
        $stmt = $db->prepare("SELECT * FROM mis_labour WHERE mis_id = ?");
        $stmt->execute([$misId]);
        $labourData = $stmt->fetch();
        
        $stmt = $db->prepare("SELECT * FROM mis_budget_vs_actual WHERE mis_id = ?");
        $stmt->execute([$misId]);
        $budgetData = $stmt->fetchAll();
        
        $stmt = $db->prepare("SELECT * FROM mis_fuel_consumption WHERE mis_id = ?");
        $stmt->execute([$misId]);
        $fuelData = $stmt->fetch();
        
        $stmt = $db->prepare("SELECT * FROM mis_summary WHERE mis_id = ?");
        $stmt->execute([$misId]);
        $summaryData = $stmt->fetch();
        
    } catch (Exception $e) {
        error_log("MIS load error: " . $e->getMessage());
        $errors[] = 'Error loading existing data.';
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db = getDB();
        $db->beginTransaction();
        
        $reportMonth = (int)($_POST['report_month'] ?? date('m'));
        $reportYear = (int)($_POST['report_year'] ?? date('Y'));
        
        if ($isEdit) {
            // Update existing report
            $stmt = $db->prepare("
                UPDATE mis_reports SET
                    report_month = ?, report_year = ?,
                    entity = ?, segment = ?, location = ?,
                    hm_manager_name = ?, site_accountant_name = ?, operation_head = ?,
                    updated_by = ?, updated_at = NOW()
                WHERE mis_id = ? AND site_id = ?
            ");
            $stmt->execute([
                $reportMonth, $reportYear,
                sanitize($_POST['entity'] ?? 'Divine Food Cravers'),
                sanitize($_POST['segment'] ?? 'Industry'),
                sanitize($_POST['location'] ?? ''),
                sanitize($_POST['hm_manager_name'] ?? ''),
                sanitize($_POST['site_accountant_name'] ?? ''),
                sanitize($_POST['operation_head'] ?? ''),
                getCurrentUserId(),
                $misId, $siteId
            ]);
        } else {
            // Check if report already exists
            $stmt = $db->prepare("SELECT mis_id FROM mis_reports WHERE site_id = ? AND report_month = ? AND report_year = ?");
            $stmt->execute([$siteId, $reportMonth, $reportYear]);
            $existing = $stmt->fetch();
            
            if ($existing) {
                throw new Exception('MIS report for this month/year already exists.');
            }
            
            // Create new report
            $stmt = $db->prepare("
                INSERT INTO mis_reports (
                    site_id, report_month, report_year,
                    entity, segment, location,
                    hm_manager_name, site_accountant_name, operation_head,
                    created_by
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $siteId, $reportMonth, $reportYear,
                sanitize($_POST['entity'] ?? 'Divine Food Cravers'),
                sanitize($_POST['segment'] ?? 'Industry'),
                sanitize($_POST['location'] ?? ''),
                sanitize($_POST['hm_manager_name'] ?? ''),
                sanitize($_POST['site_accountant_name'] ?? ''),
                sanitize($_POST['operation_head'] ?? ''),
                getCurrentUserId()
            ]);
            $misId = $db->lastInsertId();
        }
        
        // Save/Update Sales
        if ($salesData) {
            $stmt = $db->prepare("
                UPDATE mis_sales SET
                    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 = ?,
                    updated_at = NOW()
                WHERE mis_id = ?
            ");
            $stmt->execute([
                (float)($_POST['variable_sales'] ?? 0),
                (float)($_POST['catering_sales_bill_company'] ?? 0),
                (float)($_POST['laundry_sales_bill_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),
                $misId
            ]);
        } else {
            $stmt = $db->prepare("
                INSERT INTO mis_sales (
                    mis_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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $misId,
                (float)($_POST['variable_sales'] ?? 0),
                (float)($_POST['catering_sales_bill_company'] ?? 0),
                (float)($_POST['laundry_sales_bill_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)
            ]);
        }
        
        // Save/Update Segment Purchases
        $defaultSegments = [
            'provision_dry' => 'Provision and Dry',
            'bakes' => 'Bakes',
            'dairy' => 'Dairy',
            'sweets' => 'Sweets',
            'soft_drinks' => 'Soft Drinks',
            'ice_cream' => 'Ice Cream',
            'non_vegetable' => 'Non Vegitable',
            'vegetable' => 'Vegitable',
            'angul_vegetables' => 'Angul Vegetables',
            'disposable' => 'Dispossible',
            'housekeeping' => 'Housekeeping',
            'fuel_gas' => 'Fuel & Gas',
            'bio_gas' => 'Bio Gas'
        ];
        
        foreach ($defaultSegments as $key => $name) {
            $vendor = sanitize($_POST[$key . '_vendor'] ?? '');
            $amount = (float)($_POST[$key . '_amount'] ?? 0);
            
            // Check if exists
            $stmt = $db->prepare("SELECT segment_id FROM mis_segment_purchases WHERE mis_id = ? AND segment_name = ?");
            $stmt->execute([$misId, $name]);
            $exists = $stmt->fetch();
            
            if ($exists) {
                $stmt = $db->prepare("UPDATE mis_segment_purchases SET vendor_name = ?, amount = ? WHERE mis_id = ? AND segment_name = ?");
                $stmt->execute([$vendor, $amount, $misId, $name]);
            } else {
                $stmt = $db->prepare("INSERT INTO mis_segment_purchases (mis_id, segment_name, vendor_name, amount) VALUES (?, ?, ?, ?)");
                $stmt->execute([$misId, $name, $vendor, $amount]);
            }
        }
        
        // Save/Update Purchase
        if ($purchaseData) {
            $stmt = $db->prepare("
                UPDATE mis_purchases SET
                    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 = ?,
                    updated_at = NOW()
                WHERE mis_id = ?
            ");
            $stmt->execute([
                (float)($_POST['opening_stock_catering'] ?? 0),
                (float)($_POST['purchase_credit_catering'] ?? 0),
                (float)($_POST['purchase_dairy_catering'] ?? 0),
                (float)($_POST['purchase_provision_catering'] ?? 0),
                (float)($_POST['material_in_catering'] ?? 0),
                (float)($_POST['material_out_catering'] ?? 0),
                (float)($_POST['closing_stock_catering'] ?? 0),
                $misId
            ]);
        } else {
            $stmt = $db->prepare("
                INSERT INTO mis_purchases (
                    mis_id, 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
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $misId,
                (float)($_POST['opening_stock_catering'] ?? 0),
                (float)($_POST['purchase_credit_catering'] ?? 0),
                (float)($_POST['purchase_dairy_catering'] ?? 0),
                (float)($_POST['purchase_provision_catering'] ?? 0),
                (float)($_POST['material_in_catering'] ?? 0),
                (float)($_POST['material_out_catering'] ?? 0),
                (float)($_POST['closing_stock_catering'] ?? 0)
            ]);
        }
        
        // Save/Update ODC Breakup
        $defaultODC = [
            'traveling_conveyance' => 'Traveling & Conveyance Exp. To',
            'commission_sales' => 'Commission on Sales @',
            'purchase_catering' => 'Purchase catering',
            'courier_charges' => 'Courier Charges',
            'telephone_internet' => 'Telphone & Internet Charges',
            'decoration_charges' => 'Decoration Charges',
            'housekeeping' => 'Housekeeping',
            'electricity_client' => 'Electricity Client',
            'water_charges' => 'Water Charges',
            'fuel_gas' => 'Fuel & Gas',
            'repair_maintenance' => 'Repair & Maint.- Gas Line & othe',
            'printing_stationary' => 'Printing & Stationary Materials',
            'staff_welfare' => 'Staff & Welfare',
            'staff_accommodation' => 'Staff Accomodation & Electricity',
            'amc_charges' => 'AMC-Charges',
            'depreciation' => 'Depreciation',
            'disposable_exp' => 'Dispossibale Exp.',
            'books_periodicals' => 'Books & Periodicals',
            'crockery_cutlery' => 'Crockery & Cuttlery',
            'other_direct_expenses' => 'Other Direct Expenses',
            'garbage_dispose' => 'Garbage Dispose',
            'impres_money_commission' => 'Impres Money Commision',
            'uniform' => 'Uniform',
            'festival_expenses' => 'Festival Expenses'
        ];
        
        foreach ($defaultODC as $key => $name) {
            $dfcCredit = (float)($_POST[$key . '_dfc'] ?? 0);
            $pettyCash = (float)($_POST[$key . '_pc'] ?? 0);
            
            $stmt = $db->prepare("SELECT odc_id FROM mis_odc_breakup WHERE mis_id = ? AND expense_category = ?");
            $stmt->execute([$misId, $name]);
            $exists = $stmt->fetch();
            
            if ($exists) {
                $stmt = $db->prepare("UPDATE mis_odc_breakup SET dfc_credit = ?, petty_cash = ? WHERE mis_id = ? AND expense_category = ?");
                $stmt->execute([$dfcCredit, $pettyCash, $misId, $name]);
            } else {
                $stmt = $db->prepare("INSERT INTO mis_odc_breakup (mis_id, expense_category, dfc_credit, petty_cash) VALUES (?, ?, ?, ?)");
                $stmt->execute([$misId, $name, $dfcCredit, $pettyCash]);
            }
        }
        
        // Save/Update Labour
        if ($labourData) {
            $stmt = $db->prepare("
                UPDATE mis_labour SET
                    gross_salary = ?, no_of_crew = ?,
                    laundry_allowance = ?, provision_for_bonus = ?,
                    provision_for_leave_salary = ?, employee_statutory_contribution = ?,
                    staff_welfare_expenses = ?, dist_head_cost = ?,
                    overtime = ?,
                    updated_at = NOW()
                WHERE mis_id = ?
            ");
            $stmt->execute([
                (float)($_POST['gross_salary'] ?? 0),
                (int)($_POST['no_of_crew'] ?? 0),
                (float)($_POST['laundry_allowance'] ?? 0),
                (float)($_POST['provision_bonus'] ?? 0),
                (float)($_POST['provision_leave_salary'] ?? 0),
                (float)($_POST['esi_epf'] ?? 0),
                (float)($_POST['staff_welfare'] ?? 0),
                (float)($_POST['dist_head_cost'] ?? 0),
                (float)($_POST['overtime'] ?? 0),
                $misId
            ]);
        } else {
            $stmt = $db->prepare("
                INSERT INTO mis_labour (
                    mis_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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $misId,
                (float)($_POST['gross_salary'] ?? 0),
                (int)($_POST['no_of_crew'] ?? 0),
                (float)($_POST['laundry_allowance'] ?? 0),
                (float)($_POST['provision_bonus'] ?? 0),
                (float)($_POST['provision_leave_salary'] ?? 0),
                (float)($_POST['esi_epf'] ?? 0),
                (float)($_POST['staff_welfare'] ?? 0),
                (float)($_POST['dist_head_cost'] ?? 0),
                (float)($_POST['overtime'] ?? 0)
            ]);
        }
        
        // Calculate totals
        $totalSales = (float)($_POST['total_sales_calculated'] ?? 0);
        $totalConsumption = (float)($_POST['total_consumption_calculated'] ?? 0);
        $totalLabourCost = (float)($_POST['total_labour_cost_calculated'] ?? 0);
        $totalODC = (float)($_POST['total_odc_calculated'] ?? 0);
        $gop = $totalSales - $totalConsumption - $totalLabourCost - $totalODC;
        $gopPercent = $totalSales > 0 ? ($gop / $totalSales * 100) : 0;
        
        // Save/Update Summary
        if ($summaryData) {
            $stmt = $db->prepare("
                UPDATE mis_summary SET
                    total_sales = ?, total_purchase = ?,
                    total_labour_cost = ?, total_other_direct_expenses = ?,
                    gop = ?, gop_percent = ?,
                    petty_cash_closing_balance = ?,
                    sales_cash_closing_balance = ?,
                    updated_at = NOW()
                WHERE mis_id = ?
            ");
            $stmt->execute([
                $totalSales, $totalConsumption,
                $totalLabourCost, $totalODC,
                $gop, $gopPercent,
                (float)($_POST['petty_cash_closing'] ?? 0),
                (float)($_POST['sales_cash_closing'] ?? 0),
                $misId
            ]);
        } else {
            $stmt = $db->prepare("
                INSERT INTO mis_summary (
                    mis_id, total_sales, total_purchase,
                    total_labour_cost, total_other_direct_expenses,
                    gop, gop_percent,
                    petty_cash_closing_balance, sales_cash_closing_balance
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $misId, $totalSales, $totalConsumption,
                $totalLabourCost, $totalODC,
                $gop, $gopPercent,
                (float)($_POST['petty_cash_closing'] ?? 0),
                (float)($_POST['sales_cash_closing'] ?? 0)
            ]);
        }
        
        // Save/Update Fuel Consumption
        if ($fuelData) {
            $stmt = $db->prepare("
                UPDATE mis_fuel_consumption SET
                    no_of_cylinders = ?,
                    credit_purchases = ?, bio_gas_purchase = ?,
                    consumption = ?, cost_percent = ?,
                    updated_at = NOW()
                WHERE mis_id = ?
            ");
            $stmt->execute([
                (int)($_POST['fuel_no_cylinders'] ?? 0),
                (float)($_POST['fuel_credit_purchases'] ?? 0),
                (float)($_POST['fuel_bio_gas'] ?? 0),
                (float)($_POST['fuel_consumption'] ?? 0),
                (float)($_POST['fuel_cost_percent'] ?? 0),
                $misId
            ]);
        } else {
            $stmt = $db->prepare("
                INSERT INTO mis_fuel_consumption (
                    mis_id, no_of_cylinders,
                    credit_purchases, bio_gas_purchase,
                    consumption, cost_percent
                ) VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $misId,
                (int)($_POST['fuel_no_cylinders'] ?? 0),
                (float)($_POST['fuel_credit_purchases'] ?? 0),
                (float)($_POST['fuel_bio_gas'] ?? 0),
                (float)($_POST['fuel_consumption'] ?? 0),
                (float)($_POST['fuel_cost_percent'] ?? 0)
            ]);
        }
        
        // Save/Update Budget Vs Actual
        $defaultBudget = ['sales', 'consumption', 'labour_cost', 'other_expenses', 'depreciation', 'ce'];
        foreach ($defaultBudget as $cat) {
            $budget = sanitize($_POST[$cat . '_budget'] ?? 'FALSE');
            $actual = (float)($_POST[$cat . '_actual'] ?? 0);
            
            $stmt = $db->prepare("SELECT budget_id FROM mis_budget_vs_actual WHERE mis_id = ? AND category = ?");
            $stmt->execute([$misId, $cat]);
            $exists = $stmt->fetch();
            
            if ($exists) {
                $stmt = $db->prepare("UPDATE mis_budget_vs_actual SET budget_amount = ?, actual_amount = ? WHERE mis_id = ? AND category = ?");
                $stmt->execute([$budget === 'FALSE' ? 0 : (float)$budget, $actual, $misId, $cat]);
            } else {
                $stmt = $db->prepare("INSERT INTO mis_budget_vs_actual (mis_id, category, budget_amount, actual_amount) VALUES (?, ?, ?, ?)");
                $stmt->execute([$misId, $cat, $budget === 'FALSE' ? 0 : (float)$budget, $actual]);
            }
        }
        
        $db->commit();
        logAudit($isEdit ? 'UPDATE' : 'CREATE', 'mis_reports', $misId);
        
        $_SESSION['success'] = 'MIS report ' . ($isEdit ? 'updated' : 'created') . ' successfully!';
        header('Location: ' . BASE_URL . '/modules/mis/view.php?id=' . $misId);
        exit;
        
    } catch (Exception $e) {
        if (isset($db) && $db->inTransaction()) {
            $db->rollBack();
        }
        error_log("MIS save error: " . $e->getMessage());
        $errors[] = 'Error saving MIS report: ' . $e->getMessage();
    }
}

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

<style>
/* Excel-like MIS Edit Styles */
.mis-excel-container {
    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: middle;
}
.mis-header-table .label-cell {
    background: #d4e6f1;
    font-weight: bold;
    width: 140px;
}
.mis-header-table .value-cell {
    background: #fff;
}
.mis-header-table input,
.mis-header-table select {
    width: 100%;
    border: 1px solid #ccc;
    padding: 4px;
    font-size: 11px;
}

/* Main Excel Table */
.mis-excel-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 11px;
    margin-bottom: 10px;
}
.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;
}

/* 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;
}

/* Input styling */
.mis-excel-table input[type="text"],
.mis-excel-table input[type="number"] {
    width: 100%;
    border: none;
    padding: 2px 4px;
    font-size: 11px;
    background: transparent;
    text-align: right;
}
.mis-excel-table input:focus {
    outline: 2px solid #3b82f6;
    background: #fff;
}

/* Calculated fields */
.mis-excel-table .calculated-field {
    background: #aed6f1 !important;
    font-weight: bold;
    text-align: right;
}

/* 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;
    min-width: 0;
}

/* Negative value styling */
.negative-value {
    color: #c0392b !important;
}

/* Positive value styling */
.positive-value {
    color: #196f3d !important;
}

/* Responsive */
@media (max-width: 1200px) {
    .mis-two-col {
        flex-direction: column;
    }
}
</style>

<div class="card">
    <div class="card-header">
        <h2 class="card-title"><?php echo $isEdit ? 'Edit' : 'Create'; ?> MIS Report</h2>
        <a href="<?php echo BASE_URL; ?>/modules/mis/index.php" class="btn btn-secondary">← Back to List</a>
    </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; ?>
    
    <form method="POST" id="misForm" style="margin-top: 20px;">
        <div class="mis-excel-container">
            
            <!-- MIS REPORT Title -->
            <div class="mis-excel-title">MIS REPORT</div>
            
            <!-- Header Section -->
            <table class="mis-header-table" style="margin-bottom: 15px;">
                <tr>
                    <td class="label-cell">Year</td>
                    <td class="value-cell">
                        <select name="report_month" style="width: 45%; display: inline-block;">
                            <?php for ($m = 1; $m <= 12; $m++): ?>
                            <option value="<?php echo $m; ?>" <?php echo ($misData && $misData['report_month'] == $m) || (!$misData && $m == date('m')) ? 'selected' : ''; ?>>
                                <?php echo date('M', mktime(0, 0, 0, $m, 1)); ?>
                            </option>
                            <?php endfor; ?>
                        </select>
                        <input type="number" name="report_year" value="<?php echo $misData ? $misData['report_year'] : date('Y'); ?>" style="width: 50%; display: inline-block;" required>
                    </td>
                    <td class="label-cell">HM Manager name:</td>
                    <td class="value-cell"><input type="text" name="hm_manager_name" value="<?php echo htmlspecialchars($misData['hm_manager_name'] ?? ''); ?>"></td>
                </tr>
                <tr>
                    <td class="label-cell">Site Name</td>
                    <td class="value-cell"><input type="text" value="<?php echo htmlspecialchars($site['site_name'] ?? ''); ?>" readonly style="background: #f3f4f6;"></td>
                    <td class="label-cell">Site Accountant Name</td>
                    <td class="value-cell"><input type="text" name="site_accountant_name" value="<?php echo htmlspecialchars($misData['site_accountant_name'] ?? ''); ?>"></td>
                </tr>
                <tr>
                    <td class="label-cell">Entity</td>
                    <td class="value-cell"><input type="text" name="entity" value="<?php echo htmlspecialchars($misData['entity'] ?? 'Divine Food Cravers'); ?>"></td>
                    <td class="label-cell">Operation Head</td>
                    <td class="value-cell"><input type="text" name="operation_head" value="<?php echo htmlspecialchars($misData['operation_head'] ?? ''); ?>"></td>
                </tr>
                <tr>
                    <td class="label-cell">Segment</td>
                    <td class="value-cell">
                        <select name="segment" style="width: 100%;">
                            <option value="Industry" <?php echo ($misData['segment'] ?? '') == 'Industry' ? 'selected' : ''; ?>>Industry</option>
                            <option value="Hotel" <?php echo ($misData['segment'] ?? '') == 'Hotel' ? 'selected' : ''; ?>>Hotel</option>
                            <option value="Education" <?php echo ($misData['segment'] ?? '') == 'Education' ? 'selected' : ''; ?>>Education</option>
                            <option value="Healthcare" <?php echo ($misData['segment'] ?? '') == 'Healthcare' ? 'selected' : ''; ?>>Healthcare</option>
                            <option value="Corporate" <?php echo ($misData['segment'] ?? '') == 'Corporate' ? 'selected' : ''; ?>>Corporate</option>
                        </select>
                    </td>
                    <td colspan="2" rowspan="2"></td>
                </tr>
                <tr>
                    <td class="label-cell">Location</td>
                    <td class="value-cell"><input type="text" name="location" value="<?php echo htmlspecialchars($misData['location'] ?? ''); ?>"></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">
                        <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><input type="number" name="variable_sales" step="0.01" class="sales-input" value="<?php echo number_format($salesData['variable_sales'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Catering Sales - Bill to Company</td>
                                <td class="highlight-orange"><input type="number" name="catering_sales_bill_company" step="0.01" class="sales-input" value="<?php echo number_format($salesData['catering_sales_bill_to_company'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Laundry Sales - Bill to Company</td>
                                <td><input type="number" name="laundry_sales_bill_company" step="0.01" class="sales-input" value="<?php echo number_format($salesData['laundry_sales_bill_to_company'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Catering Sales - Cash</td>
                                <td class="highlight-orange"><input type="number" name="catering_sales_cash" step="0.01" class="sales-input" value="<?php echo number_format($salesData['catering_sales_cash'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Laundry Sales - Cash</td>
                                <td><input type="number" name="laundry_sales_cash" step="0.01" class="sales-input" value="<?php echo number_format($salesData['laundry_sales_cash'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Saloon Sale Cash</td>
                                <td><input type="number" name="saloon_sale_cash" step="0.01" class="sales-input" value="<?php echo number_format($salesData['saloon_sale_cash'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr class="total-row">
                                <td><strong>Total</strong></td>
                                <td class="calculated-field"><span id="sales_subtotal">0.00</span></td>
                            </tr>
                            <tr>
                                <td>Lumsump</td>
                                <td class="highlight-orange"><input type="number" name="lumsump" step="0.01" class="sales-other-input" value="<?php echo number_format($salesData['lumsump'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Fixed Revenue Onetime</td>
                                <td><input type="number" name="fixed_revenue_onetime" step="0.01" class="sales-other-input" value="<?php echo number_format($salesData['fixed_revenue_onetime'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td class="highlight-cyan">Reimbursement</td>
                                <td class="highlight-green"><input type="number" name="reimbursement" step="0.01" class="sales-other-input" value="<?php echo number_format($salesData['reimbursement'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td class="highlight-cyan">Other Income</td>
                                <td><input type="number" name="other_income" step="0.01" class="sales-other-input" value="<?php echo number_format($salesData['other_income'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr class="total-row">
                                <td><strong>Total Sales</strong></td>
                                <td class="calculated-field">
                                    <span id="total_sales_display">0.00</span>
                                    <input type="hidden" name="total_sales_calculated" id="total_sales_calculated" value="0">
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- PURCHASE Section -->
                    <table class="mis-excel-table">
                        <thead>
                            <tr>
                                <th class="header-cell" style="width: 130px;">PURCHASE</th>
                                <th class="header-cell" style="width: 80px;">CATERING</th>
                                <th class="header-cell" style="width: 80px;">HK & LAUNDRY</th>
                                <th class="header-cell" style="width: 70px;">Other</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Opening Stock</td>
                                <td><input type="number" name="opening_stock_catering" step="0.01" class="purchase-input" value="<?php echo number_format($purchaseData['opening_stock_catering'] ?? 0, 2, '.', ''); ?>"></td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Purchase Credit</td>
                                <td class="highlight-orange"><input type="number" name="purchase_credit_catering" step="0.01" class="purchase-input" value="<?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><input type="number" name="purchase_dairy_catering" step="0.01" class="purchase-input" value="<?php echo number_format($purchaseData['purchase_dairy_catering'] ?? 0, 2, '.', ''); ?>"></td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Purchase Provision</td>
                                <td><input type="number" name="purchase_provision_catering" step="0.01" class="purchase-input" value="<?php echo number_format($purchaseData['purchase_provision_catering'] ?? 0, 2, '.', ''); ?>"></td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Material In Attach Format</td>
                                <td><input type="number" name="material_in_catering" step="0.01" class="purchase-input" value="<?php echo number_format($purchaseData['material_in_attach_format_catering'] ?? 0, 2, '.', ''); ?>"></td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td>Material Out Attach Format</td>
                                <td><input type="number" name="material_out_catering" step="0.01" class="purchase-input" value="<?php echo number_format($purchaseData['material_out_attach_format_catering'] ?? 0, 2, '.', ''); ?>"></td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr>
                                <td class="highlight-cyan">Closing Stock</td>
                                <td class="highlight-green"><input type="number" name="closing_stock_catering" step="0.01" class="purchase-input" value="<?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="calculated-field"><span id="consumption_catering">0.00</span></td>
                                <td class="text-right">-</td>
                                <td class="text-right">-</td>
                            </tr>
                            <tr class="total-row">
                                <td><strong>Cost %</strong></td>
                                <td class="calculated-field"><span id="cost_percent_catering">0</span>%</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="calculated-field" colspan="3"><span id="total_purchase_food">0.00</span></td>
                            </tr>
                            <tr>
                                <td>Total Consumption</td>
                                <td class="calculated-field" colspan="3">
                                    <span id="total_consumption_display">0.00</span>
                                    <input type="hidden" name="total_consumption_calculated" id="total_consumption_calculated" value="0">
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- LABOUR Section -->
                    <table class="mis-excel-table">
                        <thead>
                            <tr>
                                <th class="header-cell" colspan="2">LABOUR</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td style="width: 200px;">Gross Salary</td>
                                <td class="highlight-orange"><input type="number" name="gross_salary" step="0.01" class="labour-input" value="<?php echo number_format($labourData['gross_salary'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>No. of Crew</td>
                                <td><input type="number" name="no_of_crew" value="<?php echo $labourData['no_of_crew'] ?? 0; ?>"></td>
                            </tr>
                            <tr>
                                <td>Laundry Allowance</td>
                                <td><input type="number" name="laundry_allowance" step="0.01" class="labour-input" value="<?php echo number_format($labourData['laundry_allowance'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Provision for Bonus</td>
                                <td><input type="number" name="provision_bonus" step="0.01" class="labour-input" value="<?php echo number_format($labourData['provision_for_bonus'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Provision for Leave Salary</td>
                                <td><input type="number" name="provision_leave_salary" step="0.01" class="labour-input" value="<?php echo number_format($labourData['provision_for_leave_salary'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Employee Sat. Contribution (ESI & EPF)</td>
                                <td class="highlight-orange"><input type="number" name="esi_epf" step="0.01" class="labour-input" value="<?php echo number_format($labourData['employee_statutory_contribution'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Staff Welfare Expenses</td>
                                <td><input type="number" name="staff_welfare" step="0.01" class="labour-input" value="<?php echo number_format($labourData['staff_welfare_expenses'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>DIST HEAD COST</td>
                                <td><input type="number" name="dist_head_cost" step="0.01" class="labour-input" value="<?php echo number_format($labourData['dist_head_cost'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Overtime</td>
                                <td><input type="number" name="overtime" step="0.01" class="labour-input" value="<?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="calculated-field">
                                    <span id="total_labour_cost_display">0.00</span>
                                    <input type="hidden" name="total_labour_cost_calculated" id="total_labour_cost_calculated" value="0">
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- Summary Section -->
                    <table class="mis-excel-table">
                        <tbody>
                            <tr class="total-row">
                                <td class="highlight-cyan" style="width: 200px;"><strong>Total Other Direct Expenses</strong></td>
                                <td class="calculated-field">
                                    <span id="total_odc_display">0.00</span>
                                    <input type="hidden" name="total_odc_calculated" id="total_odc_calculated" value="0">
                                </td>
                            </tr>
                            <tr>
                                <td><strong>GOP</strong></td>
                                <td class="calculated-field"><span id="gop_calculated">0.00</span></td>
                            </tr>
                            <tr>
                                <td><strong>GOP%</strong></td>
                                <td class="calculated-field"><span id="gop_percent_calculated">0.00</span>%</td>
                            </tr>
                            <tr>
                                <td class="highlight-yellow">Petty Cash Closing Balance Rs</td>
                                <td class="highlight-green"><input type="number" name="petty_cash_closing" step="0.01" value="<?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><input type="number" name="sales_cash_closing" step="0.01" value="<?php echo number_format($summaryData['sales_cash_closing_balance'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- Fuel Consumption Report -->
                    <table class="mis-excel-table" style="width: 300px;">
                        <thead>
                            <tr>
                                <th class="header-cell" colspan="2">Fuel Consumption Report</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>No of Cylinder</td>
                                <td><input type="number" name="fuel_no_cylinders" value="<?php echo $fuelData['no_of_cylinders'] ?? 0; ?>" style="width: 60px;"> Nos</td>
                            </tr>
                            <tr>
                                <td>Credit Purchases</td>
                                <td>INR <input type="number" name="fuel_credit_purchases" step="0.01" value="<?php echo number_format($fuelData['credit_purchases'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td>Bio - Gas Purchase</td>
                                <td><input type="number" name="fuel_bio_gas" step="0.01" value="<?php echo number_format($fuelData['bio_gas_purchase'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr>
                                <td class="highlight-cyan">Consumption</td>
                                <td>INR <input type="number" name="fuel_consumption" step="0.01" value="<?php echo number_format($fuelData['consumption'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <tr class="total-row">
                                <td>COST %</td>
                                <td><input type="number" name="fuel_cost_percent" step="0.01" value="<?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">
                        <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_dry' => 'Provision and Dry',
                                'bakes' => 'Bakes',
                                'dairy' => 'Dairy',
                                'sweets' => 'Sweets',
                                'soft_drinks' => 'Soft Drinks',
                                'ice_cream' => 'Ice Cream',
                                'non_vegetable' => 'Non Vegitable',
                                'vegetable' => 'Vegitable',
                                'angul_vegetables' => 'Angul Vegetables',
                                'disposable' => 'Dispossible',
                                'housekeeping' => 'Housekeeping',
                                'fuel_gas' => 'Fuel & Gas',
                                'bio_gas' => 'Bio Gas'
                            ];
                            
                            $segmentMap = [];
                            foreach ($segmentPurchases as $seg) {
                                $segmentMap[strtolower($seg['segment_name'])] = $seg;
                            }
                            
                            foreach ($defaultSegments as $key => $name):
                                $segData = $segmentMap[strtolower($name)] ?? null;
                            ?>
                            <tr>
                                <td><?php echo htmlspecialchars($name); ?></td>
                                <td class="highlight-orange"><input type="text" name="<?php echo $key; ?>_vendor" value="<?php echo htmlspecialchars($segData['vendor_name'] ?? ''); ?>" style="text-align: left;"></td>
                                <td class="highlight-orange"><input type="number" name="<?php echo $key; ?>_amount" step="0.01" class="segment-amount" value="<?php echo number_format($segData['amount'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <?php endforeach; ?>
                            <tr class="total-row">
                                <td colspan="2"><strong>Total Credit Procurement</strong></td>
                                <td class="calculated-field"><span id="total_credit_procurement">0.00</span></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- ODC BREAKUP Section -->
                    <table class="mis-excel-table">
                        <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' => 'Traveling & Conveyance Exp. To',
                                'commission_sales' => 'Commission on Sales @',
                                'purchase_catering' => 'Purchase catering',
                                'courier_charges' => 'Courier Charges',
                                'telephone_internet' => 'Telphone & Internet Charges',
                                'decoration_charges' => 'Decoration Charges',
                                'housekeeping' => 'Housekeeping',
                                'electricity_client' => 'Electricity Client',
                                'water_charges' => 'Water Charges',
                                'fuel_gas' => 'Fuel & Gas',
                                'repair_maintenance' => 'Repair & Maint.- Gas Line & othe',
                                'printing_stationary' => 'Printing & Stationery Materials',
                                'staff_welfare' => 'Staff & Welfare',
                                'staff_accommodation' => 'Staff Accomodation & Electricity',
                                'amc_charges' => 'AMC-Charges',
                                'depreciation' => 'Depreciation',
                                'disposable_exp' => 'Dispossibale Exp.',
                                'books_periodicals' => 'Books & Periodicals',
                                'crockery_cutlery' => 'Crockery & Cuttlery',
                                'other_direct_expenses' => 'Other Direct Expenses',
                                'garbage_dispose' => 'Garbage Dispose',
                                'impres_money_commission' => 'Impres Money Commision',
                                'uniform' => 'Uniform',
                                'festival_expenses' => 'Festival Expenses'
                            ];
                            
                            $odcMap = [];
                            foreach ($odcData as $odc) {
                                $odcMap[strtolower($odc['expense_category'])] = $odc;
                            }
                            
                            foreach ($defaultODC as $key => $name):
                                $odcItem = $odcMap[strtolower($name)] ?? null;
                            ?>
                            <tr>
                                <td><?php echo htmlspecialchars($name); ?></td>
                                <td><input type="number" name="<?php echo $key; ?>_dfc" step="0.01" class="odc-dfc-input" value="<?php echo number_format($odcItem['dfc_credit'] ?? 0, 2, '.', ''); ?>"></td>
                                <td class="highlight-orange"><input type="number" name="<?php echo $key; ?>_pc" step="0.01" class="odc-pc-input" value="<?php echo number_format($odcItem['petty_cash'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <?php endforeach; ?>
                            <tr class="total-row">
                                <td><strong>Total Expenses Amount</strong></td>
                                <td class="calculated-field"><span id="total_odc_dfc">0.00</span></td>
                                <td class="calculated-field"><span id="total_odc_pc">0.00</span></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- Budget Vs DBR Section -->
                    <table class="mis-excel-table">
                        <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' => 'Sales',
                                'consumption' => 'Consumption',
                                'labour_cost' => 'Labour Cost',
                                'other_expenses' => 'Other Expenses',
                                'depreciation' => 'Depreciation',
                                'ce' => 'CE'
                            ];
                            $budgetMap = [];
                            foreach ($budgetData as $bud) {
                                $budgetMap[strtolower($bud['category'])] = $bud;
                            }
                            
                            foreach ($budgetCategories as $key => $label):
                                $budItem = $budgetMap[$key] ?? null;
                                $budgetVal = $budItem ? ($budItem['budget_amount'] == 0 ? 'FALSE' : $budItem['budget_amount']) : 'FALSE';
                            ?>
                            <tr>
                                <td class="highlight-orange"><?php echo $label; ?></td>
                                <td class="highlight-yellow text-center"><input type="text" name="<?php echo $key; ?>_budget" value="<?php echo htmlspecialchars($budgetVal); ?>" style="text-align: center;"></td>
                                <td>INR <input type="number" name="<?php echo $key; ?>_actual" step="0.01" id="budget_actual_<?php echo $key; ?>" value="<?php echo number_format($budItem['actual_amount'] ?? 0, 2, '.', ''); ?>"></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                </div>
            </div>
            
            <!-- Action Buttons -->
            <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 2px solid #1a5276;">
                <a href="<?php echo BASE_URL; ?>/modules/mis/index.php" class="btn btn-secondary">Cancel</a>
                <button type="submit" class="btn btn-primary" style="background: #1a5276;"><?php echo $isEdit ? 'Update' : 'Create'; ?> MIS Report</button>
            </div>
        </div>
    </form>
</div>

<script>
// Auto-calculations - Excel Formula Implementation
document.addEventListener('DOMContentLoaded', function() {
    calculateAll();
    
    // Add event listeners for all inputs
    document.querySelectorAll('.sales-input, .sales-other-input').forEach(input => {
        input.addEventListener('input', function() {
            calculateSales();
            updateBudgetActuals();
        });
    });
    
    document.querySelectorAll('.purchase-input').forEach(input => {
        input.addEventListener('input', function() {
            calculatePurchase();
            updateBudgetActuals();
        });
    });
    
    document.querySelectorAll('.labour-input').forEach(input => {
        input.addEventListener('input', function() {
            calculateLabour();
            updateBudgetActuals();
        });
    });
    
    document.querySelectorAll('.segment-amount').forEach(input => {
        input.addEventListener('input', calculateSegmentTotal);
    });
    
    document.querySelectorAll('.odc-dfc-input, .odc-pc-input').forEach(input => {
        input.addEventListener('input', function() {
            calculateODC();
            updateBudgetActuals();
        });
    });
});

// SALES CALCULATION: Total = Sum of all sales line items
function calculateSales() {
    let subtotal = 0;
    document.querySelectorAll('.sales-input').forEach(input => {
        subtotal += parseFloat(input.value) || 0;
    });
    document.getElementById('sales_subtotal').textContent = subtotal.toFixed(2);
    
    let otherTotal = 0;
    document.querySelectorAll('.sales-other-input').forEach(input => {
        otherTotal += parseFloat(input.value) || 0;
    });
    
    let totalSales = subtotal + otherTotal;
    document.getElementById('total_sales_display').textContent = totalSales.toFixed(2);
    document.getElementById('total_sales_calculated').value = totalSales.toFixed(2);
    
    calculatePurchase();
    calculateGOP();
}

// PURCHASE CALCULATION: Consumption = Opening Stock + Purchases - Closing Stock
function calculatePurchase() {
    let openingStock = parseFloat(document.querySelector('[name="opening_stock_catering"]').value) || 0;
    let purchaseCredit = parseFloat(document.querySelector('[name="purchase_credit_catering"]').value) || 0;
    let purchaseDairy = parseFloat(document.querySelector('[name="purchase_dairy_catering"]').value) || 0;
    let purchaseProvision = parseFloat(document.querySelector('[name="purchase_provision_catering"]').value) || 0;
    let materialIn = parseFloat(document.querySelector('[name="material_in_catering"]').value) || 0;
    let materialOut = parseFloat(document.querySelector('[name="material_out_catering"]').value) || 0;
    let closingStock = parseFloat(document.querySelector('[name="closing_stock_catering"]').value) || 0;
    
    // Consumption = Opening + Purchases - Material Out - Closing
    let consumption = openingStock + purchaseCredit + purchaseDairy + purchaseProvision + materialIn - materialOut - closingStock;
    document.getElementById('consumption_catering').textContent = consumption.toFixed(2);
    document.getElementById('total_consumption_display').textContent = consumption.toFixed(2);
    document.getElementById('total_consumption_calculated').value = consumption.toFixed(2);
    
    // Total Purchase Food
    let totalPurchaseFood = purchaseCredit + purchaseDairy + purchaseProvision;
    document.getElementById('total_purchase_food').textContent = totalPurchaseFood.toFixed(2);
    
    // Cost % = (Consumption / Total Sales) * 100
    let totalSales = parseFloat(document.getElementById('total_sales_calculated').value) || 0;
    let costPercent = totalSales > 0 ? (consumption / totalSales * 100) : 0;
    document.getElementById('cost_percent_catering').textContent = costPercent.toFixed(0);
    
    calculateGOP();
}

// LABOUR CALCULATION: Total = Sum of all labour costs
function calculateLabour() {
    let total = 0;
    document.querySelectorAll('.labour-input').forEach(input => {
        total += parseFloat(input.value) || 0;
    });
    document.getElementById('total_labour_cost_display').textContent = total.toFixed(2);
    document.getElementById('total_labour_cost_calculated').value = total.toFixed(2);
    
    calculateGOP();
}

// SEGMENT TOTAL CALCULATION
function calculateSegmentTotal() {
    let total = 0;
    document.querySelectorAll('.segment-amount').forEach(input => {
        total += parseFloat(input.value) || 0;
    });
    document.getElementById('total_credit_procurement').textContent = total.toFixed(2);
}

// ODC CALCULATION: Total = Sum of DFC Credit + Petty Cash
function calculateODC() {
    let totalDFC = 0;
    document.querySelectorAll('.odc-dfc-input').forEach(input => {
        totalDFC += parseFloat(input.value) || 0;
    });
    document.getElementById('total_odc_dfc').textContent = totalDFC.toFixed(2);
    
    let totalPC = 0;
    document.querySelectorAll('.odc-pc-input').forEach(input => {
        totalPC += parseFloat(input.value) || 0;
    });
    document.getElementById('total_odc_pc').textContent = totalPC.toFixed(2);
    
    let totalODC = totalDFC + totalPC;
    document.getElementById('total_odc_display').textContent = totalODC.toFixed(2);
    document.getElementById('total_odc_calculated').value = totalODC.toFixed(2);
    
    calculateGOP();
}

// GOP CALCULATION: GOP = Total Sales - Consumption - Labour Cost - Other Direct Expenses
function calculateGOP() {
    let totalSales = parseFloat(document.getElementById('total_sales_calculated').value) || 0;
    let totalConsumption = parseFloat(document.getElementById('total_consumption_calculated').value) || 0;
    let totalLabourCost = parseFloat(document.getElementById('total_labour_cost_calculated').value) || 0;
    let totalODC = parseFloat(document.getElementById('total_odc_calculated').value) || 0;
    
    let gop = totalSales - totalConsumption - totalLabourCost - totalODC;
    
    // GOP% = (GOP / Total Sales) * 100
    let gopPercent = totalSales > 0 ? (gop / totalSales * 100) : 0;
    
    // Display with color coding
    let gopElement = document.getElementById('gop_calculated');
    let gopPercentElement = document.getElementById('gop_percent_calculated');
    
    if (gop < 0) {
        gopElement.textContent = '(' + Math.abs(gop).toFixed(2) + ')';
        gopElement.className = 'negative-value';
        gopPercentElement.className = 'negative-value';
    } else {
        gopElement.textContent = gop.toFixed(2);
        gopElement.className = 'positive-value';
        gopPercentElement.className = 'positive-value';
    }
    
    gopPercentElement.textContent = gopPercent.toFixed(2);
}

// Update Budget Actual values automatically
function updateBudgetActuals() {
    let totalSales = parseFloat(document.getElementById('total_sales_calculated').value) || 0;
    let totalConsumption = parseFloat(document.getElementById('total_consumption_calculated').value) || 0;
    let totalLabourCost = parseFloat(document.getElementById('total_labour_cost_calculated').value) || 0;
    let totalODC = parseFloat(document.getElementById('total_odc_calculated').value) || 0;
    let gop = totalSales - totalConsumption - totalLabourCost - totalODC;
    
    // Update actual values in Budget Vs DBR
    document.getElementById('budget_actual_sales').value = totalSales.toFixed(2);
    document.getElementById('budget_actual_consumption').value = totalConsumption.toFixed(2);
    document.getElementById('budget_actual_labour_cost').value = totalLabourCost.toFixed(2);
    document.getElementById('budget_actual_other_expenses').value = totalODC.toFixed(2);
    document.getElementById('budget_actual_ce').value = gop.toFixed(2);
}

// Calculate all on page load
function calculateAll() {
    calculateSales();
    calculatePurchase();
    calculateLabour();
    calculateSegmentTotal();
    calculateODC();
    calculateGOP();
    updateBudgetActuals();
}
</script>

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