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

$userModel = new User($pdo);

// مسیر و متد را بخوان
$method = $_SERVER['REQUEST_METHOD'];
$path = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
$resource = $path[count($path) - 1];

// مسیرهای API
switch ($method) {
    case 'GET':
        echo json_encode($userModel->getAll());
        break;

    case 'POST':
        $data = json_decode(file_get_contents("php://input"), true);
        echo json_encode($userModel->create($data['name'], $data['email']));
        break;

    case 'PUT':
        $id = $path[count($path) - 1];
        $data = json_decode(file_get_contents("php://input"), true);
        echo json_encode($userModel->update($id, $data['name'], $data['email']));
        break;

    case 'DELETE':
        $id = $path[count($path) - 1];
        echo json_encode($userModel->delete($id));
        break;

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}
?>