<?php
header("Content-Type: application/json");
require_once "db.php"; // include your DB connection

$action = $_POST['action'] ?? $_GET['action'] ?? null;

switch ($action) {
    case "list":
        $stmt = $pdo->query("SELECT * FROM users ORDER BY created_at DESC");
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(["success" => true, "users" => $users]);
        break;

    case "get_stats":
        $total = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
        $admins = $pdo->query("SELECT COUNT(*) FROM users WHERE is_admin=1")->fetchColumn();
        $normal = $pdo->query("SELECT COUNT(*) FROM users WHERE is_admin=0")->fetchColumn();

        echo json_encode([
            "success" => true,
            "stats" => [
                "total" => $total,
                "admins" => $admins,
                "users" => $normal
            ]
        ]);
        break;

    case "add_user":
        $stmt = $pdo->prepare("INSERT INTO users (firstName,lastName,phone,email,is_admin,created_at) VALUES (?,?,?,?,?,NOW())");
        $stmt->execute([
            $_POST['firstName'],
            $_POST['lastName'],
            $_POST['phone'],
            $_POST['email'],
            0
        ]);
        echo json_encode(["success" => true, "message" => "User added"]);
        break;

    case "delete_user":
        $stmt = $pdo->prepare("DELETE FROM users WHERE id=?");
        $stmt->execute([$_POST['user_id']]);
        echo json_encode(["success" => true, "message" => "User deleted"]);
        break;

    default:
        echo json_encode(["success" => false, "error" => "Invalid action"]);
}
