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

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

$pageTitle = 'Edit Petty Cash Transaction';
$currentModule = 'petty_cash';

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

if ($transactionId <= 0) {
    redirect(BASE_URL . '/modules/petty_cash/list.php', 'Invalid transaction ID.', 'error');
}

// Get transaction
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM petty_cash_transactions WHERE transaction_id = ? AND site_id = ?");
    $stmt->execute([$transactionId, $siteId]);
    $transaction = $stmt->fetch();
    
    if (!$transaction) {
        redirect(BASE_URL . '/modules/petty_cash/list.php', 'Transaction not found.', 'error');
    }
    
    $formData = $transaction;
    
    // Check if locked
    $isLocked = isDataLocked('petty_cash', $siteId, $transaction['month'], $transaction['year']);
    if ($isLocked && !hasAdminAccess()) {
        requireUnlocked('petty_cash', $siteId, $transaction['month'], $transaction['year']);
    }
    
} catch (Exception $e) {
    error_log("Error loading transaction: " . $e->getMessage());
    redirect(BASE_URL . '/modules/petty_cash/list.php', 'Error loading transaction data.', 'error');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        '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'] ?? ''),
    ];
    
    // Validation
    if ($formData['amount'] <= 0) {
        $errors[] = 'Amount must be greater than 0.';
    }
    
    if ($transaction['transaction_type'] === 'cash_out' && empty($formData['expense_head_id'])) {
        $errors[] = 'Expense head is required for cash out transactions.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                UPDATE petty_cash_transactions SET
                    amount = ?,
                    expense_head_id = ?,
                    description = ?,
                    voucher_number = ?,
                    updated_by = ?,
                    updated_at = NOW()
                WHERE transaction_id = ? AND site_id = ?
            ");
            $stmt->execute([
                $formData['amount'],
                $formData['expense_head_id'],
                $formData['description'],
                $formData['voucher_number'],
                getCurrentUserId(),
                $transactionId,
                $siteId
            ]);
            
            logAudit('UPDATE', 'petty_cash_transactions', $transactionId);
            
            redirect(BASE_URL . '/modules/petty_cash/list.php?month=' . $transaction['month'] . '&year=' . $transaction['year'], 'Transaction updated successfully.');
            
        } catch (Exception $e) {
            error_log("Error updating transaction: " . $e->getMessage());
            $errors[] = 'An error occurred while updating 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) {
    $expenseHeads = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit Petty Cash Transaction</h2>
        <a href="<?php echo BASE_URL; ?>/modules/petty_cash/list.php?month=<?php echo $transaction['month']; ?>&year=<?php echo $transaction['year']; ?>" 
           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" style="margin-top: 20px;">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label">Date</label>
                <input type="text" class="form-control" value="<?php echo formatDate($transaction['transaction_date']); ?>" disabled>
            </div>
            
            <div class="form-group">
                <label class="form-label">Type</label>
                <input type="text" class="form-control" value="<?php echo ucfirst(str_replace('_', ' ', $transaction['transaction_type'])); ?>" disabled>
            </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'] ?? $transaction['amount']); ?>"
                       min="0.01" step="0.01">
            </div>
            
            <?php if ($transaction['transaction_type'] === 'cash_out'): ?>
            <div class="form-group">
                <label class="form-label" for="expense_head_id">Expense Head *</label>
                <select id="expense_head_id" name="expense_head_id" class="form-control" required>
                    <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'] ?? $transaction['expense_head_id']) == $eh['expense_head_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($eh['expense_head_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            
            <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"><?php echo htmlspecialchars($formData['description'] ?? $transaction['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'] ?? $transaction['voucher_number']); ?>">
            </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 $transaction['month']; ?>&year=<?php echo $transaction['year']; ?>" 
               class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Transaction</button>
        </div>
    </form>
</div>

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

