<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name, b.branch_name, b.branch_code 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     LEFT JOIN branches b ON u.branch_id = b.branch_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
    $branch_name = $user_details['branch_name'];
    $staff_number = $user_details['staff_number'];
}

$success_message = '';
$errors = array();

// Handle role status updates
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] == 'toggle_status') {
            $role_id = $_POST['role_id'];
            $new_status = $_POST['new_status'] == '1' ? 0 : 1;
            
            $update_sql = "UPDATE user_roles SET is_active = ? WHERE role_id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param("ii", $new_status, $role_id);
            
            if ($update_stmt->execute()) {
                $success_message = "Role status updated successfully!";
                
                // Log the activity
                $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                                old_values, new_values, ip_address, user_agent) VALUES (?, 'UPDATE', 'USER_ROLE', ?, 'USER_ROLE', ?, ?, ?, ?)";
                $activity_stmt = $conn->prepare($activity_sql);
                $old_values = json_encode(['is_active' => $_POST['new_status']]);
                $new_values = json_encode(['is_active' => $new_status]);
                $ip_address = $_SERVER['REMOTE_ADDR'];
                $user_agent = $_SERVER['HTTP_USER_AGENT'];
                $activity_stmt->bind_param("iissss", $user_id, $role_id, $old_values, $new_values, $ip_address, $user_agent);
                $activity_stmt->execute();
            } else {
                $errors[] = "Error updating role status: " . $conn->error;
            }
        }
        
        if ($_POST['action'] == 'add_role') {
            $role_name = trim($_POST['role_name']);
            $description = trim($_POST['description']);
            
            if (empty($role_name)) {
                $errors[] = "Role name is required";
            } else {
                // Check if role name already exists
                $check_sql = "SELECT role_id FROM user_roles WHERE role_name = ?";
                $check_stmt = $conn->prepare($check_sql);
                $check_stmt->bind_param("s", $role_name);
                $check_stmt->execute();
                
                if ($check_stmt->get_result()->num_rows > 0) {
                    $errors[] = "Role name already exists";
                } else {
                    $insert_sql = "INSERT INTO user_roles (role_name, description, is_system, is_active) VALUES (?, ?, 0, 1)";
                    $insert_stmt = $conn->prepare($insert_sql);
                    $insert_stmt->bind_param("ss", $role_name, $description);
                    
                    if ($insert_stmt->execute()) {
                        $success_message = "Role created successfully!";
                        
                        // Log the activity
                        $new_role_id = $conn->insert_id;
                        $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                                        new_values, ip_address, user_agent) VALUES (?, 'CREATE', 'USER_ROLE', ?, 'USER_ROLE', ?, ?, ?)";
                        $activity_stmt = $conn->prepare($activity_sql);
                        $new_values = json_encode(['role_name' => $role_name, 'description' => $description]);
                        $ip_address = $_SERVER['REMOTE_ADDR'];
                        $user_agent = $_SERVER['HTTP_USER_AGENT'];
                        $activity_stmt->bind_param("iisss", $user_id, $new_role_id, $new_values, $ip_address, $user_agent);
                        $activity_stmt->execute();
                    } else {
                        $errors[] = "Error creating role: " . $conn->error;
                    }
                }
            }
        }
    }
}

// Get all roles with user counts
$roles_query = "SELECT ur.*, 
                COUNT(u.user_id) as user_count,
                COUNT(CASE WHEN u.status = 'ACTIVE' THEN 1 END) as active_users
                FROM user_roles ur 
                LEFT JOIN users u ON ur.role_id = u.role_id 
                GROUP BY ur.role_id 
                ORDER BY ur.role_name";
$roles_result = $conn->query($roles_query);

// Get role statistics
$stats_query = "SELECT 
                COUNT(*) as total_roles,
                COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_roles,
                COUNT(CASE WHEN is_system = 1 THEN 1 END) as system_roles,
                COUNT(CASE WHEN is_system = 0 THEN 1 END) as custom_roles
                FROM user_roles";
$stats_result = $conn->query($stats_query);
$stats = $stats_result->fetch_assoc();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'User Roles & Permissions - Healthcare EMR System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        /* Use the same styling from dashboard */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* Role Cards */
        .roles-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .role-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            transition: all 0.2s ease;
        }
        
        .role-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .role-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
        }
        
        .role-name {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 0.5rem 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .role-description {
            color: #64748b;
            font-size: 0.875rem;
            margin: 0;
        }
        
        .role-body {
            padding: 1.5rem;
        }
        
        .role-stats {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .role-stat {
            text-align: center;
            padding: 1rem;
            background: #f8fafc;
            border-radius: 8px;
        }
        
        .role-stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .role-stat-label {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .role-actions {
            display: flex;
            gap: 0.5rem;
            justify-content: flex-end;
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #f1f5f9; color: #475569; }
        .status-system { background: #dbeafe; color: #1d4ed8; }
        .status-custom { background: #fef3c7; color: #92400e; }
        
        /* Action Buttons */
        .btn-action {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            margin: 0 0.25rem;
            transition: all 0.2s ease;
            border: none;
            cursor: pointer;
        }
        
        .btn-primary { background: #3b82f6; color: white; }
        .btn-primary:hover { background: #1d4ed8; color: white; }
        
        .btn-success { background: #059669; color: white; }
        .btn-success:hover { background: #047857; color: white; }
        
        .btn-warning { background: #d97706; color: white; }
        .btn-warning:hover { background: #b45309; color: white; }
        
        .btn-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; color: white; }
        
        /* Add Role Form */
        .add-role-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .add-role-header {
            padding: 1.5rem;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .add-role-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .add-role-body {
            padding: 1.5rem;
        }
        
        /* Form Controls */
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        /* Alert Messages */
        .alert {
            border-radius: 8px;
            border: none;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
        }
        
        /* Buttons */
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
            color: white;
        }
        
        /* Required field indicator */
        .required {
            color: #dc2626;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .roles-grid {
                grid-template-columns: 1fr;
            }
            
            .role-stats {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">User Roles & Permissions</h1>
                        <p class="page-subtitle">Manage user roles, permissions, and access control</p>
                    </div>

                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['total_roles']; ?></div>
                            <div class="stat-label">Total Roles</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['active_roles']; ?></div>
                            <div class="stat-label">Active Roles</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['system_roles']; ?></div>
                            <div class="stat-label">System Roles</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['custom_roles']; ?></div>
                            <div class="stat-label">Custom Roles</div>
                        </div>
                    </div>

                    <!-- Messages -->
                    <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                <?php foreach ($errors as $error): ?>
                                    <li><?php echo htmlspecialchars($error); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>

                    <?php if ($success_message): ?>
                        <div class="alert alert-success">
                            <?php echo htmlspecialchars($success_message); ?>
                        </div>
                    <?php endif; ?>

                    <!-- Add Role Form -->
                    <div class="add-role-card">
                        <div class="add-role-header">
                            <h3 class="add-role-title">Add New Role</h3>
                        </div>
                        <div class="add-role-body">
                            <form method="POST" class="row g-3">
                                <input type="hidden" name="action" value="add_role">
                                <div class="col-md-4">
                                    <label class="form-label">Role Name <span class="required">*</span></label>
                                    <input type="text" class="form-control" name="role_name" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Description</label>
                                    <input type="text" class="form-control" name="description" placeholder="Brief description of the role">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="ph-plus me-1"></i> Add Role
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Roles Grid -->
                    <div class="roles-grid">
                        <?php while ($role = $roles_result->fetch_assoc()): ?>
                        <div class="role-card">
                            <div class="role-header">
                                <div class="role-name">
                                    <?php echo htmlspecialchars($role['role_name']); ?>
                                    <div>
                                        <?php if ($role['is_system']): ?>
                                            <span class="status-badge status-system">System</span>
                                        <?php else: ?>
                                            <span class="status-badge status-custom">Custom</span>
                                        <?php endif; ?>
                                        
                                        <?php if ($role['is_active']): ?>
                                            <span class="status-badge status-active">Active</span>
                                        <?php else: ?>
                                            <span class="status-badge status-inactive">Inactive</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php if ($role['description']): ?>
                                    <p class="role-description"><?php echo htmlspecialchars($role['description']); ?></p>
                                <?php endif; ?>
                            </div>
                            
                            <div class="role-body">
                                <div class="role-stats">
                                    <div class="role-stat">
                                        <div class="role-stat-value"><?php echo $role['user_count']; ?></div>
                                        <div class="role-stat-label">Total Users</div>
                                    </div>
                                    <div class="role-stat">
                                        <div class="role-stat-value"><?php echo $role['active_users']; ?></div>
                                        <div class="role-stat-label">Active Users</div>
                                    </div>
                                </div>
                                
                                <div class="role-actions">
                                    <a href="view_role_users.php?role_id=<?php echo $role['role_id']; ?>" class="btn-action btn-primary" title="View Users">
                                        <i class="ph-users"></i> Users
                                    </a>
                                    
                                    <?php if (!$role['is_system']): ?>
                                        <a href="edit_role.php?id=<?php echo $role['role_id']; ?>" class="btn-action btn-warning" title="Edit Role">
                                            <i class="ph-pencil"></i> Edit
                                        </a>
                                    <?php endif; ?>
                                    
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to <?php echo $role['is_active'] ? 'deactivate' : 'activate'; ?> this role?')">
                                        <input type="hidden" name="action" value="toggle_status">
                                        <input type="hidden" name="role_id" value="<?php echo $role['role_id']; ?>">
                                        <input type="hidden" name="new_status" value="<?php echo $role['is_active']; ?>">
                                        
                                        <?php if ($role['is_active']): ?>
                                            <button type="submit" class="btn-action btn-danger" title="Deactivate Role">
                                                <i class="ph-prohibit"></i> Deactivate
                                            </button>
                                        <?php else: ?>
                                            <button type="submit" class="btn-action btn-success" title="Activate Role">
                                                <i class="ph-check"></i> Activate
                                            </button>
                                        <?php endif; ?>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    </div>

                    <!-- Role Permissions Matrix (placeholder for future implementation) -->
                    <div class="add-role-card">
                        <div class="add-role-header">
                            <h3 class="add-role-title">Role Permissions Matrix</h3>
                        </div>
                        <div class="add-role-body">
                            <p style="color: #64748b; font-style: italic;">
                                Detailed role permissions and access control matrix will be implemented here. 
                                This will allow granular control over what each role can access and perform within the system.
                            </p>
                            <div class="mt-3">
                                <a href="role_permissions.php" class="btn btn-primary">
                                    <i class="ph-lock-key me-1"></i> Manage Permissions
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Add any JavaScript functionality here
            console.log('User Roles page loaded');
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>