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

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

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

$siteId = getCurrentSiteId();
$errors = [];
$formData = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'expense_head_code' => sanitize($_POST['expense_head_code'] ?? ''),
        'expense_head_name' => sanitize($_POST['expense_head_name'] ?? ''),
        'expense_category' => sanitize($_POST['expense_category'] ?? ''),
    ];
    
    // Validation
    if (empty($formData['expense_head_code'])) {
        $errors[] = 'Expense head code is required.';
    }
    
    if (empty($formData['expense_head_name'])) {
        $errors[] = 'Expense head name is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            
            // Check if code already exists
            $stmt = $db->prepare("SELECT expense_head_id FROM expense_heads WHERE site_id = ? AND expense_head_code = ?");
            $stmt->execute([$siteId, $formData['expense_head_code']]);
            if ($stmt->fetch()) {
                $errors[] = 'Expense head code already exists.';
            } else {
                $stmt = $db->prepare("
                    INSERT INTO expense_heads (
                        site_id, expense_head_code, expense_head_name, expense_category
                    ) VALUES (?, ?, ?, ?)
                ");
                $stmt->execute([
                    $siteId,
                    $formData['expense_head_code'],
                    $formData['expense_head_name'],
                    $formData['expense_category'] ?: null
                ]);
                
                logAudit('CREATE', 'expense_heads', $db->lastInsertId());
                
                redirect(BASE_URL . '/admin/expense_heads.php', 'Expense head created successfully.');
            }
            
        } catch (Exception $e) {
            error_log("Error creating expense head: " . $e->getMessage());
            $errors[] = 'An error occurred while creating expense head. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Add 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" for="expense_head_code">Expense Code *</label>
                <input type="text" id="expense_head_code" name="expense_head_code" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['expense_head_code'] ?? ''); ?>"
                       placeholder="e.g., TRAVEL, STATIONERY">
            </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'] ?? ''); ?>"
                       placeholder="e.g., Travel Expenses">
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <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'] ?? ''); ?>"
                       placeholder="e.g., operational, administrative">
            </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">Create Expense Head</button>
        </div>
    </form>
</div>

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

