<?php
// Role and permission utilities for admin/subadmin/editor pages
// always re-evaluate roles from the database to avoid stale sessions

require_once __DIR__ . '/../db_config.php';

/**
 * Returns an associative array with boolean flags for each role.
 * Also updates $_SESSION entries to reflect the latest state.
 */
function getUserRoles() {
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    $roles = ['isAdmin' => false, 'isSubadmin' => false, 'isEditor' => false];
    $userId = $_SESSION['user_id'] ?? null;
    if (!$userId || !isset($GLOBALS['conn'])) {
        return $roles;
    }
    $conn = $GLOBALS['conn'];
    // check admins table if exists
    try {
        $tbl = $conn->query("SHOW TABLES LIKE 'admins'");
        if ($tbl && $tbl->num_rows > 0) {
            $q = $conn->query("SELECT id FROM admins WHERE user_id = " . intval($userId) . " LIMIT 1");
            if ($q && $q->num_rows > 0) {
                $roles['isAdmin'] = true;
            }
        }
    } catch (Throwable $e) {
        // ignore failures
    }
    // check subadmins table
    try {
        $q2 = $conn->query("SELECT id FROM subadmins WHERE user_id = " . intval($userId) . " LIMIT 1");
        if ($q2 && $q2->num_rows > 0) {
            $roles['isSubadmin'] = true;
        }
    } catch (Throwable $e) {}
    // check editors table
    try {
        $q3 = $conn->query("SELECT id FROM editors WHERE user_id = " . intval($userId) . " LIMIT 1");
        if ($q3 && $q3->num_rows > 0) {
            $roles['isEditor'] = true;
        }
    } catch (Throwable $e) {}

    // update session flags (clear stale values)
    $_SESSION['is_admin'] = $roles['isAdmin'];
    $_SESSION['is_subadmin'] = $roles['isSubadmin'];
    $_SESSION['is_editor'] = $roles['isEditor'];
    return $roles;
}

/**
 * Returns true if the current user is an admin.
 */
function isAdminUser() {
    $roles = getUserRoles();
    return $roles['isAdmin'];
}

/**
 * Returns true if the current user is a subadmin.
 */
function isSubadminUser() {
    $roles = getUserRoles();
    return $roles['isSubadmin'];
}

/**
 * Returns true if the current user is an editor.
 */
function isEditorUser() {
    $roles = getUserRoles();
    return $roles['isEditor'];
}

/**
 * Returns the proper dashboard URL for the current role (with safe fallback).
 */
function dashboardUrl() {
    $roles = getUserRoles();
    if ($roles['isAdmin']) return 'admin_dashboard.php';
    if ($roles['isSubadmin']) return 'subadmin_dashboard.php';
    // Editors & others go to home (editor_dashboard.php does not exist)
    // return 'admin_dashboard.php';
}

/**
 * Renders a back-to-dashboard button. Override $label text if needed.
 */
function renderBackButton($label = 'Dashboard') {
    $url = dashboardUrl();
    return '<a href="' . htmlspecialchars($url) . '" class="btn" '
         . 'style="background:#007bff; color:#fff; text-decoration:none; '
         . 'padding:8px 12px; border-radius:6px;">' . htmlspecialchars($label) . '</a>';
}
/**
 * SubAdminPageGuard Class - Enforces role-based access control for admin pages.
 * Allows: Full admins, subadmins, and editors with specific permissions.
 */
class SubAdminPageGuard {
    private $permissionKey;

    /**
     * Constructor takes a permission key (e.g., 'manage_news', 'manage_posts')
     */
    public function __construct($permissionKey) {
        $this->permissionKey = $permissionKey;
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    /**
     * Enforces view permission - redirects if user doesn't have access
     */
    public function enforceView() {
        // Check if user is logged in
        if (empty($_SESSION['user_id'])) {
            header('Location: admin_login.php');
            exit;
        }

        // Get fresh role information
        $roles = getUserRoles();

        // Admins bypass permission checks
        if ($roles['isAdmin']) {
            return true;
        }

        // Subadmins bypass permission checks
        if ($roles['isSubadmin']) {
            return true;
        }

        // Editors need specific permission for this page - check both session and database
        if ($roles['isEditor']) {
            $editorPerms = $_SESSION['editor_permissions'] ?? [];
            $permValue = $editorPerms[$this->permissionKey] ?? null;
            
            // If not in session, try to fetch from database
            if ($permValue === null && isset($GLOBALS['conn'])) {
                $conn = $GLOBALS['conn'];
                $userId = $_SESSION['user_id'] ?? null;
                if ($userId) {
                    try {
                        $query = "SELECT permissions FROM editors WHERE user_id = ? LIMIT 1";
                        $stmt = $conn->prepare($query);
                        if ($stmt) {
                            $stmt->bind_param('i', $userId);
                            $stmt->execute();
                            $result = $stmt->get_result();
                            if ($result && $row = $result->fetch_assoc()) {
                                $perms = json_decode($row['permissions'] ?? '{}', true);
                                $permValue = $perms[$this->permissionKey] ?? 'none';
                            }
                            $stmt->close();
                        }
                    } catch (Throwable $e) {
                        // Silently fail - continue anyway
                    }
                }
            }
            
            // Allow if permission is not 'none'
            if ($permValue !== 'none' && !empty($permValue)) {
                return true;
            }
        }

        // No permission - redirect to dashboard
        header('Location: ' . dashboardUrl());
        exit;
    }

    /**
     * Enforces edit permission (stricter than view)
     */
    public function enforceEdit() {
        // Check if user is logged in
        if (empty($_SESSION['user_id'])) {
            header('Location: admin_login.php');
            exit;
        }

        // Get fresh role information
        $roles = getUserRoles();

        // Admins bypass permission checks
        if ($roles['isAdmin']) {
            return true;
        }

        // Subadmins bypass permission checks
        if ($roles['isSubadmin']) {
            return true;
        }

        // Editors need 'editor' permission level for edits
        if ($roles['isEditor']) {
            $editorPerms = $_SESSION['editor_permissions'] ?? [];
            $permValue = $editorPerms[$this->permissionKey] ?? 'none';
            
            // Only allow if permission is explicitly 'editor'
            if ($permValue === 'editor') {
                return true;
            }
        }

        // No permission - redirect to dashboard
        header('Location: ' . dashboardUrl());
        exit;
    }

    /**
     * Check if user has permission for a specific action
     * Actions: 'view', 'create', 'edit', 'delete'
     */
    public function can($action = 'view') {
        $roles = getUserRoles();

        // Admins can do everything
        if ($roles['isAdmin']) {
            return true;
        }

        // Subadmins can do everything for their areas
        if ($roles['isSubadmin']) {
            return true;
        }

        // Editors have specific permissions - check both session and database
        if ($roles['isEditor']) {
            // First try session permissions
            $editorPerms = $_SESSION['editor_permissions'] ?? [];
            $permValue = $editorPerms[$this->permissionKey] ?? null;
            
            // If not in session, try to fetch from database
            if ($permValue === null && isset($GLOBALS['conn'])) {
                $conn = $GLOBALS['conn'];
                $userId = $_SESSION['user_id'] ?? null;
                if ($userId) {
                    try {
                        $query = "SELECT permissions FROM editors WHERE user_id = ? LIMIT 1";
                        $stmt = $conn->prepare($query);
                        if ($stmt) {
                            $stmt->bind_param('i', $userId);
                            $stmt->execute();
                            $result = $stmt->get_result();
                            if ($result && $row = $result->fetch_assoc()) {
                                $perms = json_decode($row['permissions'] ?? '{}', true);
                                $permValue = $perms[$this->permissionKey] ?? 'none';
                            }
                            $stmt->close();
                        }
                    } catch (Throwable $e) {
                        // Silently fail and use default
                    }
                }
            }
            
            // Viewer level can view only
            if ($action === 'view') {
                return $permValue !== 'none' && !empty($permValue);
            }
            
            // Editor level can do everything
            if ($action === 'create' || $action === 'edit' || $action === 'delete') {
                return $permValue === 'editor';
            }
        }

        return false;
    }

    /**
     * Get the current access level ('admin', 'subadmin', 'editor', 'viewer', 'none')
     */
    public function getLevel() {
        $roles = getUserRoles();

        if ($roles['isAdmin']) {
            return 'admin';
        }

        if ($roles['isSubadmin']) {
            return 'subadmin';
        }

        if ($roles['isEditor']) {
            $editorPerms = $_SESSION['editor_permissions'] ?? [];
            $permValue = $editorPerms[$this->permissionKey] ?? 'none';
            
            if ($permValue === 'editor') {
                return 'editor';
            }
            if ($permValue !== 'none' && !empty($permValue)) {
                return 'viewer';
            }
        }

        return 'none';
    }
}