<?php
/**
 * Enterprise HRM ERP System - Create Salary Component
 */

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

$pageTitle = 'Create Salary Component';
$currentModule = 'settings';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'component_code' => sanitize($_POST['component_code'] ?? ''),
        'component_name' => sanitize($_POST['component_name'] ?? ''),
        'component_type' => sanitize($_POST['component_type'] ?? 'earning'),
        'is_taxable' => isset($_POST['is_taxable']) ? 1 : 0,
        'calculation_type' => sanitize($_POST['calculation_type'] ?? 'fixed'),
        'calculation_value' => isset($_POST['calculation_value']) ? (float)$_POST['calculation_value'] : 0.00,
        'component_status' => sanitize($_POST['component_status'] ?? 'active'),
    ];
    
    // Validation
    if (empty($formData['component_code'])) {
        $errors[] = 'Component code is required.';
    } elseif (strlen($formData['component_code']) < 2) {
        $errors[] = 'Component code must be at least 2 characters.';
    }
    
    if (empty($formData['component_name'])) {
        $errors[] = 'Component name is required.';
    }
    
    if (!in_array($formData['component_type'], ['earning', 'deduction'])) {
        $errors[] = 'Invalid component type.';
    }
    
    if (!in_array($formData['calculation_type'], ['fixed', 'percentage', 'formula'])) {
        $errors[] = 'Invalid calculation type.';
    }
    
    if ($formData['calculation_type'] !== 'formula' && $formData['calculation_value'] < 0) {
        $errors[] = 'Calculation value must be 0 or greater.';
    }
    
    if ($formData['calculation_type'] === 'percentage' && $formData['calculation_value'] > 100) {
        $errors[] = 'Percentage cannot exceed 100%.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if component code already exists for this site
            $stmt = $db->prepare("SELECT component_id FROM salary_components WHERE site_id = ? AND component_code = ?");
            $stmt->execute([$siteId, $formData['component_code']]);
            if ($stmt->fetch()) {
                $errors[] = 'Component code already exists for this site.';
                $db->rollBack();
            } else {
                // Insert salary component
                $stmt = $db->prepare("
                    INSERT INTO salary_components (
                        site_id, component_code, component_name, 
                        component_type, is_taxable, calculation_type,
                        calculation_value, component_status
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $siteId,
                    $formData['component_code'],
                    $formData['component_name'],
                    $formData['component_type'],
                    $formData['is_taxable'],
                    $formData['calculation_type'],
                    $formData['calculation_value'],
                    $formData['component_status']
                ]);
                
                $componentId = $db->lastInsertId();
                $db->commit();
                
                // Log audit
                logAudit('CREATE', 'salary_components', $componentId);
                
                redirect(BASE_URL . '/admin/salary_components.php', 'Salary component created successfully.');
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error creating salary component: " . $e->getMessage());
            $errors[] = 'An error occurred while creating salary component. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Create Salary Component</h2>
        <a href="<?php echo BASE_URL; ?>/admin/salary_components.php" class="btn btn-secondary">Back to Salary Components</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="componentForm" 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="component_code">Component Code *</label>
                <input type="text" id="component_code" name="component_code" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['component_code'] ?? ''); ?>"
                       placeholder="e.g., BASIC, HRA, PF" maxlength="50">
                <small style="color: var(--text-secondary);">Unique code for this component</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="component_name">Component Name *</label>
                <input type="text" id="component_name" name="component_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['component_name'] ?? ''); ?>"
                       placeholder="e.g., Basic Salary, House Rent Allowance" maxlength="255">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="component_type">Component Type *</label>
                <select id="component_type" name="component_type" class="form-control" required>
                    <option value="earning" <?php echo ($formData['component_type'] ?? 'earning') === 'earning' ? 'selected' : ''; ?>>💰 Earning</option>
                    <option value="deduction" <?php echo ($formData['component_type'] ?? '') === 'deduction' ? 'selected' : ''; ?>>➖ Deduction</option>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="calculation_type">Calculation Type *</label>
                <select id="calculation_type" name="calculation_type" class="form-control" required>
                    <option value="fixed" <?php echo ($formData['calculation_type'] ?? 'fixed') === 'fixed' ? 'selected' : ''; ?>>Fixed Amount</option>
                    <option value="percentage" <?php echo ($formData['calculation_type'] ?? '') === 'percentage' ? 'selected' : ''; ?>>Percentage</option>
                    <option value="formula" <?php echo ($formData['calculation_type'] ?? '') === 'formula' ? 'selected' : ''; ?>>Formula</option>
                </select>
            </div>
            
            <div class="form-group" id="calculation_value_group">
                <label class="form-label" for="calculation_value" id="calculation_value_label">Calculation Value *</label>
                <input type="number" id="calculation_value" name="calculation_value" class="form-control"
                       value="<?php echo htmlspecialchars($formData['calculation_value'] ?? 0); ?>"
                       min="0" step="0.01" required>
                <small style="color: var(--text-secondary);" id="calculation_value_help">Enter the fixed amount or percentage value</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="component_status">Status *</label>
                <select id="component_status" name="component_status" class="form-control" required>
                    <option value="active" <?php echo ($formData['component_status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo ($formData['component_status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                </select>
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
                    <input type="checkbox" id="is_taxable" name="is_taxable" value="1"
                           <?php echo ($formData['is_taxable'] ?? 0) ? 'checked' : ''; ?>>
                    <span>Is Taxable</span>
                </label>
                <small style="color: var(--text-secondary);">This component is subject to tax calculation</small>
            </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/salary_components.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create Component</button>
        </div>
    </form>
</div>

<script>
document.getElementById('calculation_type').addEventListener('change', function() {
    const calculationValueGroup = document.getElementById('calculation_value_group');
    const calculationValue = document.getElementById('calculation_value');
    const calculationValueLabel = document.getElementById('calculation_value_label');
    const calculationValueHelp = document.getElementById('calculation_value_help');
    
    if (this.value === 'formula') {
        calculationValueGroup.style.display = 'none';
        calculationValue.removeAttribute('required');
        calculationValue.value = 0;
    } else {
        calculationValueGroup.style.display = 'block';
        calculationValue.setAttribute('required', 'required');
        
        if (this.value === 'fixed') {
            calculationValueLabel.textContent = 'Fixed Amount *';
            calculationValueHelp.textContent = 'Enter the fixed amount';
            calculationValue.setAttribute('max', '999999999');
        } else if (this.value === 'percentage') {
            calculationValueLabel.textContent = 'Percentage (%) *';
            calculationValueHelp.textContent = 'Enter percentage (0-100)';
            calculationValue.setAttribute('max', '100');
        }
    }
});

// Initialize on page load
document.getElementById('calculation_type').dispatchEvent(new Event('change'));
</script>

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

