<?php
// api/users/item.php

require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';
require_once '../../helpers/request.php';
require_once '../../helpers/auth.php';

$method = getRequestMethod();

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$user = requireAdmin();

$id = isset($_GET['id']) ? intval($_GET['id']) : null;

if (!$id) {
    sendError('User ID required', 400);
}

// GET - Single user
if ($method === 'GET') {
    try {
        $stmt = $pdo->prepare("
            SELECT u.id, u.name, u.email, u.role_id, u.status, u.created_at, r.name as role_name
            FROM users u
            LEFT JOIN roles r ON r.id = u.role_id
            WHERE u.id = :id
        ");
        $stmt->execute([':id' => $id]);
        $userData = $stmt->fetch();
        
        if (!$userData) {
            sendError('User not found', 404);
        }
        
        sendSuccess($userData);
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
// PUT - Update user
} elseif ($method === 'PUT') {
    $data = getRequestData();
    
    try {
        // Check if user exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE id = :id");
        $stmt->execute([':id' => $id]);
        if (!$stmt->fetch()) {
            sendError('User not found', 404);
        }
        
        $updates = [];
        $params = [':id' => $id];
        
        if (isset($data['name'])) {
            $updates[] = "name = :name";
            $params[':name'] = $data['name'];
        }
        
        if (isset($data['role_id'])) {
            $updates[] = "role_id = :role_id";
            $params[':role_id'] = $data['role_id'];
        }
        
        if (isset($data['status'])) {
            $allowed_status = ['active', 'pending', 'blocked'];
            if (!in_array($data['status'], $allowed_status)) {
                sendError('Invalid status', 400);
            }
            $updates[] = "status = :status";
            $params[':status'] = $data['status'];
        }
        
        if (isset($data['password']) && !empty($data['password'])) {
            $updates[] = "password = :password";
            $params[':password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        
        if (empty($updates)) {
            sendError('No fields to update', 400);
        }
        
        $sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        sendSuccess(null, 'User updated successfully');
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
// DELETE - Remove user
} elseif ($method === 'DELETE') {
    try {
        // Check if user exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE id = :id");
        $stmt->execute([':id' => $id]);
        if (!$stmt->fetch()) {
            sendError('User not found', 404);
        }
        
        // Prevent deleting yourself
        $currentUser = requireAdmin();
        if ($currentUser['id'] == $id) {
            sendError('Cannot delete your own account', 400);
        }
        
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
        $stmt->execute([':id' => $id]);
        
        sendSuccess(null, 'User deleted successfully');
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
} else {
    sendError('Method not allowed', 405);
}
?>