<?php
/**
 * Enterprise HRM ERP System - Delete Custom Role
 */

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 delete roles. Your role: ' . ($roleCode ?: 'Unknown');
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$roleId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($roleId <= 0) {
    redirect(BASE_URL . '/admin/roles.php', 'Invalid role ID.', 'error');
}

try {
    $db = getDB();
    
    // Check if role exists and is custom (not system role)
    $stmt = $db->prepare("SELECT role_id, role_code, is_system_role FROM roles WHERE role_id = ?");
    $stmt->execute([$roleId]);
    $role = $stmt->fetch();
    
    if (!$role) {
        redirect(BASE_URL . '/admin/roles.php', 'Role not found.', 'error');
    }
    
    if ($role['is_system_role']) {
        redirect(BASE_URL . '/admin/roles.php', 'System roles cannot be deleted.', 'error');
    }
    
    // Check if any users have this role
    $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE role_id = ?");
    $stmt->execute([$roleId]);
    $userCount = $stmt->fetchColumn();
    
    if ($userCount > 0) {
        redirect(BASE_URL . '/admin/roles.php', 'Cannot delete role. ' . $userCount . ' user(s) are assigned this role.', 'error');
    }
    
    // Delete role permissions first
    $stmt = $db->prepare("DELETE FROM role_permissions WHERE role_id = ?");
    $stmt->execute([$roleId]);
    
    // Delete role
    $stmt = $db->prepare("DELETE FROM roles WHERE role_id = ?");
    $stmt->execute([$roleId]);
    
    logAudit('DELETE', 'roles', $roleId);
    
    redirect(BASE_URL . '/admin/roles.php', 'Role deleted successfully.');
    
} catch (Exception $e) {
    error_log("Error deleting role: " . $e->getMessage());
    redirect(BASE_URL . '/admin/roles.php', 'Error deleting role.', 'error');
}

