<?php
/**
 * Seed HR Admin Permissions
 * Run this script to ensure HR Admin has all required permissions
 */

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

// Only Super Admin can run this
if (!isSuperAdmin()) {
    die('Only Super Admin can run this script.');
}

$db = getDB();
$db->beginTransaction();

try {
    $messages = [];
    
    // Get HR Admin role_id (assuming role_code = 'HR_ADMIN')
    $stmt = $db->prepare("SELECT role_id FROM roles WHERE role_code = 'HR_ADMIN' LIMIT 1");
    $stmt->execute();
    $hrRole = $stmt->fetch();
    
    if (!$hrRole) {
        throw new Exception("HR_ADMIN role not found!");
    }
    
    $hrRoleId = $hrRole['role_id'];
    $messages[] = "HR Admin Role ID: {$hrRoleId}";
    
    // Required permissions for HR Admin
    $requiredPermissions = [
        'USER_ROLE_ASSIGN' => 'Assign Roles to Users',
        'ATTENDANCE_VIEW' => 'View Attendance',
        'ATTENDANCE_CREATE' => 'Create Attendance',
        'ATTENDANCE_EDIT' => 'Edit Attendance',
        'ATTENDANCE_REPORT' => 'Generate Attendance Reports',
    ];
    
    // Add missing permissions
    foreach ($requiredPermissions as $code => $name) {
        $stmt = $db->prepare("SELECT permission_id FROM permissions WHERE permission_code = ?");
        $stmt->execute([$code]);
        $permission = $stmt->fetch();
        
        if (!$permission) {
            // Insert permission
            $stmt = $db->prepare("
                INSERT INTO permissions (permission_code, permission_name, permission_module, permission_description)
                VALUES (?, ?, ?, ?)
            ");
            $module = strpos($code, 'ATTENDANCE') !== false ? 'attendance' : 'user';
            $description = $code === 'USER_ROLE_ASSIGN' 
                ? 'Allow assigning roles to users/employees' 
                : 'HR Admin permission for ' . strtolower(str_replace('_', ' ', $code));
            $stmt->execute([$code, $name, $module, $description]);
            $permissionId = $db->lastInsertId();
            $messages[] = "✓ Added permission: {$code}";
        } else {
            $permissionId = $permission['permission_id'];
        }
        
        // Assign to HR Admin if not already assigned
        $stmt = $db->prepare("
            SELECT role_permission_id FROM role_permissions 
            WHERE role_id = ? AND permission_id = ?
        ");
        $stmt->execute([$hrRoleId, $permissionId]);
        if (!$stmt->fetch()) {
            $stmt = $db->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
            $stmt->execute([$hrRoleId, $permissionId]);
            $messages[] = "✓ Assigned permission: {$code} to HR Admin";
        } else {
            $messages[] = "✓ Permission already assigned: {$code}";
        }
    }
    
    $db->commit();
    
    echo "<h2>HR Admin Permissions Seeded Successfully!</h2>";
    echo "<ul>";
    foreach ($messages as $msg) {
        echo "<li>{$msg}</li>";
    }
    echo "</ul>";
    echo "<p><a href='" . BASE_URL . "/admin/users.php'>Back to Users</a></p>";
    
} catch (Exception $e) {
    $db->rollBack();
    echo "<h2>Error!</h2>";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<p><a href='" . BASE_URL . "/admin/users.php'>Back to Users</a></p>";
}

