<?php
header('Content-Type: application/json');
require_once 'config.php';

// Check authentication and authorization
requireRole(['Admin']);

if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
    http_response_code(405);
    die(json_encode(['error' => 'Method not allowed']));
}

$data = json_decode(file_get_contents('php://input'), true);

// Validate input
if (!isset($data['id']) || !isset($data['role'])) {
    http_response_code(400);
    die(json_encode(['error' => 'Missing required fields: id, role']));
}

// Validate role
$validRoles = ['Admin', 'Petugas', 'Pimpinan'];
if (!in_array($data['role'], $validRoles)) {
    http_response_code(400);
    die(json_encode(['error' => 'Invalid role. Must be Admin, Petugas, or Pimpinan']));
}

try {
    $db = getDB();
    
    $stmt = $db->prepare('
        UPDATE users 
        SET role = ?, updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
    ');
    $stmt->execute([$data['role'], $data['id']]);
    
    if ($stmt->rowCount() > 0) {
        http_response_code(200);
        die(json_encode([
            'success' => true,
            'message' => 'User role updated successfully'
        ]));
    } else {
        http_response_code(404);
        die(json_encode(['error' => 'User not found']));
    }
} catch (PDOException $e) {
    http_response_code(500);
    die(json_encode(['error' => 'Database error: ' . $e->getMessage()]));
}
