<?php
/**
 * Enterprise HRM ERP System - Permission Setup
 * Manage all permissions in the system
 */

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

// Check if user is Super Admin - with better error handling
startSession();

// Force refresh role_code from database
$roleCode = $_SESSION['role_code'] ?? '';
if (empty($roleCode) && isset($_SESSION['user_id'])) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT r.role_code 
            FROM users u
            INNER JOIN roles r ON u.role_id = r.role_id
            WHERE u.user_id = ?
        ");
        $stmt->execute([$_SESSION['user_id']]);
        $userRole = $stmt->fetch();
        if ($userRole && !empty($userRole['role_code'])) {
            $roleCode = $userRole['role_code'];
            $_SESSION['role_code'] = $roleCode;
        }
    } catch (Exception $e) {
        error_log("Error loading role_code: " . $e->getMessage());
    }
}

// Check if Super Admin (case-insensitive)
if (strtolower($roleCode) !== 'super_admin') {
    $_SESSION['error'] = 'Only Super Admin can manage permissions. Your role: ' . ($roleCode ?: 'Unknown');
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

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

$errors = [];
$success = false;

// Handle permission creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_permission'])) {
    $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.';
    }
    
    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());
                $success = true;
            }
        } catch (Exception $e) {
            error_log("Error creating permission: " . $e->getMessage());
            $errors[] = 'An error occurred while creating permission.';
        }
    }
}

// Get all permissions grouped by module
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT 
            permission_id,
            permission_code,
            permission_name,
            permission_module,
            permission_description,
            (SELECT COUNT(*) FROM role_permissions WHERE permission_id = p.permission_id) as role_count
        FROM permissions p
        ORDER BY permission_module, permission_name
    ");
    $stmt->execute();
    $permissions = $stmt->fetchAll();
    
    // Group by module
    $permissionsByModule = [];
    foreach ($permissions as $perm) {
        $module = $perm['permission_module'];
        if (!isset($permissionsByModule[$module])) {
            $permissionsByModule[$module] = [];
        }
        $permissionsByModule[$module][] = $perm;
    }
    
    // Get unique modules
    $modules = array_unique(array_column($permissions, 'permission_module'));
    
} catch (Exception $e) {
    error_log("Error loading permissions: " . $e->getMessage());
    $permissions = [];
    $permissionsByModule = [];
    $modules = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Permission Setup</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?php echo BASE_URL; ?>/modules/settings/index.php" class="btn btn-secondary">Back to Settings</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles.php" class="btn btn-secondary">Role Management</a>
            <a href="<?php echo BASE_URL; ?>/admin/branch_permissions.php" class="btn btn-secondary">Branch Permissions</a>
            <button onclick="document.getElementById('createPermissionForm').style.display='block'" class="btn btn-primary">Add Permission</button>
        </div>
    </div>
    
    <?php if ($success): ?>
    <div class="alert alert-success" style="margin-top: 20px;">
        Permission created successfully.
    </div>
    <?php endif; ?>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-top: 20px;">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <!-- Create Permission Form (Hidden by default) -->
    <div id="createPermissionForm" style="display: none; margin-top: 20px; padding: 20px; background: #f9fafb; border-radius: 8px;">
        <h3 style="margin-bottom: 15px;">Create New Permission</h3>
        <form method="POST">
            <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
                           placeholder="e.g., EMPLOYEE_CREATE" pattern="[A-Z_]+">
                    <small style="color: var(--text-secondary);">Uppercase letters 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
                           placeholder="e.g., Create Employee">
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="permission_module">Module *</label>
                    <input type="text" id="permission_module" name="permission_module" class="form-control" required
                           placeholder="e.g., Employee, Attendance, Payroll">
                </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..."></textarea>
                </div>
            </div>
            
            <div style="margin-top: 20px; text-align: right;">
                <button type="button" onclick="document.getElementById('createPermissionForm').style.display='none'" class="btn btn-secondary">Cancel</button>
                <button type="submit" name="create_permission" class="btn btn-primary">Create Permission</button>
            </div>
        </form>
    </div>
    
    <!-- Permissions List -->
    <div style="margin-top: 30px;">
        <?php if (empty($permissionsByModule)): ?>
        <div class="table-empty">
            <div class="table-empty-icon">🔐</div>
            <div class="table-empty-message">No permissions found</div>
            <div class="table-empty-submessage">
                <button onclick="document.getElementById('createPermissionForm').style.display='block'" class="btn btn-primary">Create First Permission</button>
            </div>
        </div>
        <?php else: ?>
        <?php foreach ($permissionsByModule as $module => $modulePermissions): ?>
        <div style="margin-bottom: 30px;">
            <h3 style="margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid var(--primary-color);">
                <?php echo htmlspecialchars($module); ?> Module
                <span style="font-size: 14px; color: var(--text-secondary); font-weight: normal;">
                    (<?php echo count($modulePermissions); ?> permissions)
                </span>
            </h3>
            
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Permission Code</th>
                        <th>Permission Name</th>
                        <th>Description</th>
                        <th>Assigned to Roles</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($modulePermissions as $perm): ?>
                    <tr>
                        <td><strong><?php echo htmlspecialchars($perm['permission_code']); ?></strong></td>
                        <td><?php echo htmlspecialchars($perm['permission_name']); ?></td>
                        <td><?php echo htmlspecialchars($perm['permission_description'] ?? 'N/A'); ?></td>
                        <td><?php echo number_format($perm['role_count']); ?> role(s)</td>
                        <td class="table-actions-cell">
                            <a href="<?php echo BASE_URL; ?>/admin/permissions_edit.php?id=<?php echo $perm['permission_id']; ?>" 
                               class="btn btn-sm btn-primary">Edit</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

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