<?php
/**
 * Enterprise HRM ERP System - Edit Leave Type
 */

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

$pageTitle = 'Edit Leave Type';
$currentModule = 'settings';

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

if ($leaveTypeId <= 0) {
    redirect(BASE_URL . '/admin/leave_types.php', 'Invalid leave type ID.', 'error');
}

// Get leave type details
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM leave_types WHERE leave_type_id = ? AND site_id = ?");
    $stmt->execute([$leaveTypeId, $siteId]);
    $leaveType = $stmt->fetch();
    
    if (!$leaveType) {
        redirect(BASE_URL . '/admin/leave_types.php', 'Leave type not found.', 'error');
    }
    
    $formData = $leaveType;
    
} catch (Exception $e) {
    error_log("Error loading leave type: " . $e->getMessage());
    redirect(BASE_URL . '/admin/leave_types.php', 'Error loading leave type data.', 'error');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'leave_type_code' => sanitize($_POST['leave_type_code'] ?? ''),
        'leave_type_name' => sanitize($_POST['leave_type_name'] ?? ''),
        'max_days_per_year' => isset($_POST['max_days_per_year']) ? (int)$_POST['max_days_per_year'] : 0,
        'carry_forward' => isset($_POST['carry_forward']) ? 1 : 0,
        'max_carry_forward_days' => isset($_POST['max_carry_forward_days']) ? (int)$_POST['max_carry_forward_days'] : 0,
        'requires_approval' => isset($_POST['requires_approval']) ? 1 : 0,
        'leave_type_status' => sanitize($_POST['leave_type_status'] ?? 'active'),
    ];
    
    // Validation
    if (empty($formData['leave_type_code'])) {
        $errors[] = 'Leave type code is required.';
    } elseif (strlen($formData['leave_type_code']) < 2) {
        $errors[] = 'Leave type code must be at least 2 characters.';
    }
    
    if (empty($formData['leave_type_name'])) {
        $errors[] = 'Leave type name is required.';
    }
    
    if ($formData['max_days_per_year'] < 0) {
        $errors[] = 'Max days per year must be 0 or greater.';
    }
    
    if ($formData['carry_forward'] && $formData['max_carry_forward_days'] < 0) {
        $errors[] = 'Max carry forward days must be 0 or greater.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if leave type code already exists for this site (excluding current leave type)
            $stmt = $db->prepare("SELECT leave_type_id FROM leave_types WHERE site_id = ? AND leave_type_code = ? AND leave_type_id != ?");
            $stmt->execute([$siteId, $formData['leave_type_code'], $leaveTypeId]);
            if ($stmt->fetch()) {
                $errors[] = 'Leave type code already exists for this site.';
                $db->rollBack();
            } else {
                // Update leave type
                $stmt = $db->prepare("
                    UPDATE leave_types SET
                        leave_type_code = ?,
                        leave_type_name = ?,
                        max_days_per_year = ?,
                        carry_forward = ?,
                        max_carry_forward_days = ?,
                        requires_approval = ?,
                        leave_type_status = ?,
                        updated_at = NOW()
                    WHERE leave_type_id = ? AND site_id = ?
                ");
                $stmt->execute([
                    $formData['leave_type_code'],
                    $formData['leave_type_name'],
                    $formData['max_days_per_year'],
                    $formData['carry_forward'],
                    $formData['max_carry_forward_days'],
                    $formData['requires_approval'],
                    $formData['leave_type_status'],
                    $leaveTypeId,
                    $siteId
                ]);
                
                $db->commit();
                
                // Log audit
                logAudit('UPDATE', 'leave_types', $leaveTypeId);
                
                redirect(BASE_URL . '/admin/leave_types.php', 'Leave type updated successfully.');
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error updating leave type: " . $e->getMessage());
            $errors[] = 'An error occurred while updating leave type. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit Leave Type</h2>
        <a href="<?php echo BASE_URL; ?>/admin/leave_types.php" class="btn btn-secondary">Back to Leave Types</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="leaveTypeForm" 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="leave_type_code">Leave Type Code *</label>
                <input type="text" id="leave_type_code" name="leave_type_code" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['leave_type_code'] ?? ''); ?>"
                       placeholder="e.g., AL, SL, CL" maxlength="50">
                <small style="color: var(--text-secondary);">Unique code for this leave type</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="leave_type_name">Leave Type Name *</label>
                <input type="text" id="leave_type_name" name="leave_type_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['leave_type_name'] ?? ''); ?>"
                       placeholder="e.g., Annual Leave, Sick Leave" maxlength="255">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="max_days_per_year">Max Days Per Year</label>
                <input type="number" id="max_days_per_year" name="max_days_per_year" class="form-control"
                       value="<?php echo htmlspecialchars($formData['max_days_per_year'] ?? 0); ?>"
                       min="0" max="365">
                <small style="color: var(--text-secondary);">0 = Unlimited</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="leave_type_status">Status *</label>
                <select id="leave_type_status" name="leave_type_status" class="form-control" required>
                    <option value="active" <?php echo ($formData['leave_type_status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo ($formData['leave_type_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="carry_forward" name="carry_forward" value="1"
                           <?php echo ($formData['carry_forward'] ?? 0) ? 'checked' : ''; ?>>
                    <span>Allow Carry Forward</span>
                </label>
                <small style="color: var(--text-secondary);">Allow employees to carry forward unused leave to next year</small>
            </div>
            
            <div class="form-group" id="max_carry_forward_group" style="display: <?php echo ($formData['carry_forward'] ?? 0) ? 'block' : 'none'; ?>;">
                <label class="form-label" for="max_carry_forward_days">Max Carry Forward Days</label>
                <input type="number" id="max_carry_forward_days" name="max_carry_forward_days" class="form-control"
                       value="<?php echo htmlspecialchars($formData['max_carry_forward_days'] ?? 0); ?>"
                       min="0" max="365">
                <small style="color: var(--text-secondary);">Maximum days that can be carried forward</small>
            </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="requires_approval" name="requires_approval" value="1"
                           <?php echo ($formData['requires_approval'] ?? 1) ? 'checked' : ''; ?>>
                    <span>Requires Approval</span>
                </label>
                <small style="color: var(--text-secondary);">Leave applications of this type require manager approval</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/leave_types.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Leave Type</button>
        </div>
    </form>
</div>

<script>
document.getElementById('carry_forward').addEventListener('change', function() {
    const maxCarryForwardGroup = document.getElementById('max_carry_forward_group');
    if (this.checked) {
        maxCarryForwardGroup.style.display = 'block';
    } else {
        maxCarryForwardGroup.style.display = 'none';
        document.getElementById('max_carry_forward_days').value = 0;
    }
});
</script>

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

