<?php
/**
 * Enterprise HRM ERP System - Branch-wise Permission Management
 * Set permissions for roles in specific branches
 */

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

// Check if user is Super Admin
startSession();
$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());
    }
}

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

$pageTitle = 'Branch-wise Permission Management';
$currentModule = 'settings';

$errors = [];
$success = false;

// Get selected branch and role
$selectedSiteId = isset($_GET['site_id']) ? (int)$_GET['site_id'] : 0;
$selectedRoleId = isset($_GET['role_id']) ? (int)$_GET['role_id'] : 0;

// Handle permission assignment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_permissions'])) {
    $siteId = isset($_POST['site_id']) ? (int)$_POST['site_id'] : 0;
    $roleId = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
    $permissions = $_POST['permissions'] ?? [];
    
    if ($siteId <= 0 || $roleId <= 0) {
        $errors[] = 'Please select both branch and role.';
    } else {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if table exists, if not create it
            $stmt = $db->query("SHOW TABLES LIKE 'site_role_permissions'");
            if ($stmt->rowCount() == 0) {
                // Create table
                $db->exec("
                    CREATE TABLE IF NOT EXISTS `site_role_permissions` (
                      `site_role_permission_id` int(11) NOT NULL AUTO_INCREMENT,
                      `site_id` int(11) NOT NULL,
                      `role_id` int(11) NOT NULL,
                      `permission_id` int(11) NOT NULL,
                      `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
                      `created_by` int(11),
                      PRIMARY KEY (`site_role_permission_id`),
                      UNIQUE KEY `unique_site_role_permission` (`site_id`,`role_id`,`permission_id`),
                      KEY `fk_site_role_permission_site` (`site_id`),
                      KEY `fk_site_role_permission_role` (`role_id`),
                      KEY `fk_site_role_permission_permission` (`permission_id`),
                      CONSTRAINT `fk_site_role_permission_site` FOREIGN KEY (`site_id`) REFERENCES `sites` (`site_id`) ON DELETE CASCADE,
                      CONSTRAINT `fk_site_role_permission_role` FOREIGN KEY (`role_id`) REFERENCES `roles` (`role_id`) ON DELETE CASCADE,
                      CONSTRAINT `fk_site_role_permission_permission` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`permission_id`) ON DELETE CASCADE
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
                ");
            }
            
            // Delete existing branch-specific permissions for this role
            $stmt = $db->prepare("DELETE FROM site_role_permissions WHERE site_id = ? AND role_id = ?");
            $stmt->execute([$siteId, $roleId]);
            
            // Insert new permissions
            if (!empty($permissions)) {
                $stmt = $db->prepare("
                    INSERT INTO site_role_permissions (site_id, role_id, permission_id, created_by)
                    VALUES (?, ?, ?, ?)
                ");
                foreach ($permissions as $permissionId) {
                    $stmt->execute([$siteId, $roleId, (int)$permissionId, getCurrentUserId()]);
                }
            }
            
            $db->commit();
            
            logAudit('UPDATE', 'site_role_permissions', $siteId, ['action' => 'branch_permissions_updated', 'role_id' => $roleId]);
            $success = true;
            
            // Update selected values
            $selectedSiteId = $siteId;
            $selectedRoleId = $roleId;
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error saving branch permissions: " . $e->getMessage());
            $errors[] = 'An error occurred while saving permissions.';
        }
    }
}

// Get all branches and roles
try {
    $db = getDB();
    
    // Get branches
    $stmt = $db->prepare("SELECT site_id, site_name, site_code FROM sites WHERE site_status = 'active' ORDER BY site_name");
    $stmt->execute();
    $branches = $stmt->fetchAll();
    
    // Get roles
    $stmt = $db->prepare("SELECT role_id, role_name, role_code FROM roles ORDER BY role_name");
    $stmt->execute();
    $roles = $stmt->fetchAll();
    
    // Get all permissions grouped by module
    $stmt = $db->prepare("
        SELECT permission_id, permission_code, permission_name, permission_module
        FROM permissions
        ORDER BY permission_module, permission_name
    ");
    $stmt->execute();
    $allPermissions = $stmt->fetchAll();
    
    // Group permissions by module
    $permissionsByModule = [];
    foreach ($allPermissions as $perm) {
        $module = $perm['permission_module'];
        if (!isset($permissionsByModule[$module])) {
            $permissionsByModule[$module] = [];
        }
        $permissionsByModule[$module][] = $perm;
    }
    
    // Get branch-specific permissions if branch and role selected
    $branchPermissions = [];
    if ($selectedSiteId > 0 && $selectedRoleId > 0) {
        // Check if table exists
        $stmt = $db->query("SHOW TABLES LIKE 'site_role_permissions'");
        if ($stmt->rowCount() > 0) {
            $stmt = $db->prepare("SELECT permission_id FROM site_role_permissions WHERE site_id = ? AND role_id = ?");
            $stmt->execute([$selectedSiteId, $selectedRoleId]);
            $branchPermissions = $stmt->fetchAll(PDO::FETCH_COLUMN);
        }
    }
    
    // Get default role permissions (from role_permissions table)
    $defaultRolePermissions = [];
    if ($selectedRoleId > 0) {
        $stmt = $db->prepare("SELECT permission_id FROM role_permissions WHERE role_id = ?");
        $stmt->execute([$selectedRoleId]);
        $defaultRolePermissions = $stmt->fetchAll(PDO::FETCH_COLUMN);
    }
    
} catch (Exception $e) {
    error_log("Error loading data: " . $e->getMessage());
    $branches = [];
    $roles = [];
    $permissionsByModule = [];
    $branchPermissions = [];
    $defaultRolePermissions = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Branch-wise Permission Management</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/permissions.php" class="btn btn-secondary">Permission Setup</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles.php" class="btn btn-secondary">Role Management</a>
        </div>
    </div>
    
    <?php if ($success): ?>
    <div class="alert alert-success" style="margin-top: 20px;">
        Branch permissions updated 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; ?>
    
    <!-- Branch and Role Selection -->
    <div style="margin-top: 20px; padding: 20px; background: #f9fafb; border-radius: 8px; margin-bottom: 30px;">
        <h3 style="margin-bottom: 15px;">Select Branch and Role</h3>
        <form method="GET" style="display: grid; grid-template-columns: 2fr 2fr 1fr; gap: 15px; align-items: end;">
            <div class="form-group">
                <label class="form-label" for="site_id">Select Branch *</label>
                <select id="site_id" name="site_id" class="form-control" required onchange="this.form.submit()">
                    <option value="">-- Select Branch --</option>
                    <?php foreach ($branches as $branch): ?>
                    <option value="<?php echo $branch['site_id']; ?>" 
                            <?php echo $selectedSiteId == $branch['site_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($branch['site_name']); ?> (<?php echo htmlspecialchars($branch['site_code']); ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="role_id">Select Role *</label>
                <select id="role_id" name="role_id" class="form-control" required onchange="this.form.submit()">
                    <option value="">-- Select Role --</option>
                    <?php foreach ($roles as $role): ?>
                    <option value="<?php echo $role['role_id']; ?>" 
                            <?php echo $selectedRoleId == $role['role_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($role['role_name']); ?> (<?php echo htmlspecialchars($role['role_code']); ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <button type="submit" class="btn btn-primary" style="width: 100%;">Load Permissions</button>
            </div>
        </form>
    </div>
    
    <!-- Permission Assignment Form -->
    <?php if ($selectedSiteId > 0 && $selectedRoleId > 0): ?>
    <form method="POST" id="permissionForm">
        <input type="hidden" name="site_id" value="<?php echo $selectedSiteId; ?>">
        <input type="hidden" name="role_id" value="<?php echo $selectedRoleId; ?>">
        
        <div style="margin-bottom: 20px; padding: 15px; background: #e0f2fe; border-radius: 6px;">
            <p style="margin: 0; color: #0369a1;">
                <strong>Note:</strong> Branch-specific permissions will override default role permissions for this branch only. 
                If no branch-specific permissions are set, default role permissions will apply.
            </p>
        </div>
        
        <div style="margin-top: 30px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <h3>Assign Permissions for Selected Branch</h3>
                <div>
                    <button type="button" onclick="selectAllPermissions()" class="btn btn-sm btn-secondary">Select All</button>
                    <button type="button" onclick="deselectAllPermissions()" class="btn btn-sm btn-secondary">Deselect All</button>
                    <button type="button" onclick="useDefaultPermissions()" class="btn btn-sm btn-primary">Use Default Role Permissions</button>
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
                <?php foreach ($permissionsByModule as $module => $permissions): ?>
                <div style="padding: 15px; background: #f9fafb; border-radius: 8px; border: 2px solid #e5e7eb;">
                    <h4 style="margin-bottom: 10px; text-transform: uppercase; color: var(--primary-color); display: flex; align-items: center; gap: 8px;">
                        <span><?php echo htmlspecialchars($module); ?></span>
                        <span style="font-size: 12px; color: var(--text-secondary); font-weight: normal;">
                            (<?php echo count($permissions); ?> permissions)
                        </span>
                    </h4>
                    <?php foreach ($permissions as $perm): 
                        $isChecked = in_array($perm['permission_id'], $branchPermissions);
                        $isDefault = in_array($perm['permission_id'], $defaultRolePermissions);
                    ?>
                    <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px; cursor: pointer; padding: 5px; border-radius: 4px; transition: background 0.2s;"
                           onmouseover="this.style.background='#f3f4f6'"
                           onmouseout="this.style.background='transparent'">
                        <input type="checkbox" 
                               name="permissions[]" 
                               value="<?php echo $perm['permission_id']; ?>"
                               class="permission-checkbox"
                               data-permission-id="<?php echo $perm['permission_id']; ?>"
                               <?php echo $isChecked ? 'checked' : ''; ?>>
                        <span style="flex: 1;">
                            <?php echo htmlspecialchars($perm['permission_name']); ?>
                            <?php if ($isDefault && !$isChecked): ?>
                            <span style="font-size: 10px; color: #6b7280;">(Default)</span>
                            <?php endif; ?>
                        </span>
                        <span style="font-size: 10px; color: #9ca3af;">
                            <?php echo htmlspecialchars($perm['permission_code']); ?>
                        </span>
                    </label>
                    <?php endforeach; ?>
                </div>
                <?php endforeach; ?>
            </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/branch_permissions.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" name="save_permissions" class="btn btn-primary">Save Branch Permissions</button>
        </div>
    </form>
    <?php else: ?>
    <div style="padding: 40px; text-align: center; background: #f9fafb; border-radius: 8px; color: #6b7280;">
        <div style="font-size: 48px; margin-bottom: 15px;">🔐</div>
        <h3>Select Branch and Role</h3>
        <p>Please select a branch and role above to manage permissions.</p>
    </div>
    <?php endif; ?>
</div>

<script>
function selectAllPermissions() {
    document.querySelectorAll('.permission-checkbox').forEach(cb => cb.checked = true);
}

function deselectAllPermissions() {
    document.querySelectorAll('.permission-checkbox').forEach(cb => cb.checked = false);
}

function useDefaultPermissions() {
    // Get default permissions from PHP (we'll need to pass them via data attribute)
    const defaultPerms = <?php echo json_encode($defaultRolePermissions); ?>;
    
    // First deselect all
    deselectAllPermissions();
    
    // Then select only default permissions
    defaultPerms.forEach(permId => {
        const checkbox = document.querySelector(`.permission-checkbox[data-permission-id="${permId}"]`);
        if (checkbox) {
            checkbox.checked = true;
        }
    });
}

// Auto-submit when branch/role changes
document.getElementById('site_id')?.addEventListener('change', function() {
    if (this.value && document.getElementById('role_id').value) {
        // this.form.submit(); // Already handled by onchange
    }
});

document.getElementById('role_id')?.addEventListener('change', function() {
    if (this.value && document.getElementById('site_id').value) {
        // this.form.submit(); // Already handled by onchange
    }
});
</script>

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

