<?php
/**
 * Enterprise HRM ERP System - Edit Expense Head
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

$pageTitle = 'Edit Expense Head';
$currentModule = 'settings';

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

if ($expenseHeadId <= 0) {
    redirect(BASE_URL . '/admin/expense_heads.php', 'Invalid expense head ID.', 'error');
}

// Get expense head
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM expense_heads WHERE expense_head_id = ? AND site_id = ?");
    $stmt->execute([$expenseHeadId, $siteId]);
    $expenseHead = $stmt->fetch();
    
    if (!$expenseHead) {
        redirect(BASE_URL . '/admin/expense_heads.php', 'Expense head not found.', 'error');
    }
    
    $formData = $expenseHead;
    
} catch (Exception $e) {
    error_log("Error loading expense head: " . $e->getMessage());
    redirect(BASE_URL . '/admin/expense_heads.php', 'Error loading expense head data.', 'error');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'expense_head_name' => sanitize($_POST['expense_head_name'] ?? ''),
        'expense_category' => sanitize($_POST['expense_category'] ?? ''),
        'is_active' => isset($_POST['is_active']) ? 1 : 0,
    ];
    
    // Validation
    if (empty($formData['expense_head_name'])) {
        $errors[] = 'Expense head name is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                UPDATE expense_heads SET
                    expense_head_name = ?,
                    expense_category = ?,
                    is_active = ?,
                    updated_at = NOW()
                WHERE expense_head_id = ? AND site_id = ?
            ");
            $stmt->execute([
                $formData['expense_head_name'],
                $formData['expense_category'] ?: null,
                $formData['is_active'],
                $expenseHeadId,
                $siteId
            ]);
            
            logAudit('UPDATE', 'expense_heads', $expenseHeadId);
            
            redirect(BASE_URL . '/admin/expense_heads.php', 'Expense head updated successfully.');
            
        } catch (Exception $e) {
            error_log("Error updating expense head: " . $e->getMessage());
            $errors[] = 'An error occurred while updating expense head. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit Expense Head</h2>
        <a href="<?php echo BASE_URL; ?>/admin/expense_heads.php" class="btn btn-secondary">Back to Expense Heads</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">Expense Code</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($expenseHead['expense_head_code']); ?>" disabled>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="expense_head_name">Expense Name *</label>
                <input type="text" id="expense_head_name" name="expense_head_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['expense_head_name'] ?? $expenseHead['expense_head_name']); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="expense_category">Category</label>
                <input type="text" id="expense_category" name="expense_category" class="form-control"
                       value="<?php echo htmlspecialchars($formData['expense_category'] ?? $expenseHead['expense_category'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
                    <input type="checkbox" id="is_active" name="is_active" value="1" 
                           <?php echo ($formData['is_active'] ?? $expenseHead['is_active']) ? 'checked' : ''; ?>>
                    <span>Active</span>
                </label>
            </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; ?>/admin/expense_heads.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Expense Head</button>
        </div>
    </form>
</div>

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

