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

header('Content-Type: application/json');

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Insufficient permissions']);
    exit;
}

try {
    $user_id = $_POST['user_id'];
    $username = $_POST['username'];
    $email = $_POST['email'];
    $full_name = $_POST['full_name'];
    $role_id = $_POST['role_id'];

    // Check if email is unique (except for current user)
    $sql = "SELECT user_id FROM users WHERE email = ? AND user_id != ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('si', $email, $user_id);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        throw new Exception('Email address is already in use');
    }

    // Update user
    $sql = "UPDATE users SET 
            username = ?,
            email = ?,
            full_name = ?,
            role_id = ?,
            modified_by = ?,
            modified_at = NOW()
            WHERE user_id = ?";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('sssiii', $username, $email, $full_name, $role_id, $_SESSION['user_id'], $user_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update user information');
    }

    // Log the update
    $sql = "INSERT INTO activity_log (
        user_id, 
        action, 
        table_name, 
        record_id, 
        new_values,
        ip_address,
        user_agent,
        action_date
    ) VALUES (?, 'UPDATE', 'users', ?, ?, ?, ?, NOW())";

    $new_values = json_encode([
        'username' => $username,
        'email' => $email,
        'full_name' => $full_name,
        'role_id' => $role_id
    ]);

    $stmt = $conn->prepare($sql);
    $stmt->bind_param('iisss', 
        $_SESSION['user_id'], 
        $user_id,
        $new_values,
        $_SERVER['REMOTE_ADDR'],
        $_SERVER['HTTP_USER_AGENT']
    );
    $stmt->execute();

    echo json_encode([
        'success' => true,
        'message' => 'User information updated successfully'
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'error' => $e->getMessage()
    ]);
}
?>