<?php
header('Content-Type: application/json; charset=utf-8');
session_start();

// Try to use SubAdminPageGuard only when helper is available. Otherwise
// fall back to simple admin check to avoid fatal errors during FTP sync.
if (file_exists(__DIR__ . '/helpers/subadmin_page_guard.php')) {
    require_once __DIR__ . '/helpers/subadmin_page_guard.php';
    try {
        $pageGuard = new SubAdminPageGuard('manage_users');
        // enforce that requester can edit users
        $pageGuard->enforceAction();
    } catch (Throwable $e) {
        error_log('api_update_user.php: SubAdminPageGuard failed: ' . $e->getMessage());
        // fall through to manual admin check below
    }
} else {
    // helper missing; ensure only admins can update users
    if (empty($_SESSION['user_id']) || empty($_SESSION['is_admin'])) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Access denied']);
        exit;
    }
}

$userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';

if (!$userId || !$email) { http_response_code(400); echo json_encode(['success'=>false,'message'=>'Invalid data']); exit; }

$dbPath = __DIR__ . '/db_config.php'; if (file_exists($dbPath)) require $dbPath;

// Protect primary admin from email change (optional)
$protectedEmail = 'maham11abc@gmail.com';
if (isset($conn) && $conn) {
    $stmt = @$conn->prepare('SELECT email FROM users WHERE id = ? LIMIT 1');
    if ($stmt) { $stmt->bind_param('i',$userId); $stmt->execute(); $r=$stmt->get_result(); $row=$r? $r->fetch_assoc():null; $stmt->close(); }
    $currentEmail = $row['email'] ?? null;
    if ($currentEmail === $protectedEmail && $email !== $protectedEmail) {
        echo json_encode(['success'=>false,'message'=>'Cannot modify primary admin']); exit;
    }

    // perform update
    $fields = [];
    $types = '';
    $params = [];
    if ($username !== '') { $fields[] = 'username = ?'; $types .= 's'; $params[] = $username; }
    if ($email !== '') { $fields[] = 'email = ?'; $types .= 's'; $params[] = $email; }
    if ($password !== '') { 
        $fields[] = 'password_hash = ?'; 
        $types .= 's'; 
        // Check if plain text password is enabled (from db_config.php)
        $usePlain = (isset($STORE_PLAINTEXT_PASSWORDS) && $STORE_PLAINTEXT_PASSWORDS === true);
        $finalPassword = $usePlain ? $password : password_hash($password, PASSWORD_DEFAULT);
        $params[] = $finalPassword; 
    }
    if (count($fields) > 0) {
        $sql = 'UPDATE users SET ' . implode(', ', $fields) . ' WHERE id = ?';
        $types .= 'i'; $params[] = $userId;
        $stmt = @$conn->prepare($sql);
        if ($stmt) {
            $stmt->bind_param($types, ...$params);
            $ok = $stmt->execute(); $stmt->close();
            echo json_encode(['success' => (bool)$ok]); exit;
        }
    }
    echo json_encode(['success'=>false,'message'=>'Nothing to update']); exit;
}

// JSON fallback
$usersFile = __DIR__ . '/data/users.json';
if (!file_exists($usersFile)) { echo json_encode(['success'=>false,'message'=>'No DB']); exit; }
$users = json_decode(file_get_contents($usersFile), true);
if (!is_array($users)) $users = [];
$found = false;
for ($i=0;$i<count($users);$i++) {
    if (isset($users[$i]['id']) && $users[$i]['id']==$userId) {
        if ($users[$i]['email'] === $protectedEmail && $email !== $protectedEmail) { echo json_encode(['success'=>false,'message'=>'Cannot modify primary admin']); exit; }
        if ($username !== '') $users[$i]['username'] = $username;
        if ($email !== '') $users[$i]['email'] = $email;
        if ($password !== '') $users[$i]['password'] = password_hash($password, PASSWORD_DEFAULT);
        $found = true; break;
    }
}
if ($found) { file_put_contents($usersFile, json_encode($users, JSON_PRETTY_PRINT)); echo json_encode(['success'=>true]); exit; }
echo json_encode(['success'=>false,'message'=>'User not found']); exit;

?>
