<?php
/**
 * Enterprise HRM ERP System - Petty Cash Management
 * Excel-like Cash Expenses Summary with Dynamic Table Creation
 */

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

$pageTitle = 'Petty Cash Management';
$currentModule = 'petty_cash';

$siteId = getCurrentSiteId();
$userId = $_SESSION['user_id'];
$roleCode = strtolower($_SESSION['role_code'] ?? '');

// Get parameters
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');
$periodId = isset($_GET['period_id']) ? (int)$_GET['period_id'] : 0;

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

$errors = [];
$success = false;
$period = null;
$entries = [];
$periodDetails = null;

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_petty_cash'])) {
    try {
        $db = getDB();
        $db->beginTransaction();
        
        $fromDate = $_POST['from_date'] ?? '';
        $toDate = $_POST['to_date'] ?? '';
        $periodName = sanitize($_POST['period_name'] ?? '');
        $openingBalance = (float)($_POST['opening_balance'] ?? 0);
        
        if (empty($fromDate) || empty($toDate)) {
            throw new Exception('From Date and To Date are required.');
        }
        
        $month = (int)date('m', strtotime($fromDate));
        $year = (int)date('Y', strtotime($fromDate));
        
        // Create or update period (similar logic to fortnight)
        if (!empty($periodName)) {
            $stmt = $db->prepare("SELECT period_id FROM petty_cash_periods WHERE period_name = ? AND start_date = ? AND end_date = ? AND site_id = ?");
            $stmt->execute([$periodName, $fromDate, $toDate, $siteId]);
            $existingPeriod = $stmt->fetch();
            
            if ($existingPeriod) {
                $periodId = $existingPeriod['period_id'];
                $stmt = $db->prepare("SELECT is_locked FROM petty_cash_periods WHERE period_id = ?");
                $stmt->execute([$periodId]);
                $periodData = $stmt->fetch();
                if ($periodData && $periodData['is_locked']) {
                    throw new Exception('This period is locked and cannot be modified.');
                }
                
                $stmt = $db->prepare("UPDATE petty_cash_periods SET period_name = ?, month = ?, year = ?, opening_balance = ? WHERE period_id = ?");
                $stmt->execute([$periodName, $month, $year, $openingBalance, $periodId]);
            } else {
                $stmt = $db->prepare("INSERT INTO petty_cash_periods (period_name, start_date, end_date, month, year, opening_balance, site_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$periodName, $fromDate, $toDate, $month, $year, $openingBalance, $siteId, $userId]);
                $periodId = $db->lastInsertId();
            }
        } else {
            $uniquePeriodName = 'Period ' . date('d-M-Y', strtotime($fromDate)) . ' to ' . date('d-M-Y', strtotime($toDate)) . ' - ' . date('H:i:s');
            $stmt = $db->prepare("INSERT INTO petty_cash_periods (period_name, start_date, end_date, month, year, opening_balance, site_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$uniquePeriodName, $fromDate, $toDate, $month, $year, $openingBalance, $siteId, $userId]);
            $periodId = $db->lastInsertId();
        }
        
        // Delete existing entries
        $stmt = $db->prepare("DELETE FROM petty_cash_entries WHERE period_id = ?");
        $stmt->execute([$periodId]);
        
        // Save entries
        if (isset($_POST['entries']) && is_array($_POST['entries'])) {
            $srNo = 1;
            foreach ($_POST['entries'] as $row) {
                // Skip empty rows and header/calculation rows
                if (empty($row['entry_date']) && empty($row['description_bill'])) continue;
                
                $entryDate = $row['entry_date'] ?? '';
                if (empty($entryDate)) continue;
                
                $voucherNo = sanitize($row['voucher_no'] ?? '');
                $descriptionBill = sanitize($row['description_bill'] ?? '');
                $totalCashInHand = (float)($row['total_cash_in_hand'] ?? 0);
                $receivedFromFinance = (float)($row['received_from_finance'] ?? 0);
                $otherReceipt = (float)($row['other_receipt'] ?? 0);
                $purchaseCatering = (float)($row['purchase_catering'] ?? 0);
                $purchaseHK = (float)($row['purchase_hk'] ?? 0);
                $maintenance = (float)($row['maintenance'] ?? 0);
                $impresMoneyCommission = (float)($row['impres_money_commission'] ?? 0);
                $printingStationery = (float)($row['printing_stationery'] ?? 0);
                $groceryCutleryRentHire = (float)($row['grocery_cutlery_rent_hire'] ?? 0);
                $mobileTel = (float)($row['mobile_tel'] ?? 0);
                $localConveyance = (float)($row['local_conveyance'] ?? 0);
                $courier = (float)($row['courier'] ?? 0);
                $staffWelfare = (float)($row['staff_welfare'] ?? 0);
                $otherMisc = (float)($row['other_misc'] ?? 0);
                $decorationCharges = (float)($row['decoration_charges'] ?? 0);
                $bankDeposit = (float)($row['bank_deposit'] ?? 0);
                $reimbursableNonReimbursable = sanitize($row['reimbursable_non_reimbursable'] ?? '');
                
                // Calculate Total Cash Out (sum of all expense categories)
                $totalCashOut = round($purchaseCatering + $purchaseHK + $maintenance + $impresMoneyCommission + 
                                     $printingStationery + $groceryCutleryRentHire + $mobileTel + $localConveyance + 
                                     $courier + $staffWelfare + $otherMisc + $decorationCharges, 2);
                
                // Balance In Hand will be calculated in JavaScript/display, stored as 0 for now
                $balanceInHand = 0;
                
                $stmt = $db->prepare("
                    INSERT INTO petty_cash_entries (
                        period_id, entry_date, voucher_no, description_bill,
                        total_cash_in_hand, received_from_finance, other_receipt,
                        total_cash_out, purchase_catering, purchase_hk, maintenance,
                        impres_money_commission, printing_stationery, grocery_cutlery_rent_hire,
                        mobile_tel, local_conveyance, courier, staff_welfare, other_misc,
                        decoration_charges, bank_deposit, balance_in_hand,
                        reimbursable_non_reimbursable, sr_no
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $periodId, $entryDate, $voucherNo, $descriptionBill,
                    $totalCashInHand, $receivedFromFinance, $otherReceipt,
                    $totalCashOut, $purchaseCatering, $purchaseHK, $maintenance,
                    $impresMoneyCommission, $printingStationery, $groceryCutleryRentHire,
                    $mobileTel, $localConveyance, $courier, $staffWelfare, $otherMisc,
                    $decorationCharges, $bankDeposit, $balanceInHand,
                    $reimbursableNonReimbursable, $srNo++
                ]);
            }
        }
        
        // Save period details (remarks, approval, denomination)
        $remarks = sanitize($_POST['remarks'] ?? '');
        $preparedBySignature = sanitize($_POST['prepared_by_signature'] ?? '');
        $preparedByName = sanitize($_POST['prepared_by_name'] ?? '');
        $approvedBySignature = sanitize($_POST['approved_by_signature'] ?? '');
        $approvedByName = sanitize($_POST['approved_by_name'] ?? '');
        $denomination2000 = (int)($_POST['denomination_2000'] ?? 0);
        $denomination500 = (int)($_POST['denomination_500'] ?? 0);
        $denomination200 = (int)($_POST['denomination_200'] ?? 0);
        $denomination100 = (int)($_POST['denomination_100'] ?? 0);
        $denomination50 = (int)($_POST['denomination_50'] ?? 0);
        $denomination20 = (int)($_POST['denomination_20'] ?? 0);
        $denomination10 = (int)($_POST['denomination_10'] ?? 0);
        $denomination5 = (int)($_POST['denomination_5'] ?? 0);
        $denomination2 = (int)($_POST['denomination_2'] ?? 0);
        $denomination1 = (int)($_POST['denomination_1'] ?? 0);
        
        // Calculate total amount from denominations
        $totalAmount = round(($denomination2000 * 2000) + ($denomination500 * 500) + ($denomination200 * 200) + 
                          ($denomination100 * 100) + ($denomination50 * 50) + ($denomination20 * 20) + 
                          ($denomination10 * 10) + ($denomination5 * 5) + ($denomination2 * 2) + ($denomination1 * 1), 2);
        
        // Calculate difference (will be calculated against closing balance)
        $difference = 0;
        
        // Check if period details exist
        $stmt = $db->prepare("SELECT detail_id FROM petty_cash_period_details WHERE period_id = ?");
        $stmt->execute([$periodId]);
        $existingDetail = $stmt->fetch();
        
        if ($existingDetail) {
            $stmt = $db->prepare("
                UPDATE petty_cash_period_details SET
                    remarks = ?, prepared_by_signature = ?, prepared_by_name = ?,
                    approved_by_signature = ?, approved_by_name = ?,
                    denomination_2000 = ?, denomination_500 = ?, denomination_200 = ?, denomination_100 = ?,
                    denomination_50 = ?, denomination_20 = ?, denomination_10 = ?,
                    denomination_5 = ?, denomination_2 = ?, denomination_1 = ?,
                    total_amount = ?, difference = ?
                WHERE period_id = ?
            ");
            $stmt->execute([
                $remarks, $preparedBySignature, $preparedByName,
                $approvedBySignature, $approvedByName,
                $denomination2000, $denomination500, $denomination200, $denomination100,
                $denomination50, $denomination20, $denomination10,
                $denomination5, $denomination2, $denomination1,
                $totalAmount, $difference, $periodId
            ]);
        } else {
            $stmt = $db->prepare("
                INSERT INTO petty_cash_period_details (
                    period_id, remarks, prepared_by_signature, prepared_by_name,
                    approved_by_signature, approved_by_name,
                    denomination_2000, denomination_500, denomination_200, denomination_100,
                    denomination_50, denomination_20, denomination_10,
                    denomination_5, denomination_2, denomination_1,
                    total_amount, difference
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $periodId, $remarks, $preparedBySignature, $preparedByName,
                $approvedBySignature, $approvedByName,
                $denomination2000, $denomination500, $denomination200, $denomination100,
                $denomination50, $denomination20, $denomination10,
                $denomination5, $denomination2, $denomination1,
                $totalAmount, $difference
            ]);
        }
        
        $db->commit();
        $success = true;
        $_SESSION['success'] = 'Petty Cash data saved successfully.';
        header('Location: ' . $_SERVER['PHP_SELF'] . '?period_id=' . $periodId . '&month=' . $month . '&year=' . $year);
        exit;
        
    } catch (Exception $e) {
        $db->rollBack();
        $errors[] = $e->getMessage();
        error_log("Petty cash save error: " . $e->getMessage());
    }
}

// Load data
try {
    $db = getDB();
    
    // Get all periods for selected month/year
    $stmt = $db->prepare("
        SELECT * FROM petty_cash_periods 
        WHERE site_id = ? AND month = ? AND year = ?
        ORDER BY period_id DESC
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $periods = $stmt->fetchAll();
    
    // Load period and entries if period_id is set
    if ($periodId > 0) {
        $stmt = $db->prepare("SELECT * FROM petty_cash_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$periodId, $siteId]);
        $period = $stmt->fetch();
        
        if ($period) {
            $stmt = $db->prepare("
                SELECT * FROM petty_cash_entries 
                WHERE period_id = ? 
                ORDER BY sr_no, entry_id
            ");
            $stmt->execute([$periodId]);
            $entries = $stmt->fetchAll();
            
            // Load period details
            $stmt = $db->prepare("SELECT * FROM petty_cash_period_details WHERE period_id = ?");
            $stmt->execute([$periodId]);
            $periodDetails = $stmt->fetch();
        }
    }
    
} catch (Exception $e) {
    error_log("Petty cash list error: " . $e->getMessage());
    $periods = [];
    $entries = [];
}

// If no entries, create empty array for new entry
if (empty($entries)) {
    $entries = [['entry_date' => '', 'sr_no' => 1]];
}

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

// Show success/error messages
if (isset($_SESSION['success'])) {
    echo '<div class="alert alert-success" style="background: #d4edda; color: #155724; padding: 12px; margin: 10px 0; border: 1px solid #c3e6cb; border-radius: 4px;">';
    echo htmlspecialchars($_SESSION['success']);
    echo '</div>';
    unset($_SESSION['success']);
}

if (!empty($errors)) {
    echo '<div class="alert alert-danger" style="background: #f8d7da; color: #721c24; padding: 12px; margin: 10px 0; border: 1px solid #f5c6cb; border-radius: 4px;">';
    foreach ($errors as $error) {
        echo htmlspecialchars($error) . '<br>';
    }
    echo '</div>';
}

// Get site name
$siteName = 'Corporate'; // Default
try {
    $stmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $site = $stmt->fetch();
    if ($site) {
        $siteName = $site['site_name'];
    }
} catch (Exception $e) {
    // Use default
}
?>

<style>
.excel-container {
    background: #d0e7ff; /* Light blue/cyan background like Excel */
    padding: 20px;
    font-family: Arial, sans-serif;
}

.period-selector {
    background: #f0f0f0;
    padding: 15px;
    margin-bottom: 20px;
    border: 1px solid #d0d0d0;
    border-radius: 4px;
}

.excel-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 11px;
    background: #fff;
    font-family: Arial, sans-serif;
    margin-bottom: 20px;
}

.excel-table thead {
    background: #808080; /* Grey header */
}

.excel-table thead th {
    background: #808080 !important;
    color: #fff;
    font-weight: bold;
    text-align: center;
    padding: 8px 4px;
    border: 1px solid #000;
    font-size: 11px;
}

.excel-table tbody td {
    padding: 4px 6px;
    border: 1px solid #000;
    text-align: left;
    font-size: 11px;
    vertical-align: middle;
    height: auto;
    background: #fff;
}

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

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

.excel-table tbody td input {
    width: 100%;
    min-width: 60px;
    border: none;
    padding: 4px 6px;
    font-size: 11px;
    background: transparent;
    font-family: Arial, sans-serif;
    height: 28px;
    line-height: 20px;
    box-sizing: border-box;
}

.excel-table tbody td input:focus {
    background: #fffacd;
    outline: 2px solid #4a90e2;
    outline-offset: -2px;
}

.calculated {
    background: #f0f0f0;
    font-weight: bold;
    text-align: right !important;
    user-select: none;
    cursor: default;
}

.header-row-duplicate {
    background: #808080 !important;
    color: #fff !important;
}

.header-row-duplicate td {
    background: #808080 !important;
    color: #fff !important;
    font-weight: bold;
    text-align: center;
    padding: 8px 4px !important;
    border: 1px solid #000 !important;
}

.calculation-row {
    background: #ffa500 !important;
}

.calculation-row td {
    background: #ffa500 !important;
    color: #000 !important;
    font-weight: bold;
    border: 1px solid #000 !important;
    padding: 8px 4px !important;
}

/* Input field backgrounds */
.input-yellow { background: #fff2cc !important; }
.input-blue { background: #cfe2f3 !important; }
.input-green { background: #d9ead3 !important; }
.input-red { background: #ffe6e6 !important; }

.btn-action {
    padding: 8px 15px;
    margin: 5px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.denomination-section {
    background: #fff;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-top: 20px;
}

.denomination-table {
    width: 300px;
    border-collapse: collapse;
}

.denomination-table th,
.denomination-table td {
    border: 1px solid #000;
    padding: 4px;
    text-align: center;
}

.denomination-table th {
    background: #808080;
    color: #fff;
}

.difference {
    background: #ffe6e6 !important;
    color: #991b1b !important;
    font-weight: bold;
}

.opening-row {
    background: #f0f0f0 !important;
    font-weight: bold;
}

.opening-row td {
    background: #f0f0f0 !important;
    border: 1px solid #000 !important;
    text-align: center !important;
}

.opening-row td.calculated {
    text-align: right !important;
    font-weight: bold;
}
</style>

<div class="excel-container">
    <h2>Cash Expenses Summary</h2>
    
    <!-- Period Selector -->
    <div class="period-selector">
        <label>Site Name: <strong><?php echo htmlspecialchars($siteName); ?></strong></label>
        <label style="margin-left: 20px;">Month:</label>
        <select id="filter_month" onchange="filterByMonthYear()">
            <?php for ($m = 1; $m <= 12; $m++): ?>
            <option value="<?php echo $m; ?>" <?php echo $m == $selectedMonth ? 'selected' : ''; ?>>
                <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
            </option>
            <?php endfor; ?>
        </select>
        
        <label>Year:</label>
        <input type="number" id="filter_year" value="<?php echo $selectedYear; ?>" 
               min="2020" max="2100" onchange="filterByMonthYear()" style="width: 80px;">
        
        <a href="<?php echo BASE_URL; ?>/modules/petty_cash/report.php" class="btn-action btn-info">View Report</a>
    </div>
    
    <!-- Period List -->
    <?php if (!empty($periods)): ?>
    <div style="margin-bottom: 20px;">
        <strong>Existing Periods:</strong>
        <?php foreach ($periods as $p): ?>
        <a href="?period_id=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
           class="btn-action btn-info" style="margin: 5px;">
            <?php echo htmlspecialchars($p['period_name'] ?: date('d M', strtotime($p['start_date'])) . ' - ' . date('d M', strtotime($p['end_date']))); ?>
        </a>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
    
    <!-- Period Form -->
    <form method="POST" id="pettyCashForm">
        <input type="hidden" name="save_petty_cash" value="1">
        
        <div class="period-form" style="background: #f9f9f9; padding: 15px; margin-bottom: 20px; border: 1px solid #ddd; border-radius: 4px;">
            <div style="display: inline-block; margin-right: 15px;">
                <label>From Date:</label>
                <input type="date" name="from_date" id="from_date" 
                       value="<?php echo $period ? htmlspecialchars($period['start_date']) : ''; ?>" required>
            </div>
            
            <div style="display: inline-block; margin-right: 15px;">
                <label>To Date:</label>
                <input type="date" name="to_date" id="to_date" 
                       value="<?php echo $period ? htmlspecialchars($period['end_date']) : ''; ?>" required>
            </div>
            
            <div style="display: inline-block; margin-right: 15px;">
                <label>Period Name:</label>
                <input type="text" name="period_name" 
                       value="<?php echo $period ? htmlspecialchars($period['period_name']) : ''; ?>" 
                       placeholder="e.g., November '22">
            </div>
            
            <div style="display: inline-block; margin-right: 15px;">
                <label>Opening Balance:</label>
                <input type="number" step="0.01" name="opening_balance" 
                       value="<?php echo $period ? number_format($period['opening_balance'], 2, '.', '') : '0.00'; ?>" 
                       style="width: 120px;">
            </div>
        </div>
        
        <!-- Excel-like Table -->
        <div style="overflow-x: auto;">
            <table class="excel-table" id="pettyCashTable">
                <thead>
                    <tr>
                        <th style="width: 80px;">Date</th>
                        <th style="width: 100px;">Voucher No</th>
                        <th style="width: 200px;">Description Bill</th>
                        <th colspan="3" style="background: #cfe2f3 !important;">Collection Details</th>
                        <th colspan="12" style="background: #fff2cc !important;">Total Cash Out</th>
                        <th style="width: 100px;">Bank Deposit</th>
                        <th style="width: 120px;">Balance In Hand</th>
                        <th style="width: 150px;">Reimbursable/Non-reimbursable</th>
                        <th style="width: 80px;">Action</th>
                    </tr>
                    <tr>
                        <th></th>
                        <th></th>
                        <th></th>
                        <th style="background: #cfe2f3 !important;">Total Cash In Hand</th>
                        <th style="background: #cfe2f3 !important;">Received from Finance</th>
                        <th style="background: #cfe2f3 !important;">Other Receipt</th>
                        <th style="background: #fff2cc !important;">Total Cash Out</th>
                        <th style="background: #fff2cc !important;">Purchase Catering</th>
                        <th style="background: #fff2cc !important;">Purchase HK</th>
                        <th style="background: #ffe6e6 !important;">Maintenance</th>
                        <th style="background: #fff2cc !important;">Impres Money Commission</th>
                        <th style="background: #fff2cc !important;">Printing Stationery</th>
                        <th style="background: #fff2cc !important;">Grocery & Cutlery & Rent & Hire</th>
                        <th style="background: #fff2cc !important;">Mobile/Tel</th>
                        <th style="background: #fff2cc !important;">Local Conveyance</th>
                        <th style="background: #cfe2f3 !important;">Courier</th>
                        <th style="background: #fff2cc !important;">Staff Welfare</th>
                        <th style="background: #fff2cc !important;">Other Misc</th>
                        <th style="background: #fff2cc !important;">Decoration Charges</th>
                        <th></th>
                        <th></th>
                        <th></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="entriesBody">
                    <!-- Opening Row (Put here last month closing) -->
                    <tr class="opening-row" style="background: #f0f0f0;">
                        <td colspan="3" style="font-weight: bold; text-align: center;">Opening (Put here last month closing)</td>
                        <td class="calculated opening-total-cash-in-hand">0.00</td>
                        <td class="calculated opening-received-from-finance">0.00</td>
                        <td class="calculated opening-other-receipt">0.00</td>
                        <td class="calculated opening-total-cash-out">0.00</td>
                        <td class="calculated opening-purchase-catering">0.00</td>
                        <td class="calculated opening-purchase-hk">0.00</td>
                        <td class="calculated opening-maintenance">0.00</td>
                        <td class="calculated opening-impres-money">0.00</td>
                        <td class="calculated opening-printing-stationery">0.00</td>
                        <td class="calculated opening-grocery-cutlery">0.00</td>
                        <td class="calculated opening-mobile-tel">0.00</td>
                        <td class="calculated opening-local-conveyance">0.00</td>
                        <td class="calculated opening-courier">0.00</td>
                        <td class="calculated opening-staff-welfare">0.00</td>
                        <td class="calculated opening-other-misc">0.00</td>
                        <td class="calculated opening-decoration-charges">0.00</td>
                        <td class="calculated opening-bank-deposit">0.00</td>
                        <td class="calculated opening-balance-in-hand" id="opening-balance-display"><?php echo number_format($period['opening_balance'] ?? 0, 2); ?></td>
                        <td colspan="2"></td>
                        <td></td>
                    </tr>
                    <?php $rowIndex = 0; ?>
                    <?php foreach ($entries as $entry): ?>
                    <tr data-row-index="<?php echo $rowIndex; ?>" class="data-row">
                        <td>
                            <input type="date" name="entries[<?php echo $rowIndex; ?>][entry_date]" 
                                   value="<?php echo htmlspecialchars($entry['entry_date'] ?? ''); ?>" 
                                   class="entry-date" onchange="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="text" name="entries[<?php echo $rowIndex; ?>][voucher_no]" 
                                   value="<?php echo htmlspecialchars($entry['voucher_no'] ?? ''); ?>">
                        </td>
                        <td>
                            <input type="text" name="entries[<?php echo $rowIndex; ?>][description_bill]" 
                                   value="<?php echo htmlspecialchars($entry['description_bill'] ?? ''); ?>" 
                                   style="width: 100%; min-width: 180px;">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][total_cash_in_hand]" 
                                   value="<?php echo number_format($entry['total_cash_in_hand'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-blue total-cash-in-hand" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][received_from_finance]" 
                                   value="<?php echo number_format($entry['received_from_finance'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-blue received-from-finance" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][other_receipt]" 
                                   value="<?php echo number_format($entry['other_receipt'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-blue other-receipt" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td class="calculated total-cash-out">
                            <?php echo number_format($entry['total_cash_out'] ?? 0, 2); ?>
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][purchase_catering]" 
                                   value="<?php echo number_format($entry['purchase_catering'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-yellow purchase-catering" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][purchase_hk]" 
                                   value="<?php echo number_format($entry['purchase_hk'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-yellow purchase-hk" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][maintenance]" 
                                   value="<?php echo number_format($entry['maintenance'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-red maintenance" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][impres_money_commission]" 
                                   value="<?php echo number_format($entry['impres_money_commission'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-yellow impres-money" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][printing_stationery]" 
                                   value="<?php echo number_format($entry['printing_stationery'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-yellow printing-stationery" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][grocery_cutlery_rent_hire]" 
                                   value="<?php echo number_format($entry['grocery_cutlery_rent_hire'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-yellow grocery-cutlery" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][mobile_tel]" 
                                   value="<?php echo number_format($entry['mobile_tel'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-yellow mobile-tel" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][local_conveyance]" 
                                   value="<?php echo number_format($entry['local_conveyance'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-yellow local-conveyance" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][courier]" 
                                   value="<?php echo number_format($entry['courier'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-blue courier" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][staff_welfare]" 
                                   value="<?php echo number_format($entry['staff_welfare'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-yellow staff-welfare" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][other_misc]" 
                                   value="<?php echo number_format($entry['other_misc'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-yellow other-misc" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][decoration_charges]" 
                                   value="<?php echo number_format($entry['decoration_charges'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right input-yellow decoration-charges" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td>
                            <input type="number" step="0.01" name="entries[<?php echo $rowIndex; ?>][bank_deposit]" 
                                   value="<?php echo number_format($entry['bank_deposit'] ?? 0, 2, '.', ''); ?>" 
                                   class="text-right bank-deposit" 
                                   onchange="calculateRow(<?php echo $rowIndex; ?>)" 
                                   oninput="calculateRow(<?php echo $rowIndex; ?>)">
                        </td>
                        <td class="calculated balance-in-hand">
                            <?php echo number_format($entry['balance_in_hand'] ?? 0, 2); ?>
                        </td>
                        <td>
                            <select name="entries[<?php echo $rowIndex; ?>][reimbursable_non_reimbursable]" style="width: 100%; border: none; padding: 4px;">
                                <option value="">Select</option>
                                <option value="Reimbursable" <?php echo ($entry['reimbursable_non_reimbursable'] ?? '') == 'Reimbursable' ? 'selected' : ''; ?>>Reimbursable</option>
                                <option value="Non-reimbursable" <?php echo ($entry['reimbursable_non_reimbursable'] ?? '') == 'Non-reimbursable' ? 'selected' : ''; ?>>Non-reimbursable</option>
                            </select>
                        </td>
                        <td>
                            <button type="button" class="btn-action btn-success" onclick="insertRowAfter(this)" title="Insert Row After" style="padding: 2px 5px; font-size: 12px;">+</button>
                            <button type="button" class="btn-action btn-info" onclick="insertHeaderAfter(this)" title="Insert Header After" style="padding: 2px 5px; font-size: 12px; background: #ffa500; color: #000;">H</button>
                            <button type="button" class="btn-action btn-danger" onclick="removeRow(this)" title="Remove Row" style="padding: 2px 5px; font-size: 12px;">×</button>
                        </td>
                    </tr>
                    <?php $rowIndex++; ?>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Remarks and Approval Section -->
        <div style="margin-top: 20px; display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
            <div>
                <h4>Remarks If Any</h4>
                <textarea name="remarks" rows="3" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;"><?php echo htmlspecialchars($periodDetails['remarks'] ?? ''); ?></textarea>
            </div>
            <div>
                <div style="margin-bottom: 15px;">
                    <label><strong>Prepared By:</strong></label>
                    <input type="text" name="prepared_by_signature" placeholder="Signature" 
                           value="<?php echo htmlspecialchars($periodDetails['prepared_by_signature'] ?? ''); ?>" 
                           style="width: 48%; margin-right: 2%;">
                    <input type="text" name="prepared_by_name" placeholder="Hospitality Manager Name" 
                           value="<?php echo htmlspecialchars($periodDetails['prepared_by_name'] ?? ''); ?>" 
                           style="width: 48%;">
                </div>
                <div>
                    <label><strong>Approved By:</strong></label>
                    <input type="text" name="approved_by_signature" placeholder="Signature" 
                           value="<?php echo htmlspecialchars($periodDetails['approved_by_signature'] ?? ''); ?>" 
                           style="width: 48%; margin-right: 2%;">
                    <input type="text" name="approved_by_name" placeholder="Operation Manager Name" 
                           value="<?php echo htmlspecialchars($periodDetails['approved_by_name'] ?? ''); ?>" 
                           style="width: 48%;">
                </div>
            </div>
        </div>
        
        <!-- Denomination Section -->
        <div class="denomination-section">
            <h4>Denomination</h4>
            <table class="denomination-table">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $denominations = [
                        ['value' => 2000, 'name' => 'denomination_2000', 'amount' => $periodDetails['denomination_2000'] ?? 0],
                        ['value' => 500, 'name' => 'denomination_500', 'amount' => $periodDetails['denomination_500'] ?? 0],
                        ['value' => 200, 'name' => 'denomination_200', 'amount' => $periodDetails['denomination_200'] ?? 0],
                        ['value' => 100, 'name' => 'denomination_100', 'amount' => $periodDetails['denomination_100'] ?? 0],
                        ['value' => 50, 'name' => 'denomination_50', 'amount' => $periodDetails['denomination_50'] ?? 0],
                        ['value' => 20, 'name' => 'denomination_20', 'amount' => $periodDetails['denomination_20'] ?? 0],
                        ['value' => 10, 'name' => 'denomination_10', 'amount' => $periodDetails['denomination_10'] ?? 0],
                        ['value' => 5, 'name' => 'denomination_5', 'amount' => $periodDetails['denomination_5'] ?? 0],
                        ['value' => 2, 'name' => 'denomination_2', 'amount' => $periodDetails['denomination_2'] ?? 0],
                        ['value' => 1, 'name' => 'denomination_1', 'amount' => $periodDetails['denomination_1'] ?? 0],
                    ];
                    foreach ($denominations as $denom): 
                    ?>
                    <tr>
                        <td><?php echo $denom['value']; ?></td>
                        <td>
                            <input type="number" name="<?php echo $denom['name']; ?>" 
                                   value="<?php echo $denom['amount']; ?>" 
                                   class="denomination-input" 
                                   data-value="<?php echo $denom['value']; ?>"
                                   onchange="calculateDenomination()" 
                                   oninput="calculateDenomination()"
                                   style="width: 100%; border: none; text-align: center;">
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th>Total Amount</th>
                        <th class="calculated" id="total-amount"><?php echo number_format($periodDetails['total_amount'] ?? 0, 2); ?></th>
                    </tr>
                    <tr>
                        <th>Difference</th>
                        <th class="calculated difference" id="difference"><?php echo number_format($periodDetails['difference'] ?? 0, 2); ?></th>
                    </tr>
                </tfoot>
            </table>
        </div>
        
        <!-- Action Buttons -->
        <div style="margin: 20px 0; text-align: center;">
            <button type="button" class="btn-action btn-success" onclick="addRow()">+ Add Row</button>
            <button type="button" class="btn-action btn-info" onclick="addHeaderRow()" style="background: #ffa500; color: #000;">+ Add Header</button>
            <button type="button" class="btn-action btn-info" onclick="addCalculationRowAtEnd()" style="background: #ffa500; color: #000;">+ Add Calculation</button>
            <button type="submit" class="btn-action btn-primary">Save Data</button>
        </div>
    </form>
</div>

<script>
let rowCount = <?php echo $rowIndex; ?>;
let openingBalance = parseFloat(document.querySelector('input[name="opening_balance"]')?.value || 0);

// Calculate row balance - AUTO CALCULATE on every change
function calculateRow(rowIndex) {
    const row = document.querySelector(`tr[data-row-index="${rowIndex}"]`);
    if (!row || row.classList.contains('header-row-duplicate') || row.classList.contains('calculation-row')) return;
    
    // Get all expense inputs with proper parsing
    const purchaseCatering = Math.max(0, parseFloat(row.querySelector('.purchase-catering')?.value || 0) || 0);
    const purchaseHK = Math.max(0, parseFloat(row.querySelector('.purchase-hk')?.value || 0) || 0);
    const maintenance = Math.max(0, parseFloat(row.querySelector('.maintenance')?.value || 0) || 0);
    const impresMoney = Math.max(0, parseFloat(row.querySelector('.impres-money')?.value || 0) || 0);
    const printingStationery = Math.max(0, parseFloat(row.querySelector('.printing-stationery')?.value || 0) || 0);
    const groceryCutlery = Math.max(0, parseFloat(row.querySelector('.grocery-cutlery')?.value || 0) || 0);
    const mobileTel = Math.max(0, parseFloat(row.querySelector('.mobile-tel')?.value || 0) || 0);
    const localConveyance = Math.max(0, parseFloat(row.querySelector('.local-conveyance')?.value || 0) || 0);
    const courier = Math.max(0, parseFloat(row.querySelector('.courier')?.value || 0) || 0);
    const staffWelfare = Math.max(0, parseFloat(row.querySelector('.staff-welfare')?.value || 0) || 0);
    const otherMisc = Math.max(0, parseFloat(row.querySelector('.other-misc')?.value || 0) || 0);
    const decorationCharges = Math.max(0, parseFloat(row.querySelector('.decoration-charges')?.value || 0) || 0);
    
    // Calculate Total Cash Out - EXACT EXCEL FORMULA
    // Excel Formula: I10 = J10+Q10+R10+S10+T10+U10+V10+K10+L10+M10+N10+O10+P10
    // Columns: J(Purchase Catering), K(Purchase HK), L(Maintenance), M(Impres Money), 
    //          N(Printing Stationery), O(Grocery Cutlery), P(Mobile/Tel), Q(Local Conveyance),
    //          R(Courier), S(Staff Welfare), T(Other Misc), U(Decoration Charges), V(Bank Deposit)
    const totalCashOut = Math.round((purchaseCatering + purchaseHK + maintenance + impresMoney + 
                        printingStationery + groceryCutlery + mobileTel + localConveyance + 
                        courier + staffWelfare + otherMisc + decorationCharges) * 100) / 100;
    
    // Update Total Cash Out display
    const totalCashOutEl = row.querySelector('.total-cash-out');
    if (totalCashOutEl) {
        totalCashOutEl.textContent = totalCashOut.toFixed(2);
    }
    
    // Calculate Balance In Hand (Running Balance)
    // Formula: Previous Balance + Total Cash In Hand + Received from Finance + Other Receipt - Total Cash Out - Bank Deposit
    const totalCashInHand = Math.max(0, parseFloat(row.querySelector('.total-cash-in-hand')?.value || 0) || 0);
    const receivedFromFinance = Math.max(0, parseFloat(row.querySelector('.received-from-finance')?.value || 0) || 0);
    const otherReceipt = Math.max(0, parseFloat(row.querySelector('.other-receipt')?.value || 0) || 0);
    const bankDeposit = Math.max(0, parseFloat(row.querySelector('.bank-deposit')?.value || 0) || 0);
    
    // Get previous balance (from previous row or opening balance)
    let previousBalance = openingBalance;
    const allRows = Array.from(document.querySelectorAll('#entriesBody tr.data-row'));
    const currentRowIndex = allRows.indexOf(row);
    
    for (let i = 0; i < currentRowIndex; i++) {
        const prevRow = allRows[i];
        if (prevRow && !prevRow.classList.contains('header-row-duplicate') && !prevRow.classList.contains('calculation-row')) {
            const prevBalanceEl = prevRow.querySelector('.balance-in-hand');
            if (prevBalanceEl) {
                const prevBalanceText = prevBalanceEl.textContent || '0';
                previousBalance = parseFloat(prevBalanceText.replace(/[^\d.-]/g, '')) || 0;
            }
        }
    }
    
    // Calculate new balance
    const balanceInHand = Math.round((previousBalance + totalCashInHand + receivedFromFinance + otherReceipt - totalCashOut - bankDeposit) * 100) / 100;
    
    // Update Balance In Hand display
    const balanceInHandEl = row.querySelector('.balance-in-hand');
    if (balanceInHandEl) {
        balanceInHandEl.textContent = balanceInHand.toFixed(2);
    }
    
    // Auto-recalculate all subsequent rows
    recalculateAllSubsequentRows(currentRowIndex);
    
    // Auto-recalculate all calculation rows
    recalculateAllCalculationRows();
    
    // Auto-recalculate denomination difference
    calculateDenomination();
}

// Recalculate all rows
function recalculateAllRows() {
    const allRows = Array.from(document.querySelectorAll('#entriesBody tr.data-row'));
    allRows.forEach((row, index) => {
        const rowIndex = parseInt(row.getAttribute('data-row-index'));
        if (!isNaN(rowIndex)) {
            calculateRow(rowIndex);
        }
    });
}

// Recalculate closing balance - AUTO CALCULATE
function recalculateClosingBalance() {
    // This is now handled by calculateDenomination which gets the last balance
    calculateDenomination();
}

// Calculate denomination total - AUTO CALCULATE
function calculateDenomination() {
    let total = 0;
    document.querySelectorAll('.denomination-input').forEach(input => {
        const count = Math.max(0, parseInt(input.value || 0) || 0);
        const value = parseInt(input.getAttribute('data-value') || 0);
        total += count * value;
    });
    
    const totalAmountEl = document.getElementById('total-amount');
    if (totalAmountEl) {
        totalAmountEl.textContent = Math.round(total * 100) / 100;
    }
    
    // Calculate difference (against closing balance)
    // Get the last balance from the last data row (not calculation row)
    const allRows = Array.from(document.querySelectorAll('#entriesBody tr.data-row'));
    let closingBalance = openingBalance;
    
    // Find last non-calculation, non-header, non-opening row
    for (let i = allRows.length - 1; i >= 0; i--) {
        const row = allRows[i];
        if (row && !row.classList.contains('header-row-duplicate') && 
            !row.classList.contains('calculation-row') && 
            !row.classList.contains('opening-row')) {
            const balanceEl = row.querySelector('.balance-in-hand');
            if (balanceEl) {
                closingBalance = parseFloat(balanceEl.textContent.replace(/[^\d.-]/g, '')) || openingBalance;
                break;
            }
        }
    }
    
    // If calculation row exists, use its balance
    const calcRow = document.querySelector('.calculation-row');
    if (calcRow) {
        const calcBalanceEl = calcRow.querySelector('#calc-balance-in-hand');
        if (calcBalanceEl) {
            closingBalance = parseFloat(calcBalanceEl.textContent.replace(/[^\d.-]/g, '')) || closingBalance;
        }
    }
    
    const difference = Math.round((closingBalance - total) * 100) / 100;
    
    const differenceEl = document.getElementById('difference');
    if (differenceEl) {
        differenceEl.textContent = difference.toFixed(2);
        // Highlight if difference is not zero
        if (Math.abs(difference) > 0.01) {
            differenceEl.style.background = '#ffe6e6';
            differenceEl.style.color = '#991b1b';
        } else {
            differenceEl.style.background = '#d1fae5';
            differenceEl.style.color = '#065f46';
        }
    }
}

// Add row - AUTO CALCULATE after adding
function addRow() {
    const tbody = document.getElementById('entriesBody');
    const newRow = document.createElement('tr');
    newRow.setAttribute('data-row-index', rowCount);
    newRow.className = 'data-row';
    newRow.innerHTML = `
        <td><input type="date" name="entries[${rowCount}][entry_date]" class="entry-date" onchange="calculateRow(${rowCount})"></td>
        <td><input type="text" name="entries[${rowCount}][voucher_no]"></td>
        <td><input type="text" name="entries[${rowCount}][description_bill]" style="width: 100%; min-width: 180px;"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][total_cash_in_hand]" value="0.00" class="text-right input-blue total-cash-in-hand" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][received_from_finance]" value="0.00" class="text-right input-blue received-from-finance" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][other_receipt]" value="0.00" class="text-right input-blue other-receipt" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td class="calculated total-cash-out">0.00</td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][purchase_catering]" value="0.00" class="text-right input-yellow purchase-catering" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][purchase_hk]" value="0.00" class="text-right input-yellow purchase-hk" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][maintenance]" value="0.00" class="text-right input-red maintenance" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][impres_money_commission]" value="0.00" class="text-right input-yellow impres-money" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][printing_stationery]" value="0.00" class="text-right input-yellow printing-stationery" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][grocery_cutlery_rent_hire]" value="0.00" class="text-right input-yellow grocery-cutlery" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][mobile_tel]" value="0.00" class="text-right input-yellow mobile-tel" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][local_conveyance]" value="0.00" class="text-right input-yellow local-conveyance" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][courier]" value="0.00" class="text-right input-blue courier" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][staff_welfare]" value="0.00" class="text-right input-yellow staff-welfare" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][other_misc]" value="0.00" class="text-right input-yellow other-misc" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][decoration_charges]" value="0.00" class="text-right input-yellow decoration-charges" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td><input type="number" step="0.01" name="entries[${rowCount}][bank_deposit]" value="0.00" class="text-right bank-deposit" onchange="calculateRow(${rowCount})" oninput="calculateRow(${rowCount})"></td>
        <td class="calculated balance-in-hand">0.00</td>
        <td><select name="entries[${rowCount}][reimbursable_non_reimbursable]" style="width: 100%; border: none; padding: 4px;"><option value="">Select</option><option value="Reimbursable">Reimbursable</option><option value="Non-reimbursable">Non-reimbursable</option></select></td>
        <td><button type="button" class="btn-action btn-success" onclick="insertRowAfter(this)" style="padding: 2px 5px; font-size: 12px;">+</button><button type="button" class="btn-action btn-danger" onclick="removeRow(this)" style="padding: 2px 5px; font-size: 12px;">×</button></td>
    `;
    tbody.appendChild(newRow);
    rowCount++;
    // Auto-calculate after adding row
    setTimeout(() => {
        calculateRow(rowCount - 1);
    }, 50);
}

// Insert header row
function insertHeaderAfter(btn) {
    const currentRow = btn.closest('tr');
    const tbody = document.getElementById('entriesBody');
    const headerRow = document.createElement('tr');
    headerRow.className = 'header-row-duplicate';
    headerRow.innerHTML = `
        <td colspan="25" style="background: #808080; color: #fff; font-weight: bold; text-align: center; padding: 8px 4px;">
            <button type="button" onclick="removeRow(this)" style="background: #dc3545; color: #fff; border: none; padding: 2px 5px; border-radius: 3px; cursor: pointer; float: right;">×</button>
            Table Header
        </td>
    `;
    currentRow.insertAdjacentElement('afterend', headerRow);
}

// Add calculation row - AUTO CALCULATE
function addCalculationRowAtEnd() {
    const tbody = document.getElementById('entriesBody');
    const calcRow = document.createElement('tr');
    calcRow.className = 'calculation-row';
    calcRow.innerHTML = `
        <td colspan="3" style="font-weight: bold;">Closing Balance</td>
        <td class="calculated" id="calc-total-cash-in-hand">0.00</td>
        <td class="calculated" id="calc-received-from-finance">0.00</td>
        <td class="calculated" id="calc-other-receipt">0.00</td>
        <td class="calculated" id="calc-total-cash-out">0.00</td>
        <td class="calculated" id="calc-purchase-catering">0.00</td>
        <td class="calculated" id="calc-purchase-hk">0.00</td>
        <td class="calculated" id="calc-maintenance">0.00</td>
        <td class="calculated" id="calc-impres-money">0.00</td>
        <td class="calculated" id="calc-printing-stationery">0.00</td>
        <td class="calculated" id="calc-grocery-cutlery">0.00</td>
        <td class="calculated" id="calc-mobile-tel">0.00</td>
        <td class="calculated" id="calc-local-conveyance">0.00</td>
        <td class="calculated" id="calc-courier">0.00</td>
        <td class="calculated" id="calc-staff-welfare">0.00</td>
        <td class="calculated" id="calc-other-misc">0.00</td>
        <td class="calculated" id="calc-decoration-charges">0.00</td>
        <td class="calculated" id="calc-bank-deposit">0.00</td>
        <td class="calculated" id="calc-balance-in-hand">0.00</td>
        <td colspan="2"></td>
        <td><button type="button" class="btn-action btn-danger" onclick="removeRow(this)" style="padding: 2px 5px; font-size: 12px;">×</button></td>
    `;
    tbody.appendChild(calcRow);
    // Auto-calculate immediately
    setTimeout(() => {
        recalculateCalculationRow(calcRow);
        calculateDenomination();
    }, 50);
}

// Recalculate calculation row
function recalculateCalculationRow(calcRow) {
    const allRows = Array.from(document.querySelectorAll('#entriesBody tr.data-row'));
    let totals = {
        totalCashInHand: 0,
        receivedFromFinance: 0,
        otherReceipt: 0,
        totalCashOut: 0,
        purchaseCatering: 0,
        purchaseHK: 0,
        maintenance: 0,
        impresMoney: 0,
        printingStationery: 0,
        groceryCutlery: 0,
        mobileTel: 0,
        localConveyance: 0,
        courier: 0,
        staffWelfare: 0,
        otherMisc: 0,
        decorationCharges: 0,
        bankDeposit: 0,
        balanceInHand: 0
    };
    
    allRows.forEach(row => {
        // Skip opening row, header rows, and calculation rows
        if (row.classList.contains('opening-row') || 
            row.classList.contains('header-row-duplicate') || 
            row.classList.contains('calculation-row')) {
            return;
        }
        
        totals.totalCashInHand += Math.max(0, parseFloat(row.querySelector('.total-cash-in-hand')?.value || 0) || 0);
        totals.receivedFromFinance += Math.max(0, parseFloat(row.querySelector('.received-from-finance')?.value || 0) || 0);
        totals.otherReceipt += Math.max(0, parseFloat(row.querySelector('.other-receipt')?.value || 0) || 0);
        totals.purchaseCatering += Math.max(0, parseFloat(row.querySelector('.purchase-catering')?.value || 0) || 0);
        totals.purchaseHK += Math.max(0, parseFloat(row.querySelector('.purchase-hk')?.value || 0) || 0);
        totals.maintenance += Math.max(0, parseFloat(row.querySelector('.maintenance')?.value || 0) || 0);
        totals.impresMoney += Math.max(0, parseFloat(row.querySelector('.impres-money')?.value || 0) || 0);
        totals.printingStationery += Math.max(0, parseFloat(row.querySelector('.printing-stationery')?.value || 0) || 0);
        totals.groceryCutlery += Math.max(0, parseFloat(row.querySelector('.grocery-cutlery')?.value || 0) || 0);
        totals.mobileTel += Math.max(0, parseFloat(row.querySelector('.mobile-tel')?.value || 0) || 0);
        totals.localConveyance += Math.max(0, parseFloat(row.querySelector('.local-conveyance')?.value || 0) || 0);
        totals.courier += Math.max(0, parseFloat(row.querySelector('.courier')?.value || 0) || 0);
        totals.staffWelfare += Math.max(0, parseFloat(row.querySelector('.staff-welfare')?.value || 0) || 0);
        totals.otherMisc += Math.max(0, parseFloat(row.querySelector('.other-misc')?.value || 0) || 0);
        totals.decorationCharges += Math.max(0, parseFloat(row.querySelector('.decoration-charges')?.value || 0) || 0);
        totals.bankDeposit += Math.max(0, parseFloat(row.querySelector('.bank-deposit')?.value || 0) || 0);
        
        const balanceEl = row.querySelector('.balance-in-hand');
        if (balanceEl) {
            totals.balanceInHand = parseFloat(balanceEl.textContent.replace(/[^\d.-]/g, '')) || totals.balanceInHand;
        }
    });
    
    totals.totalCashOut = totals.purchaseCatering + totals.purchaseHK + totals.maintenance + totals.impresMoney + 
                          totals.printingStationery + totals.groceryCutlery + totals.mobileTel + totals.localConveyance + 
                          totals.courier + totals.staffWelfare + totals.otherMisc + totals.decorationCharges;
    
    // Update calculation row
    if (calcRow) {
        calcRow.querySelector('#calc-total-cash-in-hand').textContent = totals.totalCashInHand.toFixed(2);
        calcRow.querySelector('#calc-received-from-finance').textContent = totals.receivedFromFinance.toFixed(2);
        calcRow.querySelector('#calc-other-receipt').textContent = totals.otherReceipt.toFixed(2);
        calcRow.querySelector('#calc-total-cash-out').textContent = totals.totalCashOut.toFixed(2);
        calcRow.querySelector('#calc-purchase-catering').textContent = totals.purchaseCatering.toFixed(2);
        calcRow.querySelector('#calc-purchase-hk').textContent = totals.purchaseHK.toFixed(2);
        calcRow.querySelector('#calc-maintenance').textContent = totals.maintenance.toFixed(2);
        calcRow.querySelector('#calc-impres-money').textContent = totals.impresMoney.toFixed(2);
        calcRow.querySelector('#calc-printing-stationery').textContent = totals.printingStationery.toFixed(2);
        calcRow.querySelector('#calc-grocery-cutlery').textContent = totals.groceryCutlery.toFixed(2);
        calcRow.querySelector('#calc-mobile-tel').textContent = totals.mobileTel.toFixed(2);
        calcRow.querySelector('#calc-local-conveyance').textContent = totals.localConveyance.toFixed(2);
        calcRow.querySelector('#calc-courier').textContent = totals.courier.toFixed(2);
        calcRow.querySelector('#calc-staff-welfare').textContent = totals.staffWelfare.toFixed(2);
        calcRow.querySelector('#calc-other-misc').textContent = totals.otherMisc.toFixed(2);
        calcRow.querySelector('#calc-decoration-charges').textContent = totals.decorationCharges.toFixed(2);
        calcRow.querySelector('#calc-bank-deposit').textContent = totals.bankDeposit.toFixed(2);
        calcRow.querySelector('#calc-balance-in-hand').textContent = totals.balanceInHand.toFixed(2);
    }
    
}

function insertRowAfter(btn) {
    const currentRow = btn.closest('tr');
    const newRow = currentRow.cloneNode(true);
    newRow.setAttribute('data-row-index', rowCount);
    newRow.querySelectorAll('input').forEach(input => {
        if (input.type !== 'date') input.value = '0.00';
        else input.value = '';
        const name = input.getAttribute('name');
        if (name) {
            input.setAttribute('name', name.replace(/entries\[\d+\]/, `entries[${rowCount}]`));
            if (input.classList.contains('total-cash-in-hand') || input.classList.contains('received-from-finance') || 
                input.classList.contains('other-receipt') || input.classList.contains('purchase-catering') ||
                input.classList.contains('purchase-hk') || input.classList.contains('maintenance') ||
                input.classList.contains('impres-money') || input.classList.contains('printing-stationery') ||
                input.classList.contains('grocery-cutlery') || input.classList.contains('mobile-tel') ||
                input.classList.contains('local-conveyance') || input.classList.contains('courier') ||
                input.classList.contains('staff-welfare') || input.classList.contains('other-misc') ||
                input.classList.contains('decoration-charges') || input.classList.contains('bank-deposit')) {
                input.setAttribute('onchange', `calculateRow(${rowCount})`);
                input.setAttribute('oninput', `calculateRow(${rowCount})`);
            }
        }
    });
    newRow.querySelector('.balance-in-hand').textContent = '0.00';
    newRow.querySelector('.total-cash-out').textContent = '0.00';
    currentRow.insertAdjacentElement('afterend', newRow);
    rowCount++;
    recalculateAllRows();
}

function removeRow(btn) {
    const row = btn.closest('tr');
    if (confirm('Are you sure you want to remove this row?')) {
        row.remove();
        // Auto-recalculate after removing row
        setTimeout(() => {
            recalculateAllRows();
        }, 50);
    }
}

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

// Update opening balance display
function updateOpeningBalanceDisplay() {
    const openingBalanceDisplay = document.getElementById('opening-balance-display');
    if (openingBalanceDisplay) {
        openingBalanceDisplay.textContent = openingBalance.toFixed(2);
    }
}

// Initialize on page load - AUTO CALCULATE everything
document.addEventListener('DOMContentLoaded', function() {
    // Update opening balance display
    updateOpeningBalanceDisplay();
    
    // Initial calculation
    recalculateAllRows();
    calculateDenomination();
    
    // Watch for opening balance changes - AUTO RECALCULATE
    const openingBalanceInput = document.querySelector('input[name="opening_balance"]');
    if (openingBalanceInput) {
        openingBalanceInput.addEventListener('change', function() {
            openingBalance = Math.max(0, parseFloat(this.value || 0) || 0);
            updateOpeningBalanceDisplay();
            recalculateAllRows();
        });
        openingBalanceInput.addEventListener('input', function() {
            openingBalance = Math.max(0, parseFloat(this.value || 0) || 0);
            updateOpeningBalanceDisplay();
            recalculateAllRows();
        });
    }
    
    // Auto-calculate on any input change - Global event listener for real-time calculation
    document.addEventListener('input', function(e) {
        if (e.target.matches('input[type="number"]') && e.target.closest('#entriesBody')) {
            const row = e.target.closest('tr.data-row');
            if (row && !row.classList.contains('header-row-duplicate') && !row.classList.contains('calculation-row') && !row.classList.contains('opening-row')) {
                const rowIndex = parseInt(row.getAttribute('data-row-index'));
                if (!isNaN(rowIndex)) {
                    // Debounce calculation for performance
                    clearTimeout(window.calcTimeout);
                    window.calcTimeout = setTimeout(() => {
                        calculateRow(rowIndex);
                    }, 50);
                }
            }
        }
        
        // Auto-calculate denomination on input
        if (e.target.matches('.denomination-input')) {
            clearTimeout(window.denomTimeout);
            window.denomTimeout = setTimeout(() => {
                calculateDenomination();
            }, 50);
        }
    });
    
    // Auto-calculate on any change event (for dropdowns, date changes, etc.)
    document.addEventListener('change', function(e) {
        if (e.target.matches('input[type="number"]') && e.target.closest('#entriesBody')) {
            const row = e.target.closest('tr.data-row');
            if (row && !row.classList.contains('header-row-duplicate') && !row.classList.contains('calculation-row') && !row.classList.contains('opening-row')) {
                const rowIndex = parseInt(row.getAttribute('data-row-index'));
                if (!isNaN(rowIndex)) {
                    calculateRow(rowIndex);
                }
            }
        }
        
        if (e.target.matches('input[type="date"]') && e.target.closest('#entriesBody')) {
            const row = e.target.closest('tr.data-row');
            if (row && !row.classList.contains('header-row-duplicate') && !row.classList.contains('calculation-row') && !row.classList.contains('opening-row')) {
                const rowIndex = parseInt(row.getAttribute('data-row-index'));
                if (!isNaN(rowIndex)) {
                    calculateRow(rowIndex);
                }
            }
        }
    });
    
    // Auto-calculate on paste
    document.addEventListener('paste', function(e) {
        setTimeout(() => {
            if (e.target.matches('input[type="number"]') && e.target.closest('#entriesBody')) {
                const row = e.target.closest('tr.data-row');
                if (row && !row.classList.contains('header-row-duplicate') && !row.classList.contains('calculation-row') && !row.classList.contains('opening-row')) {
                    const rowIndex = parseInt(row.getAttribute('data-row-index'));
                    if (!isNaN(rowIndex)) {
                        calculateRow(rowIndex);
                    }
                }
            }
        }, 10);
    });
});
</script>

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