<?php
/**
 * Enterprise HRM ERP System - Create Petty Cash Transaction
 */

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

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

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

$errors = [];
$formData = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'transaction_date' => $_POST['transaction_date'] ?? '',
        'transaction_type' => sanitize($_POST['transaction_type'] ?? 'cash_out'),
        'amount' => isset($_POST['amount']) ? (float)$_POST['amount'] : 0,
        'expense_head_id' => isset($_POST['expense_head_id']) && $_POST['expense_head_id'] > 0 ? (int)$_POST['expense_head_id'] : null,
        'description' => sanitize($_POST['description'] ?? ''),
        'voucher_number' => sanitize($_POST['voucher_number'] ?? ''),
        'denomination_500' => isset($_POST['denomination_500']) ? (int)$_POST['denomination_500'] : 0,
        'denomination_200' => isset($_POST['denomination_200']) ? (int)$_POST['denomination_200'] : 0,
        'denomination_100' => isset($_POST['denomination_100']) ? (int)$_POST['denomination_100'] : 0,
        'denomination_50' => isset($_POST['denomination_50']) ? (int)$_POST['denomination_50'] : 0,
        'denomination_20' => isset($_POST['denomination_20']) ? (int)$_POST['denomination_20'] : 0,
        'denomination_10' => isset($_POST['denomination_10']) ? (int)$_POST['denomination_10'] : 0,
        'denomination_5' => isset($_POST['denomination_5']) ? (int)$_POST['denomination_5'] : 0,
        'denomination_2' => isset($_POST['denomination_2']) ? (int)$_POST['denomination_2'] : 0,
        'denomination_1' => isset($_POST['denomination_1']) ? (int)$_POST['denomination_1'] : 0,
    ];
    
    // Validation
    if (empty($formData['transaction_date'])) {
        $errors[] = 'Transaction date is required.';
    }
    
    if ($formData['amount'] <= 0) {
        $errors[] = 'Amount must be greater than 0.';
    }
    
    if ($formData['transaction_type'] === 'cash_out' && empty($formData['expense_head_id'])) {
        $errors[] = 'Expense head is required for cash out transactions.';
    }
    
    // Calculate denomination total
    $denominationTotal = ($formData['denomination_500'] * 500) +
                        ($formData['denomination_200'] * 200) +
                        ($formData['denomination_100'] * 100) +
                        ($formData['denomination_50'] * 50) +
                        ($formData['denomination_20'] * 20) +
                        ($formData['denomination_10'] * 10) +
                        ($formData['denomination_5'] * 5) +
                        ($formData['denomination_2'] * 2) +
                        ($formData['denomination_1'] * 1);
    
    if ($formData['transaction_type'] === 'cash_in' && abs($denominationTotal - $formData['amount']) > 0.01) {
        $errors[] = 'Denomination total does not match the amount.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            $month = (int)date('m', strtotime($formData['transaction_date']));
            $year = (int)date('Y', strtotime($formData['transaction_date']));
            
            // Insert transaction
            $stmt = $db->prepare("
                INSERT INTO petty_cash_transactions (
                    site_id, transaction_date, transaction_type, amount,
                    expense_head_id, description, voucher_number,
                    denomination_500, denomination_200, denomination_100,
                    denomination_50, denomination_20, denomination_10,
                    denomination_5, denomination_2, denomination_1,
                    month, year, created_by
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $siteId,
                $formData['transaction_date'],
                $formData['transaction_type'],
                $formData['amount'],
                $formData['expense_head_id'],
                $formData['description'],
                $formData['voucher_number'],
                $formData['denomination_500'],
                $formData['denomination_200'],
                $formData['denomination_100'],
                $formData['denomination_50'],
                $formData['denomination_20'],
                $formData['denomination_10'],
                $formData['denomination_5'],
                $formData['denomination_2'],
                $formData['denomination_1'],
                $month,
                $year,
                getCurrentUserId()
            ]);
            
            $db->commit();
            
            logAudit('CREATE', 'petty_cash_transactions', $db->lastInsertId());
            
            redirect(BASE_URL . '/modules/petty_cash/list.php?month=' . $month . '&year=' . $year, 'Petty cash transaction created successfully.');
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error creating petty cash transaction: " . $e->getMessage());
            $errors[] = 'An error occurred while creating transaction. Please try again.';
        }
    }
}

// Get expense heads
try {
    $db = getDB();
    $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("Error loading expense heads: " . $e->getMessage());
    $expenseHeads = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Add Petty Cash Transaction</h2>
        <a href="<?php echo BASE_URL; ?>/modules/petty_cash/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
           class="btn btn-secondary">Back to Petty Cash</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" id="pettyCashForm" style="margin-top: 20px;">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label" for="transaction_date">Transaction Date *</label>
                <input type="date" id="transaction_date" name="transaction_date" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['transaction_date'] ?? date('Y-m-d')); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="transaction_type">Transaction Type *</label>
                <select id="transaction_type" name="transaction_type" class="form-control" required onchange="toggleExpenseHead()">
                    <option value="cash_in" <?php echo ($formData['transaction_type'] ?? 'cash_out') === 'cash_in' ? 'selected' : ''; ?>>Cash In</option>
                    <option value="cash_out" <?php echo ($formData['transaction_type'] ?? 'cash_out') === 'cash_out' ? 'selected' : ''; ?>>Cash Out</option>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="amount">Amount *</label>
                <input type="number" id="amount" name="amount" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['amount'] ?? ''); ?>"
                       min="0.01" step="0.01" onchange="calculateDenominationTotal()">
            </div>
            
            <div class="form-group" id="expense_head_group">
                <label class="form-label" for="expense_head_id">Expense Head *</label>
                <select id="expense_head_id" name="expense_head_id" class="form-control">
                    <option value="">Select Expense Head</option>
                    <?php foreach ($expenseHeads as $eh): ?>
                    <option value="<?php echo $eh['expense_head_id']; ?>" 
                            <?php echo ($formData['expense_head_id'] ?? 0) == $eh['expense_head_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($eh['expense_head_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="description">Description</label>
                <textarea id="description" name="description" class="form-control" rows="2"
                          placeholder="Enter transaction description..."><?php echo htmlspecialchars($formData['description'] ?? ''); ?></textarea>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="voucher_number">Voucher Number</label>
                <input type="text" id="voucher_number" name="voucher_number" class="form-control"
                       value="<?php echo htmlspecialchars($formData['voucher_number'] ?? ''); ?>"
                       placeholder="Enter voucher number">
            </div>
        </div>
        
        <!-- Denomination Breakdown (for Cash In) -->
        <div id="denomination_section" style="margin-top: 30px; padding: 20px; background: #f9fafb; border-radius: 8px;">
            <h3 style="margin-bottom: 15px;">Denomination Breakdown (Cash In Only)</h3>
            <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 15px;">
                <div class="form-group">
                    <label class="form-label" for="denomination_500">₹500</label>
                    <input type="number" id="denomination_500" name="denomination_500" class="form-control"
                           value="<?php echo htmlspecialchars($formData['denomination_500'] ?? 0); ?>" min="0"
                           onchange="calculateDenominationTotal()">
                </div>
                <div class="form-group">
                    <label class="form-label" for="denomination_200">₹200</label>
                    <input type="number" id="denomination_200" name="denomination_200" class="form-control"
                           value="<?php echo htmlspecialchars($formData['denomination_200'] ?? 0); ?>" min="0"
                           onchange="calculateDenominationTotal()">
                </div>
                <div class="form-group">
                    <label class="form-label" for="denomination_100">₹100</label>
                    <input type="number" id="denomination_100" name="denomination_100" class="form-control"
                           value="<?php echo htmlspecialchars($formData['denomination_100'] ?? 0); ?>" min="0"
                           onchange="calculateDenominationTotal()">
                </div>
                <div class="form-group">
                    <label class="form-label" for="denomination_50">₹50</label>
                    <input type="number" id="denomination_50" name="denomination_50" class="form-control"
                           value="<?php echo htmlspecialchars($formData['denomination_50'] ?? 0); ?>" min="0"
                           onchange="calculateDenominationTotal()">
                </div>
                <div class="form-group">
                    <label class="form-label" for="denomination_20">₹20</label>
                    <input type="number" id="denomination_20" name="denomination_20" class="form-control"
                           value="<?php echo htmlspecialchars($formData['denomination_20'] ?? 0); ?>" min="0"
                           onchange="calculateDenominationTotal()">
                </div>
                <div class="form-group">
                    <label class="form-label" for="denomination_10">₹10</label>
                    <input type="number" id="denomination_10" name="denomination_10" class="form-control"
                           value="<?php echo htmlspecialchars($formData['denomination_10'] ?? 0); ?>" min="0"
                           onchange="calculateDenominationTotal()">
                </div>
                <div class="form-group">
                    <label class="form-label" for="denomination_5">₹5</label>
                    <input type="number" id="denomination_5" name="denomination_5" class="form-control"
                           value="<?php echo htmlspecialchars($formData['denomination_5'] ?? 0); ?>" min="0"
                           onchange="calculateDenominationTotal()">
                </div>
                <div class="form-group">
                    <label class="form-label" for="denomination_2">₹2</label>
                    <input type="number" id="denomination_2" name="denomination_2" class="form-control"
                           value="<?php echo htmlspecialchars($formData['denomination_2'] ?? 0); ?>" min="0"
                           onchange="calculateDenominationTotal()">
                </div>
                <div class="form-group">
                    <label class="form-label" for="denomination_1">₹1</label>
                    <input type="number" id="denomination_1" name="denomination_1" class="form-control"
                           value="<?php echo htmlspecialchars($formData['denomination_1'] ?? 0); ?>" min="0"
                           onchange="calculateDenominationTotal()">
                </div>
                <div class="form-group" style="display: flex; align-items: flex-end;">
                    <div>
                        <label class="form-label">Total</label>
                        <div id="denomination_total" style="padding: 10px; background: white; border: 1px solid var(--border-color); border-radius: 6px; font-weight: 600; font-size: 18px;">
                            ₹0.00
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <a href="<?php echo BASE_URL; ?>/modules/petty_cash/list.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create Transaction</button>
        </div>
    </form>
</div>

<script>
function toggleExpenseHead() {
    const type = document.getElementById('transaction_type').value;
    const expenseHeadGroup = document.getElementById('expense_head_group');
    const expenseHeadSelect = document.getElementById('expense_head_id');
    const denominationSection = document.getElementById('denomination_section');
    
    if (type === 'cash_in') {
        expenseHeadSelect.removeAttribute('required');
        denominationSection.style.display = 'block';
    } else {
        expenseHeadSelect.setAttribute('required', 'required');
        denominationSection.style.display = 'none';
    }
}

function calculateDenominationTotal() {
    const denominations = [500, 200, 100, 50, 20, 10, 5, 2, 1];
    let total = 0;
    
    denominations.forEach(denom => {
        const count = parseInt(document.getElementById('denomination_' + denom).value) || 0;
        total += count * denom;
    });
    
    document.getElementById('denomination_total').textContent = '₹' + total.toFixed(2);
}

// Initialize
toggleExpenseHead();
calculateDenominationTotal();
</script>

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

