<?php
/**
 * Enterprise HRM ERP System - Petty Cash List
 * Excel-like daily cash flow
 */

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

$pageTitle = 'Petty Cash Management';
$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');

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

// Check if locked
$isLocked = isDataLocked('petty_cash', $siteId, $selectedMonth, $selectedYear);
if ($isLocked && !hasAdminAccess()) {
    requireUnlocked('petty_cash', $siteId, $selectedMonth, $selectedYear);
}

// Get petty cash transactions
$transactions = [];
$summary = ['opening' => 0, 'cash_in' => 0, 'cash_out' => 0, 'closing' => 0];

try {
    $db = getDB();
    
    // Get month closing
    $stmt = $db->prepare("
        SELECT * FROM petty_cash_closing
        WHERE site_id = ? AND month = ? AND year = ?
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $closing = $stmt->fetch();
    
    if ($closing) {
        $summary['opening'] = $closing['opening_balance'];
        $summary['cash_in'] = $closing['total_cash_in'];
        $summary['cash_out'] = $closing['total_cash_out'];
        $summary['closing'] = $closing['closing_balance'];
    }
    
    // Get transactions
    $stmt = $db->prepare("
        SELECT pc.*, eh.expense_head_name
        FROM petty_cash_transactions pc
        LEFT JOIN expense_heads eh ON pc.expense_head_id = eh.expense_head_id
        WHERE pc.site_id = ? AND pc.month = ? AND pc.year = ?
        ORDER BY pc.transaction_date, pc.transaction_id
    ");
    $stmt->execute([$siteId, $selectedMonth, $selectedYear]);
    $transactions = $stmt->fetchAll();
    
    // Calculate running balance if not closed
    if (!$closing) {
        $runningBalance = $summary['opening'];
        foreach ($transactions as &$t) {
            if ($t['transaction_type'] === 'cash_in') {
                $runningBalance += $t['amount'];
            } else {
                $runningBalance -= $t['amount'];
            }
            $t['running_balance'] = $runningBalance;
        }
        $summary['closing'] = $runningBalance;
    }
    
    // Get expense heads
    $stmt = $db->prepare("SELECT * FROM expense_heads WHERE site_id = ? AND is_active = 1 ORDER BY expense_head_name");
    $stmt->execute([$siteId]);
    $expenseHeads = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Petty cash list error: " . $e->getMessage());
    $expenseHeads = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Petty Cash Management</h2>
        <div style="display: flex; gap: 10px; align-items: center;">
            <select id="monthSelect" class="form-control" style="width: 120px;" onchange="updateMonthYear()">
                <?php for ($m = 1; $m <= 12; $m++): ?>
                <option value="<?php echo $m; ?>" <?php echo $selectedMonth == $m ? 'selected' : ''; ?>>
                    <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                </option>
                <?php endfor; ?>
            </select>
            <select id="yearSelect" class="form-control" style="width: 100px;" onchange="updateMonthYear()">
                <?php for ($y = date('Y') - 2; $y <= date('Y') + 1; $y++): ?>
                <option value="<?php echo $y; ?>" <?php echo $selectedYear == $y ? 'selected' : ''; ?>>
                    <?php echo $y; ?>
                </option>
                <?php endfor; ?>
            </select>
            <?php if (!$isLocked || hasAdminAccess()): ?>
            <a href="<?php echo BASE_URL; ?>/modules/petty_cash/create.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="btn btn-primary">Add Transaction</a>
            <?php endif; ?>
            <?php if (!$isLocked && hasAdminAccess()): ?>
            <a href="<?php echo BASE_URL; ?>/modules/petty_cash/closing.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="btn btn-secondary">Close Month</a>
            <?php endif; ?>
        </div>
    </div>
    
    <?php if ($isLocked): ?>
    <div class="alert alert-warning" style="margin-top: 20px;">
        <strong>⚠️ Locked:</strong> This month's petty cash is locked and cannot be modified.
        <?php if (hasAdminAccess()): ?>
        <a href="<?php echo BASE_URL; ?>/modules/petty_cash/unlock.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
           class="btn btn-sm btn-secondary" style="margin-left: 10px;">Unlock (Admin)</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <!-- Summary Cards -->
    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin-top: 20px;">
        <div class="stat-card" style="background: #dbeafe; border-left: 4px solid #1e40af;">
            <div class="stat-label">Opening Balance</div>
            <div class="stat-value"><?php echo formatCurrency($summary['opening']); ?></div>
        </div>
        <div class="stat-card" style="background: #d1fae5; border-left: 4px solid #065f46;">
            <div class="stat-label">Total Cash In</div>
            <div class="stat-value"><?php echo formatCurrency($summary['cash_in']); ?></div>
        </div>
        <div class="stat-card" style="background: #fee2e2; border-left: 4px solid #991b1b;">
            <div class="stat-label">Total Cash Out</div>
            <div class="stat-value"><?php echo formatCurrency($summary['cash_out']); ?></div>
        </div>
        <div class="stat-card" style="background: #fef3c7; border-left: 4px solid #92400e;">
            <div class="stat-label">Closing Balance</div>
            <div class="stat-value"><?php echo formatCurrency($summary['closing']); ?></div>
        </div>
    </div>
    
    <!-- Transactions Table -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Transactions - <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?></h3>
        
        <?php if (count($transactions) > 0): ?>
        <div style="overflow-x: auto;">
            <table class="data-table excel-grid">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Type</th>
                        <th>Expense Head</th>
                        <th>Description</th>
                        <th>Voucher No</th>
                        <th style="text-align: right;">Cash In</th>
                        <th style="text-align: right;">Cash Out</th>
                        <th style="text-align: right;">Balance</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $runningBalance = $summary['opening'];
                    foreach ($transactions as $t): 
                        if ($t['transaction_type'] === 'cash_in') {
                            $runningBalance += $t['amount'];
                        } else {
                            $runningBalance -= $t['amount'];
                        }
                    ?>
                    <tr>
                        <td><?php echo formatDate($t['transaction_date']); ?></td>
                        <td>
                            <span class="status-badge" style="background: <?php echo $t['transaction_type'] === 'cash_in' ? '#d1fae5' : '#fee2e2'; ?>; 
                                                                  color: <?php echo $t['transaction_type'] === 'cash_in' ? '#065f46' : '#991b1b'; ?>;">
                                <?php echo $t['transaction_type'] === 'cash_in' ? 'IN' : 'OUT'; ?>
                            </span>
                        </td>
                        <td><?php echo htmlspecialchars($t['expense_head_name'] ?? 'N/A'); ?></td>
                        <td><?php echo htmlspecialchars($t['description'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($t['voucher_number'] ?? ''); ?></td>
                        <td style="text-align: right;">
                            <?php if ($t['transaction_type'] === 'cash_in'): ?>
                            <strong style="color: #10b981;"><?php echo formatCurrency($t['amount']); ?></strong>
                            <?php else: ?>
                            -
                            <?php endif; ?>
                        </td>
                        <td style="text-align: right;">
                            <?php if ($t['transaction_type'] === 'cash_out'): ?>
                            <strong style="color: #ef4444;"><?php echo formatCurrency($t['amount']); ?></strong>
                            <?php else: ?>
                            -
                            <?php endif; ?>
                        </td>
                        <td style="text-align: right;"><strong><?php echo formatCurrency($runningBalance); ?></strong></td>
                        <td class="table-actions-cell">
                            <?php if (!$isLocked || hasAdminAccess()): ?>
                            <a href="<?php echo BASE_URL; ?>/modules/petty_cash/edit.php?id=<?php echo $t['transaction_id']; ?>" 
                               class="btn btn-sm btn-primary">Edit</a>
                            <?php else: ?>
                            <span style="color: var(--text-secondary);">Locked</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="table-empty">
            <div class="table-empty-icon">💵</div>
            <div class="table-empty-message">No petty cash transactions found for this month</div>
            <?php if (!$isLocked): ?>
            <div class="table-empty-submessage">
                <a href="<?php echo BASE_URL; ?>/modules/petty_cash/create.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                   class="btn btn-primary">Add First Transaction</a>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

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

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

