<?php
/**
 * Enterprise HRM ERP System - Petty Cash Report View
 * Date/Month/Year wise report viewing
 */

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

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

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

// Validate
if ($selectedMonth < 1 || $selectedMonth > 12) $selectedMonth = (int)date('m');
if ($selectedYear < 2020 || $selectedYear > 2100) $selectedYear = (int)date('Y');
if (!empty($selectedDate) && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $selectedDate)) {
    $selectedDate = '';
}

// Handle Excel Export
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    try {
        $db = getDB();
        
        // Get site name
        $siteStmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
        $siteStmt->execute([$siteId]);
        $siteData = $siteStmt->fetch();
        $exportSiteName = $siteData['site_name'] ?? '';
        
        // Build filename
        if (!empty($selectedDate)) {
            $exportFilename = 'Petty_Cash_Report_' . date('d_M_Y', strtotime($selectedDate)) . '_' . date('Ymd_His');
        } else {
            $exportFilename = 'Petty_Cash_Report_' . date('M_Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)) . '_' . date('Ymd_His');
        }
        
        // Build WHERE clause based on filters
        $whereConditions = ["p.site_id = ?"];
        $params = [$siteId];
        
        if (!empty($selectedDate)) {
            $whereConditions[] = "DATE(p.start_date) = ?";
            $params[] = $selectedDate;
        } else {
            $whereConditions[] = "p.month = ?";
            $whereConditions[] = "p.year = ?";
            $params[] = $selectedMonth;
            $params[] = $selectedYear;
        }
        
        $whereClause = implode(' AND ', $whereConditions);
        
        // Get all periods
        $stmt = $db->prepare("
            SELECT p.* FROM petty_cash_periods p
            WHERE {$whereClause}
            ORDER BY p.start_date DESC, p.period_id DESC
        ");
        $stmt->execute($params);
        $exportPeriods = $stmt->fetchAll();
        
        // Output Excel (HTML format)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="' . $exportFilename . '.xls"');
        header('Cache-Control: max-age=0');
        
        echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
        echo '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
        echo '<style>
            table { border-collapse: collapse; width: 100%; font-family: Arial, sans-serif; font-size: 10pt; }
            th { background-color: #808080; color: white; font-weight: bold; padding: 8px; text-align: center; border: 1px solid #000; }
            td { padding: 5px; border: 1px solid #ccc; text-align: left; }
            .text-right { text-align: right !important; }
            .site-info { font-weight: bold; font-size: 12pt; padding: 10px; border: none; }
            .period-header { background-color: #4a90e2 !important; color: white !important; font-weight: bold; }
            .total-row { background-color: #ffa500 !important; font-weight: bold; }
            .calculated { background-color: #f0f0f0 !important; font-weight: bold; }
        </style></head><body>';
        
        // Add site info
        echo '<table style="margin-bottom: 10px; border: none;">';
        echo '<tr><td class="site-info" style="border: none;">Site: ' . htmlspecialchars($exportSiteName) . '</td></tr>';
        if (!empty($selectedDate)) {
            echo '<tr><td style="border: none; font-weight: bold;">Date: ' . date('d M Y', strtotime($selectedDate)) . '</td></tr>';
        } else {
            echo '<tr><td style="border: none; font-weight: bold;">Period: ' . date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)) . '</td></tr>';
        }
        echo '<tr><td style="border: none;">Export Date: ' . date('d-m-Y H:i') . '</td></tr>';
        echo '</table>';
        
        // Export each period with its entries
        foreach ($exportPeriods as $period) {
            // Get entries for this period
            $entryStmt = $db->prepare("SELECT * FROM petty_cash_entries WHERE period_id = ? ORDER BY entry_date, sr_no, entry_id");
            $entryStmt->execute([$period['period_id']]);
            $entries = $entryStmt->fetchAll();
            
            echo '<table style="margin-top: 20px;">';
            
            // Period header
            echo '<tr class="period-header">';
            echo '<td colspan="22" style="background-color: #4a90e2; color: white; font-weight: bold; padding: 10px;">';
            echo htmlspecialchars($period['period_name']) . ' | ';
            echo date('d M Y', strtotime($period['start_date'])) . ' to ' . date('d M Y', strtotime($period['end_date']));
            echo ' | Opening: ' . number_format($period['opening_balance'], 2);
            echo '</td></tr>';
            
            // Column headers
            echo '<tr>';
            echo '<th>Date</th>';
            echo '<th>Voucher No</th>';
            echo '<th>Description</th>';
            echo '<th>Cash In Hand</th>';
            echo '<th>From Finance</th>';
            echo '<th>Other Receipt</th>';
            echo '<th>Total Cash Out</th>';
            echo '<th>Purchase Catering</th>';
            echo '<th>Purchase HK</th>';
            echo '<th>Maintenance</th>';
            echo '<th>Impres Money</th>';
            echo '<th>Printing</th>';
            echo '<th>Grocery/Cutlery</th>';
            echo '<th>Mobile/Tel</th>';
            echo '<th>Conveyance</th>';
            echo '<th>Courier</th>';
            echo '<th>Staff Welfare</th>';
            echo '<th>Other Misc</th>';
            echo '<th>Decoration</th>';
            echo '<th>Bank Deposit</th>';
            echo '<th>Balance</th>';
            echo '<th>Reimb/Non-Reimb</th>';
            echo '</tr>';
            
            // Data rows
            $runningBalance = $period['opening_balance'];
            foreach ($entries as $entry) {
                $runningBalance = $runningBalance + $entry['total_cash_in_hand'] + $entry['received_from_finance'] + $entry['other_receipt'] - $entry['total_cash_out'];
                
                echo '<tr>';
                echo '<td>' . date('d-m-Y', strtotime($entry['entry_date'])) . '</td>';
                echo '<td>' . htmlspecialchars($entry['voucher_no'] ?? '') . '</td>';
                echo '<td>' . htmlspecialchars($entry['description_bill'] ?? '') . '</td>';
                echo '<td class="text-right">' . number_format($entry['total_cash_in_hand'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['received_from_finance'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['other_receipt'], 2) . '</td>';
                echo '<td class="text-right calculated">' . number_format($entry['total_cash_out'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['purchase_catering'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['purchase_hk'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['maintenance'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['impres_money_commission'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['printing_stationery'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['grocery_cutlery_rent_hire'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['mobile_tel'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['local_conveyance'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['courier'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['staff_welfare'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['other_misc'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['decoration_charges'], 2) . '</td>';
                echo '<td class="text-right">' . number_format($entry['bank_deposit'], 2) . '</td>';
                echo '<td class="text-right calculated">' . number_format($runningBalance, 2) . '</td>';
                echo '<td>' . htmlspecialchars($entry['reimbursable_non_reimbursable'] ?? '') . '</td>';
                echo '</tr>';
            }
            
            // Total row
            echo '<tr class="total-row">';
            echo '<td colspan="3" style="background-color: #ffa500;"><strong>Closing Balance</strong></td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'total_cash_in_hand')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'received_from_finance')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'other_receipt')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'total_cash_out')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'purchase_catering')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'purchase_hk')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'maintenance')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'impres_money_commission')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'printing_stationery')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'grocery_cutlery_rent_hire')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'mobile_tel')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'local_conveyance')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'courier')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'staff_welfare')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'other_misc')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'decoration_charges')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;">' . number_format(array_sum(array_column($entries, 'bank_deposit')), 2) . '</td>';
            echo '<td class="text-right" style="background-color: #ffa500;"><strong>' . number_format($runningBalance, 2) . '</strong></td>';
            echo '<td style="background-color: #ffa500;"></td>';
            echo '</tr>';
            
            echo '</table>';
        }
        
        if (empty($exportPeriods)) {
            echo '<table><tr><td style="text-align: center; padding: 20px;">No data found for the selected period.</td></tr></table>';
        }
        
        echo '</body></html>';
        exit;
        
    } catch (Exception $e) {
        error_log("Petty cash export error: " . $e->getMessage());
        $_SESSION['error'] = 'Error exporting data: ' . $e->getMessage();
    }
}

// Handle delete request
if (isset($_GET['delete']) && $_GET['delete'] > 0) {
    $deletePeriodId = (int)$_GET['delete'];
    
    try {
        $db = getDB();
        $db->beginTransaction();
        
        // Verify period exists and belongs to this site
        $stmt = $db->prepare("SELECT period_id, period_name FROM petty_cash_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$deletePeriodId, $siteId]);
        $periodToDelete = $stmt->fetch();
        
        if (!$periodToDelete) {
            throw new Exception('Period not found or you do not have permission to delete it.');
        }
        
        // Delete all entries for this period
        $stmt = $db->prepare("DELETE FROM petty_cash_entries WHERE period_id = ?");
        $stmt->execute([$deletePeriodId]);
        
        // Delete period details
        $stmt = $db->prepare("DELETE FROM petty_cash_period_details WHERE period_id = ?");
        $stmt->execute([$deletePeriodId]);
        
        // Delete the period
        $stmt = $db->prepare("DELETE FROM petty_cash_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$deletePeriodId, $siteId]);
        
        $db->commit();
        
        $_SESSION['success'] = 'Report deleted successfully.';
        
        if (function_exists('logAudit')) {
            logAudit('DELETE', 'petty_cash_periods', $deletePeriodId, "Deleted period: {$periodToDelete['period_name']}");
        }
        
        // Preserve filter in redirect
        $redirectUrl = $_SERVER['PHP_SELF'];
        if (!empty($selectedDate)) {
            $redirectUrl .= '?date=' . urlencode($selectedDate);
        } else {
            $redirectUrl .= '?month=' . $selectedMonth . '&year=' . $selectedYear;
        }
        header('Location: ' . $redirectUrl);
        exit;
        
    } catch (Exception $e) {
        if (isset($db) && $db->inTransaction()) {
            $db->rollBack();
        }
        $_SESSION['error'] = 'Error deleting report: ' . $e->getMessage();
        // Preserve filter in redirect
        $redirectUrl = $_SERVER['PHP_SELF'];
        if (!empty($selectedDate)) {
            $redirectUrl .= '?date=' . urlencode($selectedDate);
        } else {
            $redirectUrl .= '?month=' . $selectedMonth . '&year=' . $selectedYear;
        }
        header('Location: ' . $redirectUrl);
        exit;
    }
}

try {
    $db = getDB();
    
    // Build WHERE clause based on filters
    $whereConditions = ["p.site_id = ?"];
    $params = [$siteId];
    
    // Date filter (if provided)
    if (!empty($selectedDate)) {
        $whereConditions[] = "DATE(p.start_date) = ?";
        $params[] = $selectedDate;
    } else {
        // Month/Year filter (if date not provided)
        $whereConditions[] = "p.month = ?";
        $whereConditions[] = "p.year = ?";
        $params[] = $selectedMonth;
        $params[] = $selectedYear;
    }
    
    $whereClause = implode(' AND ', $whereConditions);
    
    // Get all periods with filters (Date OR Month/Year)
    $stmt = $db->prepare("
        SELECT DISTINCT p.period_id, p.period_name, p.start_date, p.end_date,
               p.month, p.year, p.opening_balance, p.closing_balance,
               COUNT(DISTINCT pe.entry_id) as entry_count,
               COALESCE(SUM(pe.total_cash_in_hand + pe.received_from_finance + pe.other_receipt), 0) as total_cash_in,
               COALESCE(SUM(pe.total_cash_out), 0) as total_cash_out
        FROM petty_cash_periods p
        LEFT JOIN petty_cash_entries pe ON p.period_id = pe.period_id
        WHERE {$whereClause}
        GROUP BY p.period_id
        ORDER BY p.start_date DESC, p.period_id DESC
    ");
    $stmt->execute($params);
    $periods = $stmt->fetchAll();
    
    // Group periods by date for better display
    $periodsByDate = [];
    foreach ($periods as $p) {
        $dateKey = date('Y-m-d', strtotime($p['start_date']));
        if (!isset($periodsByDate[$dateKey])) {
            $periodsByDate[$dateKey] = [];
        }
        $periodsByDate[$dateKey][] = $p;
    }
    
    // Load specific period details if viewing
    $period = null;
    $entries = [];
    $periodDetails = null;
    
    if ($viewPeriodId > 0) {
        $stmt = $db->prepare("SELECT * FROM petty_cash_periods WHERE period_id = ? AND site_id = ?");
        $stmt->execute([$viewPeriodId, $siteId]);
        $period = $stmt->fetch();
        
        if ($period) {
            $stmt = $db->prepare("
                SELECT * FROM petty_cash_entries 
                WHERE period_id = ? 
                ORDER BY entry_date, sr_no, entry_id
            ");
            $stmt->execute([$viewPeriodId]);
            $entries = $stmt->fetchAll();
            
            // Load period details
            $stmt = $db->prepare("SELECT * FROM petty_cash_period_details WHERE period_id = ?");
            $stmt->execute([$viewPeriodId]);
            $periodDetails = $stmt->fetch();
        }
    }
    
} catch (Exception $e) {
    error_log("Petty cash report error: " . $e->getMessage());
    $periods = [];
    $periodsByDate = [];
    $entries = [];
}

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

// Show 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 (isset($_SESSION['error'])) {
    echo '<div class="alert alert-danger" style="background: #f8d7da; color: #721c24; padding: 12px; margin: 10px 0; border: 1px solid #f5c6cb; border-radius: 4px;">';
    echo htmlspecialchars($_SESSION['error']);
    echo '</div>';
    unset($_SESSION['error']);
}
?>

<style>
.report-container {
    background: #fff;
    padding: 20px;
    font-family: Arial, sans-serif;
}

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

.report-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
    font-size: 12px;
}

.report-table th {
    background: #4a90e2;
    color: #fff;
    padding: 10px;
    text-align: left;
    border: 1px solid #2a6eb8;
}

.report-table td {
    padding: 8px;
    border: 1px solid #ddd;
}

.btn-view, .btn-edit, .btn-delete {
    padding: 5px 10px;
    color: #fff;
    text-decoration: none;
    border-radius: 3px;
    font-size: 12px;
    margin: 2px;
    display: inline-block;
}

.btn-view {
    background: #28a745;
}

.btn-edit {
    background: #ffc107;
    color: #000;
    font-weight: bold;
}

.btn-delete {
    background: #dc3545;
    border: none;
    cursor: pointer;
}

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

.excel-table thead {
    background: #808080;
    color: #fff;
}

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

.excel-table tbody td {
    padding: 4px;
    border: 1px solid #000;
    text-align: left;
    font-size: 11px;
}

.excel-table .text-right {
    text-align: right !important;
}

.excel-table .calculated {
    background: #f0f0f0;
    font-weight: bold;
    text-align: right;
}

.excel-table .total-row {
    background: #ffa500 !important;
    color: #000 !important;
    font-weight: bold;
}

.excel-table .total-row td {
    background: #ffa500 !important;
    border: 1px solid #000 !important;
}

.summary-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 15px;
    margin: 20px 0;
}

.summary-card {
    background: #fff;
    padding: 15px;
    border-radius: 6px;
    border-left: 4px solid #4a90e2;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.summary-card-label {
    font-size: 12px;
    color: #666;
    margin-bottom: 5px;
}

.summary-card-value {
    font-size: 20px;
    font-weight: bold;
    color: #333;
}

.btn-export {
    background: #28a745;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    white-space: nowrap;
}

.btn-export:hover {
    background: #218838;
}

.btn-export:disabled {
    background: #6c757d;
    cursor: not-allowed;
    opacity: 0.6;
}
</style>

<div class="report-container">
    <h2>Cash Expenses Summary - Reports</h2>
    
    <!-- Filter Section -->
    <div class="filter-section" style="display: flex; align-items: center; gap: 15px; flex-wrap: wrap;">
        <div>
            <label><strong>Filter By:</strong></label>
        </div>
        
        <div>
            <label>Date:</label>
            <input type="date" id="filter_date" value="<?php echo htmlspecialchars($selectedDate); ?>" 
                   onchange="filterByDate()" style="padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
            <button onclick="clearDateFilter()" style="padding: 5px 10px; margin-left: 5px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer;">Clear</button>
        </div>
        
        <div style="margin-left: 20px;">
            <label>OR Month:</label>
            <select id="filter_month" onchange="filterReport()" style="padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                <?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>
        </div>
        
        <div>
            <label>Year:</label>
            <input type="number" id="filter_year" value="<?php echo $selectedYear; ?>" 
                   min="2020" max="2100" onchange="filterReport()" 
                   style="width: 100px; padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
        </div>
        
        <div style="margin-left: auto; display: flex; gap: 10px; align-items: center;">
            <button type="button" class="btn-export" onclick="exportToExcel()" title="Export to Excel" style="background: #28a745; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 12px; font-weight: 500; display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;">
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                Export
            </button>
            <a href="<?php echo BASE_URL; ?>/modules/petty_cash/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="btn-view" style="text-decoration: none; padding: 8px 15px;">← Back to Entry</a>
        </div>
    </div>
    
    <?php if ($viewPeriodId > 0 && $period): ?>
    <!-- Detailed View for Single Period -->
    <div style="margin-bottom: 20px;">
        <a href="?<?php 
            if (!empty($selectedDate)) {
                echo 'date=' . urlencode($selectedDate);
            } else {
                echo 'month=' . $selectedMonth . '&year=' . $selectedYear;
            }
        ?>" 
           class="btn-view" style="text-decoration: none; padding: 8px 15px; background: #28a745; border-radius: 4px; color: white;">← Back to Reports List</a>
    </div>
    
    <div class="detailed-report-section">
        <h3><?php echo htmlspecialchars($period['period_name']); ?></h3>
        <p><strong>Period:</strong> <?php echo date('d M Y', strtotime($period['start_date'])); ?> to <?php echo date('d M Y', strtotime($period['end_date'])); ?></p>
        
        <!-- Summary Cards -->
        <div class="summary-cards">
            <div class="summary-card" style="border-left-color: #1e40af;">
                <div class="summary-card-label">Opening Balance</div>
                <div class="summary-card-value"><?php echo number_format($period['opening_balance'], 2); ?></div>
            </div>
            <div class="summary-card" style="border-left-color: #065f46;">
                <div class="summary-card-label">Total Cash In</div>
                <div class="summary-card-value"><?php echo number_format($period['opening_balance'] + array_sum(array_column($entries, 'total_cash_in_hand')) + array_sum(array_column($entries, 'received_from_finance')) + array_sum(array_column($entries, 'other_receipt')), 2); ?></div>
            </div>
            <div class="summary-card" style="border-left-color: #991b1b;">
                <div class="summary-card-label">Total Cash Out</div>
                <div class="summary-card-value"><?php echo number_format(array_sum(array_column($entries, 'total_cash_out')), 2); ?></div>
            </div>
            <div class="summary-card" style="border-left-color: #92400e;">
                <div class="summary-card-label">Closing Balance</div>
                <div class="summary-card-value"><?php 
                    // Excel Formula: Closing Balance = Opening + Total Cash In - Total Cash Out (Bank Deposit NOT subtracted)
                    $closing = $period['opening_balance'] + array_sum(array_column($entries, 'total_cash_in_hand')) + array_sum(array_column($entries, 'received_from_finance')) + array_sum(array_column($entries, 'other_receipt')) - array_sum(array_column($entries, 'total_cash_out'));
                    echo number_format($closing, 2); 
                ?></div>
            </div>
        </div>
        
        <!-- Detailed Table -->
        <div style="overflow-x: auto; margin-top: 20px;">
            <table class="excel-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Voucher No</th>
                        <th>Description Bill</th>
                        <th>Total Cash In Hand</th>
                        <th>Received from Finance</th>
                        <th>Other Receipt</th>
                        <th>Total Cash Out</th>
                        <th>Purchase Catering</th>
                        <th>Purchase HK</th>
                        <th>Maintenance</th>
                        <th>Impres Money Commission</th>
                        <th>Printing Stationery</th>
                        <th>Grocery & Cutlery & Rent & Hire</th>
                        <th>Mobile/Tel</th>
                        <th>Local Conveyance</th>
                        <th>Courier</th>
                        <th>Staff Welfare</th>
                        <th>Other Misc</th>
                        <th>Decoration Charges</th>
                        <th>Bank Deposit</th>
                        <th>Balance In Hand</th>
                        <th>Reimbursable/Non-reimbursable</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    // Calculate running balance - EXACT EXCEL FORMULA: W10 = F9+G10+H10-I10
                    $runningBalance = $period['opening_balance'];
                    foreach ($entries as $entry): 
                        // Excel Formula: Balance = Previous Balance + Total Cash In Hand + Received from Finance + Other Receipt - Total Cash Out
                        $runningBalance = $runningBalance + $entry['total_cash_in_hand'] + $entry['received_from_finance'] + $entry['other_receipt'] - $entry['total_cash_out'];
                    ?>
                    <tr>
                        <td><?php echo date('d M Y', strtotime($entry['entry_date'])); ?></td>
                        <td><?php echo htmlspecialchars($entry['voucher_no'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($entry['description_bill'] ?? ''); ?></td>
                        <td class="text-right"><?php echo number_format($entry['total_cash_in_hand'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['received_from_finance'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['other_receipt'], 2); ?></td>
                        <td class="text-right calculated"><?php echo number_format($entry['total_cash_out'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['purchase_catering'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['purchase_hk'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['maintenance'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['impres_money_commission'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['printing_stationery'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['grocery_cutlery_rent_hire'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['mobile_tel'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['local_conveyance'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['courier'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['staff_welfare'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['other_misc'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['decoration_charges'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($entry['bank_deposit'], 2); ?></td>
                        <td class="text-right calculated"><?php echo number_format($runningBalance, 2); ?></td>
                        <td><?php echo htmlspecialchars($entry['reimbursable_non_reimbursable'] ?? ''); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    
                    <!-- Closing Balance Row -->
                    <tr class="total-row">
                        <td colspan="3"><strong>Closing Balance</strong></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'total_cash_in_hand')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'received_from_finance')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'other_receipt')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'total_cash_out')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'purchase_catering')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'purchase_hk')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'maintenance')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'impres_money_commission')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'printing_stationery')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'grocery_cutlery_rent_hire')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'mobile_tel')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'local_conveyance')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'courier')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'staff_welfare')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'other_misc')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'decoration_charges')), 2); ?></td>
                        <td class="text-right"><?php echo number_format(array_sum(array_column($entries, 'bank_deposit')), 2); ?></td>
                        <td class="text-right"><?php echo number_format($runningBalance, 2); ?></td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <!-- Period Details -->
        <?php if ($periodDetails): ?>
        <div style="margin-top: 30px; display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
            <div>
                <h4>Remarks</h4>
                <p><?php echo nl2br(htmlspecialchars($periodDetails['remarks'] ?? '')); ?></p>
                
                <div style="margin-top: 20px;">
                    <strong>Prepared By:</strong><br>
                    Signature: <?php echo htmlspecialchars($periodDetails['prepared_by_signature'] ?? ''); ?><br>
                    Name: <?php echo htmlspecialchars($periodDetails['prepared_by_name'] ?? ''); ?>
                </div>
                
                <div style="margin-top: 15px;">
                    <strong>Approved By:</strong><br>
                    Signature: <?php echo htmlspecialchars($periodDetails['approved_by_signature'] ?? ''); ?><br>
                    Name: <?php echo htmlspecialchars($periodDetails['approved_by_name'] ?? ''); ?>
                </div>
            </div>
            
            <div>
                <h4>Denomination</h4>
                <table style="width: 300px; border-collapse: collapse;">
                    <thead>
                        <tr style="background: #808080; color: #fff;">
                            <th style="padding: 4px; border: 1px solid #000;">Note</th>
                            <th style="padding: 4px; border: 1px solid #000;">Count</th>
                            <th style="padding: 4px; border: 1px solid #000;">Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $denominations = [
                            ['value' => 2000, 'count' => $periodDetails['denomination_2000'] ?? 0],
                            ['value' => 500, 'count' => $periodDetails['denomination_500'] ?? 0],
                            ['value' => 200, 'count' => $periodDetails['denomination_200'] ?? 0],
                            ['value' => 100, 'count' => $periodDetails['denomination_100'] ?? 0],
                            ['value' => 50, 'count' => $periodDetails['denomination_50'] ?? 0],
                            ['value' => 20, 'count' => $periodDetails['denomination_20'] ?? 0],
                            ['value' => 10, 'count' => $periodDetails['denomination_10'] ?? 0],
                            ['value' => 5, 'count' => $periodDetails['denomination_5'] ?? 0],
                            ['value' => 2, 'count' => $periodDetails['denomination_2'] ?? 0],
                            ['value' => 1, 'count' => $periodDetails['denomination_1'] ?? 0],
                        ];
                        $calculatedTotal = 0;
                        foreach ($denominations as $denom): 
                            $denomAmount = $denom['value'] * $denom['count'];
                            $calculatedTotal += $denomAmount;
                        ?>
                        <tr>
                            <td style="padding: 4px; border: 1px solid #000; text-align: center;">₹<?php echo $denom['value']; ?></td>
                            <td style="padding: 4px; border: 1px solid #000; text-align: center;"><?php echo $denom['count']; ?></td>
                            <td style="padding: 4px; border: 1px solid #000; text-align: right;"><?php echo number_format($denomAmount, 2); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr style="background: #d4edda; font-weight: bold;">
                            <td colspan="2" style="padding: 4px; border: 1px solid #000;">Total Amount</td>
                            <td style="padding: 4px; border: 1px solid #000; text-align: right; color: #155724;"><?php echo number_format($calculatedTotal, 2); ?></td>
                        </tr>
                        <?php 
                        // Calculate closing balance for difference
                        $closingBalance = $period['opening_balance'] + array_sum(array_column($entries, 'total_cash_in_hand')) + array_sum(array_column($entries, 'received_from_finance')) + array_sum(array_column($entries, 'other_receipt')) - array_sum(array_column($entries, 'total_cash_out'));
                        $difference = $closingBalance - $calculatedTotal;
                        ?>
                        <tr style="background: <?php echo abs($difference) < 0.01 ? '#d4edda' : '#f8d7da'; ?>; font-weight: bold;">
                            <td colspan="2" style="padding: 4px; border: 1px solid #000;">Closing Balance</td>
                            <td style="padding: 4px; border: 1px solid #000; text-align: right;"><?php echo number_format($closingBalance, 2); ?></td>
                        </tr>
                        <tr style="background: <?php echo abs($difference) < 0.01 ? '#d4edda' : '#f8d7da'; ?>; font-weight: bold;">
                            <td colspan="2" style="padding: 4px; border: 1px solid #000;">Difference</td>
                            <td style="padding: 4px; border: 1px solid #000; text-align: right; color: <?php echo abs($difference) < 0.01 ? '#155724' : '#721c24'; ?>;"><?php echo number_format($difference, 2); ?></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <?php else: ?>
    <!-- Summary Table - All Reports List -->
    <?php if (empty($periods)): ?>
    <div class="alert alert-info" style="background: #d1ecf1; color: #0c5460; padding: 15px; border: 1px solid #bee5eb; border-radius: 4px; margin: 20px 0;">
        <strong>No reports found</strong>
        <?php if (!empty($selectedDate)): ?>
            for date <?php echo date('d M Y', strtotime($selectedDate)); ?>.
        <?php else: ?>
            for <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?>.
        <?php endif; ?>
        <br>
        <a href="<?php echo BASE_URL; ?>/modules/petty_cash/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
           style="color: #0c5460; text-decoration: underline;">
            Create a new period
        </a>
    </div>
    <?php else: ?>
    
    <h3>
        Reports 
        <?php if (!empty($selectedDate)): ?>
            for Date: <?php echo date('d M Y', strtotime($selectedDate)); ?>
        <?php else: ?>
            for <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?>
        <?php endif; ?>
        (<?php echo count($periods); ?> submission<?php echo count($periods) > 1 ? 's' : ''; ?>)
    </h3>
    
    <!-- Group by Date if multiple submissions -->
    <?php if (count($periods) > 1 && empty($selectedDate)): ?>
        <?php foreach ($periodsByDate as $dateKey => $datePeriods): ?>
        <div style="margin-bottom: 30px;">
            <h4 style="background: #e9ecef; padding: 10px; margin: 0 0 10px 0; border-left: 4px solid #4a90e2;">
                📅 Date: <?php echo date('d M Y', strtotime($dateKey)); ?> 
                (<?php echo count($datePeriods); ?> submission<?php echo count($datePeriods) > 1 ? 's' : ''; ?>)
            </h4>
            
            <table class="report-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Period Name</th>
                        <th>From Date</th>
                        <th>To Date</th>
                        <th>Opening Balance</th>
                        <th>Total Cash In</th>
                        <th>Total Cash Out</th>
                        <th>Closing Balance</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($datePeriods as $index => $p): ?>
                    <tr>
                        <td style="text-align: center; font-weight: bold;"><?php echo $index + 1; ?></td>
                        <td><strong><?php echo htmlspecialchars($p['period_name'] ?: 'N/A'); ?></strong></td>
                        <td><?php echo date('d M Y', strtotime($p['start_date'])); ?></td>
                        <td><?php echo date('d M Y', strtotime($p['end_date'])); ?></td>
                        <td class="text-right"><?php echo number_format($p['opening_balance'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($p['total_cash_in'], 2); ?></td>
                        <td class="text-right"><?php echo number_format($p['total_cash_out'], 2); ?></td>
                        <td class="text-right"><strong><?php echo number_format($p['opening_balance'] + $p['total_cash_in'] - $p['total_cash_out'], 2); ?></strong></td>
                        <td>
                            <a href="?view=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?><?php echo !empty($selectedDate) ? '&date=' . urlencode($selectedDate) : ''; ?>" 
                               class="btn-view" style="background: #28a745; padding: 6px 12px; border-radius: 4px;">✓ View Details</a>
                            <a href="<?php echo BASE_URL; ?>/modules/petty_cash/list.php?period_id=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                               class="btn-edit" style="background: #ffc107; color: #000; padding: 6px 12px; border-radius: 4px; text-decoration: none; font-weight: bold;">✏️ Edit</a>
                            <a href="?delete=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?><?php echo !empty($selectedDate) ? '&date=' . urlencode($selectedDate) : ''; ?>" 
                               class="btn-delete" 
                               onclick="return confirm('Are you sure you want to delete this report?\n\nPeriod: <?php echo addslashes($p['period_name']); ?>\n\nThis action cannot be undone!');"
                               style="background: #dc3545; padding: 6px 12px; border-radius: 4px; text-decoration: none;">🗑️ Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endforeach; ?>
    <?php else: ?>
    <!-- Single submission or date filter active -->
    <table class="report-table">
        <thead>
            <tr>
                <th>#</th>
                <th>Period Name</th>
                <th>From Date</th>
                <th>To Date</th>
                <th>Opening Balance</th>
                <th>Total Cash In</th>
                <th>Total Cash Out</th>
                <th>Closing Balance</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($periods as $index => $p): ?>
            <tr>
                <td style="text-align: center; font-weight: bold;"><?php echo $index + 1; ?></td>
                <td><strong><?php echo htmlspecialchars($p['period_name'] ?: 'N/A'); ?></strong></td>
                <td><?php echo date('d M Y', strtotime($p['start_date'])); ?></td>
                <td><?php echo date('d M Y', strtotime($p['end_date'])); ?></td>
                <td class="text-right"><?php echo number_format($p['opening_balance'], 2); ?></td>
                <td class="text-right"><?php echo number_format($p['total_cash_in'], 2); ?></td>
                <td class="text-right"><?php echo number_format($p['total_cash_out'], 2); ?></td>
                <td class="text-right"><strong><?php echo number_format($p['opening_balance'] + $p['total_cash_in'] - $p['total_cash_out'], 2); ?></strong></td>
                <td>
                    <a href="?view=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?><?php echo !empty($selectedDate) ? '&date=' . urlencode($selectedDate) : ''; ?>" 
                       class="btn-view" style="background: #28a745; padding: 6px 12px; border-radius: 4px;">✓ View Details</a>
                    <a href="<?php echo BASE_URL; ?>/modules/petty_cash/list.php?period_id=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                       class="btn-edit" style="background: #ffc107; color: #000; padding: 6px 12px; border-radius: 4px; text-decoration: none; font-weight: bold;">✏️ Edit</a>
                    <a href="?delete=<?php echo $p['period_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?><?php echo !empty($selectedDate) ? '&date=' . urlencode($selectedDate) : ''; ?>" 
                       class="btn-delete" 
                       onclick="return confirm('Are you sure you want to delete this report?\n\nPeriod: <?php echo addslashes($p['period_name']); ?>\n\nThis action cannot be undone!');"
                       style="background: #dc3545; padding: 6px 12px; border-radius: 4px; text-decoration: none;">🗑️ Delete</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
    <?php endif; ?>
    <?php endif; ?>
</div>

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

function filterByDate() {
    const date = document.getElementById('filter_date').value;
    if (date) {
        window.location.href = '?date=' + encodeURIComponent(date);
    }
}

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

function exportToExcel() {
    const btn = document.querySelector('.btn-export');
    if (!btn) return;
    
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg> Exporting...';
    
    // Get current filter values
    const date = document.getElementById('filter_date').value;
    const month = document.getElementById('filter_month').value;
    const year = document.getElementById('filter_year').value;
    
    // Build export URL with current filters
    let exportUrl = window.location.pathname + '?export=excel';
    if (date) {
        exportUrl += '&date=' + encodeURIComponent(date);
    } else {
        exportUrl += '&month=' + month + '&year=' + year;
    }
    
    // Trigger download
    window.location.href = exportUrl;
    
    // Reset button after a short delay
    setTimeout(function() {
        btn.disabled = false;
        btn.innerHTML = originalText;
    }, 2000);
}
</script>

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