<?php
/**
 * Enterprise HRM ERP System - Create Permission
 */

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

if (!canCreateCustomRoles()) {
    $_SESSION['error'] = 'Only Super Admin can create permissions.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'Add Permission';
$currentModule = 'settings';

$errors = [];
$formData = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'permission_code' => sanitize($_POST['permission_code'] ?? ''),
        'permission_name' => sanitize($_POST['permission_name'] ?? ''),
        'permission_module' => sanitize($_POST['permission_module'] ?? ''),
        'permission_description' => sanitize($_POST['permission_description'] ?? ''),
    ];
    
    // Validation
    if (empty($formData['permission_code'])) {
        $errors[] = 'Permission code is required.';
    } elseif (!preg_match('/^[A-Z0-9_]+$/', $formData['permission_code'])) {
        $errors[] = 'Permission code can only contain uppercase letters, numbers, and underscores.';
    }
    
    if (empty($formData['permission_name'])) {
        $errors[] = 'Permission name is required.';
    }
    
    if (empty($formData['permission_module'])) {
        $errors[] = 'Permission module is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            
            // Check if code already exists
            $stmt = $db->prepare("SELECT permission_id FROM permissions WHERE permission_code = ?");
            $stmt->execute([$formData['permission_code']]);
            if ($stmt->fetch()) {
                $errors[] = 'Permission code already exists.';
            } else {
                $stmt = $db->prepare("
                    INSERT INTO permissions (permission_code, permission_name, permission_module, permission_description)
                    VALUES (?, ?, ?, ?)
                ");
                $stmt->execute([
                    $formData['permission_code'],
                    $formData['permission_name'],
                    $formData['permission_module'],
                    $formData['permission_description'] ?: null
                ]);
                
                logAudit('CREATE', 'permissions', $db->lastInsertId());
                
                redirect(BASE_URL . '/admin/permissions.php', 'Permission created successfully.');
            }
            
        } catch (Exception $e) {
            error_log("Error creating permission: " . $e->getMessage());
            $errors[] = 'An error occurred while creating permission. Please try again.';
        }
    }
}

// Get existing modules for dropdown
$modules = ['EMPLOYEE', 'ATTENDANCE', 'LEAVE', 'PAYROLL', 'OVERTIME', 'PETTY_CASH', 'DFC', 'MIS', 'TRANSFER', 'EXIT', 'REPORTS', 'SETTINGS', 'USERS', 'ROLES'];

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Add Permission</h2>
        <a href="<?php echo BASE_URL; ?>/admin/permissions.php" class="btn btn-secondary">Back to Permissions</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="permission_code">Permission Code *</label>
                <input type="text" id="permission_code" name="permission_code" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['permission_code'] ?? ''); ?>"
                       placeholder="e.g., EMPLOYEE_CREATE"
                       pattern="[A-Z0-9_]+" title="Only uppercase letters, numbers, and underscores">
                <small style="color: var(--text-secondary);">Uppercase letters, numbers, and underscores only</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="permission_name">Permission Name *</label>
                <input type="text" id="permission_name" name="permission_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['permission_name'] ?? ''); ?>"
                       placeholder="e.g., Create Employee">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="permission_module">Module *</label>
                <select id="permission_module" name="permission_module" class="form-control" required>
                    <option value="">Select Module</option>
                    <?php foreach ($modules as $module): ?>
                    <option value="<?php echo $module; ?>" 
                            <?php echo ($formData['permission_module'] ?? '') === $module ? 'selected' : ''; ?>>
                        <?php echo $module; ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="permission_description">Description</label>
                <textarea id="permission_description" name="permission_description" class="form-control" rows="2"
                          placeholder="Enter permission description..."><?php echo htmlspecialchars($formData['permission_description'] ?? ''); ?></textarea>
            </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/permissions.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Create Permission</button>
        </div>
    </form>
</div>

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

